python监视日志文件不阻塞

2024-05-28 19:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个测试存根,它会将几个日志消息写入系统日志。

但是,这个系统日志也会被许多其他应用程序更新。所以,基本上,我想做一个tail -f system.log | grep "application name"来只获取适当的日志消息。

我在研究dbaez生成器技巧,并试图将http://www.dabeaz.com/generators/follow.pyhttp://www.dabeaz.com/generators/apachelog.py两者结合起来

所以,在我的__main__()中,我有这样的东西:

try:
   dosomeprocessing()     #outputs stuff to the log file

在dosomeprocessing()中,我运行一个循环,对于每个循环,我想看看是否有任何新的日志消息是由我的应用程序引起的,不一定要打印出来,而是将它们存储在某个地方进行验证。

    logfile = open("/var/adm/messages","r")
    loglines = follow(logfile)
    logpats = r'I2G(JV)'
    logpat = re.compile(logpats)
    groups = (logpat.match(line) for line in loglines)
    for g in groups:
        if g:
            print g.groups()

日志看起来像:

Feb  4 12:55:27 Someprocessname.py I2G(JV)-300[20448]: [ID 702911   local2.error] [MSG-70047] xxxxxxxxxxxxxxxxxxxxxxx 
 Feb  4 12:55:27 Someprocessname.py I2G(JV)-300[20448]: [ID 702911  local2.error] [MSG-70055] xxxxxxxxxxxxxxxxxxxxxxx

除了很多其他的垃圾书。

现在,它被困在小组中:

我对python和异步编程还比较陌生。理想情况下,我希望尾部能够与主进程并行运行,并在每个循环中读取新数据。

如果我需要补充更多信息,请告诉我。


Tags: pycomlog应用程序http消息wwwgroups
1条回答
网友
1楼 · 发布于 2024-05-28 19:39:49

我建议您使用watchdogpyinotify来监视对日志文件的更改。

另外,我建议你记住上次读到的位置。在收到修改通知后,您可以从最后一个位置读取到文件末尾,然后再次应用循环。另外,如果最后一个位置大于文件大小,则将其重置为0,以防文件被截断。

以下是示例:

import pyinotify
import re
import os


wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY


class EventHandler (pyinotify.ProcessEvent):

    def __init__(self, file_path, *args, **kwargs):
        super(EventHandler, self).__init__(*args, **kwargs)
        self.file_path = file_path
        self._last_position = 0
        logpats = r'I2G\(JV\)'
        self._logpat = re.compile(logpats)

    def process_IN_MODIFY(self, event):
        print "File changed: ", event.pathname
        if self._last_position > os.path.getsize(self.file_path):
            self._last_position = 0
        with open(self.file_path) as f:
            f.seek(self._last_position)
            loglines = f.readlines()
            self._last_position = f.tell()
            groups = (self._logpat.search(line.strip()) for line in loglines)
            for g in groups:
                if g:
                    print g.string


handler = EventHandler('some_log.log')
notifier = pyinotify.Notifier(wm, handler)

wm.add_watch(handler.file_path, mask)        
notifier.loop()

相关问题 更多 >

    热门问题