julley 发表于 2018-8-14 07:56:40

python实时过滤日志脚本

  大神指导作品:
  #!/usr/bin/python
  #coding:utf8
  from functools import wraps
  from time import sleep
  import os
  RESTART='pm2 restart ios-push'
  # coroutine 先要用 next 语句调用一次
  def coroutine(fn):
  @wraps(fn)
  def wrapper(*args,**kwargs):
  ret=fn(*args,**kwargs)
  next(ret)
  return ret
  return wrapper
  def follow(file,target):
  '''
  类似 Unix 的 tail -f, 但是接受一个 target, 有新的数据,交给 target 处理
  '''
  file.seek(0,2)# 直接到文件的最后一行,类似 tail -f -n 0
  while True:
  line=file.readline()#读取行
  if not line:
  sleep(0.5)# 如果是空行,直接 sleep 0.5s,然后 continue
  continue
  target.send(line)# 如果有新数据,则交给 target 处理
  def action():
  if os.system(RESTART) == 0:
  print('ios-push restart success!')
  #print('restart')
  @coroutine
  def grep(pattern):
  '''
  grep 是一个 coroutine,接受一个 pattern 参数,需要从外部 send 数据 ,如果接受的数据匹配 pattern 通过了,则调用action函数
  '''
  while True:
  line = yield
  if pattern in line:
  action()
  if __name__ == '__main__':
  follow(open('error.log','r'),grep('MaxListenersExceededWarn'))
页: [1]
查看完整版本: python实时过滤日志脚本