服务器之家

服务器之家 > 正文

python 日志增量抓取实现方法

时间:2021-02-07 00:14     来源/作者:码农少抽烟

实例如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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 日志增量抓取实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/tiankai517/article/details/50549395

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部