栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

检测日志文件旋转(在监视日志文件进行修改的同时)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

检测日志文件旋转(在监视日志文件进行修改的同时)

使用e4c5的答案,我得到了这段代码,该代码还解决了

readline()
每秒调用多次的问题。

在第一次调用期间,它会跳到文件末尾并等待修改。移动文件后,它将重新打开文件并读取全部内容,然后开始等待。

import osimport timeimport tracebackimport threadingimport inotify.adapterslogfile = b'/var/log/auth.log'#logfile = b'logfile.log'##################################################################def process(line, history=False):  if history:    print '=', line.strip('n')  else:    print '>', line.strip('n')##################################################################from_beginning = Falsenotifier = inotify.adapters.Inotify()while True:  try:    #------------------------- check    if not os.path.exists(logfile):      print 'logfile does not exist'      time.sleep(1)      continue    print 'opening and starting to watch', logfile    #------------------------- open    file = open(logfile, 'r')    if from_beginning:      for line in file.readlines():        process(line, history=True)    else:      file.seek(0,2)      from_beginning = True    #------------------------- watch    notifier.add_watch(logfile)    try:      for event in notifier.event_gen():        if event is not None:          (header, type_names, watch_path, filename) = event          if set(type_names) & set(['IN_MOVE_SELF']): # moved print 'logfile moved' notifier.remove_watch(logfile) file.close() time.sleep(1) break          elif set(type_names) & set(['IN_MODIFY']): # modified for line in file.readlines():   process(line, history=False)    except (KeyboardInterrupt, SystemExit):      raise    except:      notifier.remove_watch(logfile)      file.close()      time.sleep(1)    #-------------------------  except (KeyboardInterrupt, SystemExit):    break  except inotify.calls.InotifyError:    time.sleep(1)  except IOError:    time.sleep(1)  except:    traceback.print_exc()    time.sleep(1)##################################################################


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/405688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号