Python - 如何获取日志附加内容

我使用看门狗来查看日志的更改,但我无法从看门狗 API 参考中获取附加内容。还有其他方法可以实现这一点吗?


from watchdog.observers import Observer

from watchdog.events import FileSystemEventHandler

import time

import os


class MyHandler(FileSystemEventHandler):

    def on_modified(self, event):

        if event.src_path == ".\\test.log":

            # how to get append content from the log


if __name__ == "__main__":

    event_handler = MyHandler()

    observer = Observer()

    observer.schedule(event_handler, path='.', recursive=False)

    observer.start()

    try:

        while True:

            time.sleep(1)

    except KeyboardInterrupt:

        observer.stop()


胡子哥哥
浏览 89回答 1
1回答

LEATH

据我所知Watchdog,仅通知文件是否已修改,但它不会提供更改的信息,您必须自行检查。我看到了两种显示新附加内容的方法。首先:保持打开的文件,然后read()将只读取新内容。我的处理程序获取文件名作为参数以在启动时打开它并始终保持打开状态。在__init__您可以使用read()跳过现有内容import osimport timefrom watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandlerclass AppendEventHandler(FileSystemEventHandler):    def __init__(self, path):        self.path = path        self.fh = open(path)        self.fh.read() # skip existing content    def on_modified(self, event):        if event.src_path == self.path:            print(self.fh.read())if __name__ == "__main__":    event_handler = AppendEventHandler(".\\test.log")    observer = Observer()    observer.schedule(event_handler, ".", recursive=True)    observer.start()    try:        while True:            time.sleep(1)    except KeyboardInterrupt:        observer.stop()    observer.join()第二:如果您不想保留打开的文件,那么您可以记住它的大小并fh.seek(previous_size)在附加内容开始时使用它来开始阅读。import osimport timefrom watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandlerclass AppendEventHandler(FileSystemEventHandler):    def __init__(self, path):        self.path = path        self.size = os.stat(path).st_size # remeber previous size    def on_modified(self, event):        if event.src_path == self.path:            new_size = os.stat(self.path).st_size # get new size             if new_size > self.size:                 fh = open(self.path)                fh.seek(self.size) # move to appended content (move to end of old content)                print(fh.read())                fh.close()                self.size = new_size # remeber new size        if __name__ == "__main__":    event_handler = AppendEventHandler("./test.log")    observer = Observer()    observer.schedule(event_handler, ".", recursive=True)    observer.start()    try:        while True:            time.sleep(1)    except KeyboardInterrupt:        observer.stop()    observer.join()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python