从日志文件中读取,因为它是使用python编写的

Ano*_*non 47 python file-io logging monitoring file

我正试图找到一种使用python实时读取日志文件的好方法.我想在写入时一次处理一个日志文件中的行.不知何故,我需要继续尝试读取文件,直到它被创建,然后继续处理行,直到我终止进程.有没有合适的方法来做到这一点?谢谢.

Way*_*ner 46

从第38页开始查看此PDF,〜幻灯片I-77,您将找到所需的所有信息.当然其余的幻灯片也很棒,但那些专门处理你的问题:

import time
def follow(thefile):
    thefile.seek(0,2) # Go to the end of the file
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1) # Sleep briefly
            continue
        yield line
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这将跳过日志文件中已有的任何内容,只打印创建此迭代器后创建的"新"条目.那个PDF真的是一个金矿;) (6认同)
  • 如果我观看轮换日志文件该怎么办?/sf/ask/3108548411/ (3认同)

Pab*_*ruz 26

你可以尝试这样的事情:

import time

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline
Run Code Online (Sandbox Code Playgroud)

这里提取实例.

  • `file` 在此上下文中似乎未定义,仅供参考。 (2认同)

R4P*_*43L 5

由于这是Python和日志记录标记,还有另一种可能性.

我假设这是基于Python记录器,基于logging.Handler.

您可以创建一个获取(命名)记录器实例的类并覆盖该emit函数以将其放入GUI(如果您需要控制台,只需将控制台处理程序添加到文件处理程序)

例:

import logging

class log_viewer(logging.Handler):
    """ Class to redistribute python logging data """

    # have a class member to store the existing logger
    logger_instance = logging.getLogger("SomeNameOfYourExistingLogger")

    def __init__(self, *args, **kwargs):
         # Initialize the Handler
         logging.Handler.__init__(self, *args)

         # optional take format
         # setFormatter function is derived from logging.Handler 
         for key, value in kwargs.items():
             if "{}".format(key) == "format":
                 self.setFormatter(value)

         # make the logger send data to this class
         self.logger_instance.addHandler(self)

    def emit(self, record):
        """ Overload of logging.Handler method """

        record = self.format(record)

        # ---------------------------------------
        # Now you can send it to a GUI or similar
        # "Do work" starts here.
        # ---------------------------------------

        # just as an example what e.g. a console
        # handler would do:
        print(record)
Run Code Online (Sandbox Code Playgroud)

我目前正在使用类似的代码添加一个TkinterTreectrl.Multilistbox,用于在运行时查看记录器输出.

Off-Side:记录器只在初始化时获取数据,因此如果您想要提供所有数据,则需要在一开始就对其进行初始化.(我知道这是预期的,但我认为值得一提.)