python 使用 watchdog 实现类似 Linux 中 tail -f 的功能

简介: python 使用 watchdog 实现类似 Linux 中 tail -f 的功能

一、代码实现


import logging
import os
import threading
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
logger = logging.getLogger(__name__)
class LogWatcher(FileSystemEventHandler):
    def __init__(self, log_file, on_modified_callback=None):
        """"
        初始化 LogWatcher 类的实例。
        参数:
        - log_file:日志文件的路径
        - on_modified_callback:可选的回调函数,在文件修改时调用
        属性:
        - log_file:日志文件的路径
        - file_object:日志文件对象
        - on_modified_callback:文件修改回调函数
        - last_line:最后一行文本
        - observer:观察者对象
        - match_string:需要匹配的字符串
        - stop_watching:停止监视的标志
        """
        self.log_file = log_file
        self.file_object = open(log_file, 'rb')
        self.on_modified_callback = on_modified_callback
        self.last_line = self.get_last_line()  # 初始化时获取最后一行文本
        self.observer = Observer()
        self.observer.schedule(self, ".", recursive=False)
        self.match_string = None
        self.stop_watching = False
    def start(self):
        """
        启动观察者对象,开始监视文件变化。
        """
        self.observer.start()
    def stop(self):
        """
        停止观察者对象,结束监视文件变化。
        """
        self.observer.stop()
        self.observer.join()
        self.file_object.close()
    def get_last_line(self):
        """
        获取日志文件的最后一行文本。它通过将文件指针移动到文件末尾,然后逐个字符向前搜索,直到找到换行符为止。
        返回值:
        - 最后一行文本,如果文件为空则返回None
        """
        # 将文件指针移动到文件末尾
        self.file_object.seek(0, os.SEEK_END)
        # 获取当前文件指针的位置(此时指针在最后一行的末尾)
        position = self.file_object.tell()
        try:
            # 尝试向前移动两个字节
            new_position = max(position - 2, 0)
            self.file_object.seek(new_position, os.SEEK_SET)
        except OSError as e:
            # 如果发生错误,可能是文件太小,返回None
            return None
        # 逐个字符向前搜索,确保文件指针最终停在当前行的第一个字符处
        while True:
            # read(1)读取的是指针位置的下一个字符,每次调用read(1)都会读取一个字符,并将指针向后移动一个字符的位置。
            char = self.file_object.read(1).decode('utf-8', errors='ignore')
            if char == '\n':
                break
            if new_position == 0:
                # 如果已经到达文件开头,跳出循环
                break
            # 尝试向前移动一个字节位置,确保不越界到文件开头
            new_position = max(new_position - 1, 0)
            # 将文件指针移动到新的位置
            self.file_object.seek(new_position, os.SEEK_SET)
        # last_line = self.file_object.readline().decode('utf-8', errors='ignore').strip()
        last_line = self.file_object.read(position - new_position).decode('utf-8', errors='ignore').strip()
        # 输出调试信息
        logger.debug(f'Reading line: {last_line}')
        return last_line
    def on_modified(self, event):
        """
        on_modified方法是FileSystemEventHandler的回调方法,当日志文件发生变化时,都会调用这个方法。
        参数:
        - event:文件变化事件对象
        """
        # 注意,这里一个要用绝对路径比较,不能直接使用 event.src_path == self.log_file,
        # event.src_path == self.log_file 的值为false
        # if event.src_path == self.log_file:
        if os.path.abspath(event.src_path) == os.path.abspath(self.log_file):
            # 在文件发生变化时,实时获取最后一行文本
            self.last_line = self.get_last_line()
        # 用户可在外部传入一个回调方法,在文本发生变化时执行该事件
        if self.on_modified_callback:
            self.on_modified_callback()
        # 调用基类的同名方法,以便执行基类的默认行为
        super(LogWatcher, self).on_modified(event)
    def tail_last_line_and_match(self, match_string=None, max_match_seconds=10):
        """
        实时监控日志文件的变化,并实时获取最后一行文本。如果匹配到指定的字符串,停止监视。
        参数:
        - match_string:需要匹配的字符串
        """
        self.match_string = match_string
        self.start()
        end_time = time.time() + max_match_seconds
        try:
            while not self.stop_watching and time.time() <= end_time:
                if self.match_string and self.match_string in self.last_line:
                    self.stop_watching = True
        except KeyboardInterrupt:
            pass
        self.stop_watching = True  # 停止监视循环
