今天就跟大家聊聊有关怎么在python中实现日志增量抓取,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
python的五大特点是什么
python的五大特点:1.简单易学,开发程序时,专注的是解决问题,而不是搞明白语言本身。2.面向对象,与其他主要的语言如C++和Java相比, Python以一种非常强大又简单的方式实现面向对象编程。3.可移植性,Python程序无需修改就可以在各种平台上运行。4.解释性,Python语言写的程序不需要编译成二进制代码,可以直接从源代码运行程序。5.开源,Python是 FLOSS(自由/开放源码软件)之一。
实例如下所示:
import time
import pickle
import os
import re
class LogIncScaner(object):
def __init__(self,log_file, reg_ex,seek_file='/tmp/log-inc-scan.seek.temp'):
self.log_file = log_file
self.reg_ex = reg_ex
self.seek_file = seek_file
def scan(self):
seek = self._get_seek()
file_mtime = os.path.getmtime(self.log_file)
if file_mtime <= seek['time']:
print 'file mtime not change since last scan'
seek['time'] = file_mtime
self._dump_seek(seek)
return []
file_size = os.path.getsize(self.log_file)
if file_size <= seek['position']:
print 'file size not change since last scan'
seek['position'] = file_size
self._dump_seek(seek)
return []
print 'file changed,start to scan'
matchs = []
with open(self.log_file, 'rb') as logfd:
logfd.seek(seek['position'],os.SEEK_SET)
for match in re.finditer(self.reg_ex, logfd.read()):
matchs.append(match)
seek = {'time':time.time(),'position': logfd.tell()}
print seek
self._dump_seek(seek)
return matchs
def _get_seek(self):
seek = {'time':time.time(),'position':0}
if os.path.exists(self.seek_file):
with open(self.seek_file,'rb') as seekfd:
try:
seek = pickle.load(seekfd)
except:
pass
print seek
return seek
def _dump_seek(self, seek):
with open(self.seek_file,'wb') as seekfd:
pickle.dump(seek,seekfd)
def reset_seek(self):
self._dump_seek({'time':time.time(),'position':0})
if __name__ == "__main__":
scaner = LogIncScaner('/var/log/messages',r'(\w+ \d+ \d+:\d+:\d+) .+?exception')
scaner.reset_seek()
while True:
matchs = scaner.scan()
for match in matchs:
print 'fond at:' + match.group(1) + ' content:' + match.group(0)
time.sleep(5)
看完上述内容,你们对怎么在python中实现日志增量抓取有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注天达云行业资讯频道,感谢大家的支持。