python 日志增量抓取实现方法

yipeiwu_com6年前Python爬虫

实例如下所示:

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 日志增量抓取实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python利用beautifulSoup实现爬虫

以前讲过利用phantomjs做爬虫抓网页 /post/55789.htm 是配合选择器做的 利用 beautifulSoup(文档 :http://www.crummy.com/sof...

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

Python使用Srapy框架爬虫模拟登陆并抓取知乎内容

一、Cookie原理 HTTP是无状态的面向连接的协议, 为了保持连接状态, 引入了Cookie机制 Cookie是http消息头中的一种属性,包括: Cookie名字(Name)...

python爬取网站数据保存使用的方法

编码问题因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了。问题要从文字的编码讲起。原本的英文编码只有0~255,刚好是8位1个字节。为了表示各种不同的语言,自...

Python 爬虫之超链接 url中含有中文出错及解决办法

Python 爬虫之超链接 url中含有中文出错及解决办法 python3.5 爬虫错误: UnicodeEncodeError: 'ascii' codec can't encod...

使用Scrapy爬取动态数据

使用Scrapy爬取动态数据

对于动态数据的爬取,可以选择selenium和PhantomJS两种方式,本文选择的是PhantomJS。 网址: https://s.taobao.com/search?q=笔记本电...