def write_logs(log_file):
    """在新线程中写入日志"""
    for i in range(10):
        with open(log_file, 'a') as file:
            file.write(f'New log entry {i}\n')
        time.sleep(1)  # 每秒写入一次日志
if __name__ == '__main__':
    import logging
    logging.basicConfig(level=logging.DEBUG)
    log_file = 'demo.log'
    # 创建日志文件并写入示例日志
    with open(log_file, 'w') as file:
        file.write('This is the first line of the log.\n')
        file.write('This is the second line of the log.\n')
    log_watcher = LogWatcher(log_file)
    # 启动新线程写入日志
    write_thread = threading.Thread(target=write_logs, args=(log_file,))
    write_thread.start()
    # 启动实时监控日志文件变化,并打印最后一行文本,直到匹配到指定字符串或超时才停止监视
    log_watcher.tail_last_line_and_match(match_string='New log entry 9', max_match_seconds=20)
    # 等待写入线程结束
    write_thread.join()


三、Demo验证


运行代码,控制台的输出结果:

DEBUG:__main__:Reading line: This is the second line of the log.
DEBUG:__main__:Reading line: New log entry 0
DEBUG:__main__:Reading line: New log entry 1
DEBUG:__main__:Reading line: New log entry 2
DEBUG:__main__:Reading line: New log entry 3
DEBUG:__main__:Reading line: New log entry 4
DEBUG:__main__:Reading line: New log entry 5
DEBUG:__main__:Reading line: New log entry 6
DEBUG:__main__:Reading line: New log entry 7
DEBUG:__main__:Reading line: New log entry 8
DEBUG:__main__:Reading line: New log entry 9
Process finished with exit code 0
相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
5天前
|
监控 Linux Perl
【专栏】Linux 命令小技巧:显示文件指定行内容的方法,包括使用`head`和`tail`命令显示文件头尾部分
【4月更文挑战第28天】本文介绍了Linux中显示文件指定行内容的方法,包括使用`head`和`tail`命令显示文件头尾部分,利用`sed`的行号指定功能以及`awk`处理文本数据。文章还列举了在代码审查、日志分析和文本处理中的应用场景,并提醒注意文件编码、行号准确性及命令组合使用。通过练习和实践,可以提升Linux文本文件处理的效率。
|
3天前
|
Web App开发 Ubuntu Linux
Linux无图形界面环境使用Python+Selenium实践
【5月更文挑战第1天】Linux无图形界面环境使用Python+Selenium实践
38 2
|
5天前
|
Oracle Java 关系型数据库
【服务器】python通过JDBC连接到位于Linux远程服务器上的Oracle数据库
【服务器】python通过JDBC连接到位于Linux远程服务器上的Oracle数据库
17 6
|
5天前
|
IDE Java 开发工具
讨论 Python 中泛型(或类似泛型的功能)的优点和缺点
【5月更文挑战第8天】Python虽无显式泛型系统,但可通过类型注解和工具实现类似功能。优点包括提升代码可读性、静态类型检查、更好的IDE支持、灵活性和可逐渐引入。缺点涉及运行时性能开销、学习成本、非强制性及与旧代码集成问题。适当使用工具和实践可管理这些挑战。
22 2
|
5天前
|
Linux 开发者
【Linux】:文件查看 stat、cat、more、less、head、tail、uniq、wc
【Linux】:文件查看 stat、cat、more、less、head、tail、uniq、wc
23 1
|
5天前
|
弹性计算 运维 Shell
设置Python 支持自动命令补齐功能
【4月更文挑战第29天】
10 0
|
5天前
|
Linux Python Windows
Python虚拟环境virtualenv安装保姆级教程(Windows和linux)
Python虚拟环境virtualenv安装保姆级教程(Windows和linux)
|
5天前
|
弹性计算 运维 Shell
设置 Python 支持自动命令补齐功能
【4月更文挑战第29天】
8 1
|
5天前
|
缓存 监控 Python
Python中的装饰器:一种强大的功能增强工具
装饰器是Python中一个独特且强大的功能,它允许在不修改原有函数或类代码的情况下,为其添加额外的功能或行为。本文将深入探讨Python装饰器的原理、用法以及在实际开发中的应用场景,帮助读者更好地理解和应用这一技术。