在open()中处理logrotate

问题描述 投票:1回答:1

我正在使用以下功能逐行跟踪和处理日志文件:

def tail(f):
    f.seek(0,2)
    while True:
        line = f.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

with open("/var/log/some.log") as f:
    for line in tail(f):
    ...

当logrotate旋转文件时,该功能停留在最后一行。我猜想logrotate会移动文件并创建一个新文件,而程序仍在等待旧文件中的行。

什么是处理此问题的好方法-发生旋转时重新打开文件?

python python-3.x logrotate log-rotation
1个回答
0
投票

标准的通常方法是告诉logrotate将HUP信号发送到处理日志的服务/程序。

在logrotate配置中,这是通过postrotate脚本完成的:

   postrotate
       /usr/bin/killall -HUP your_process
   endscript

然后您必须在python程序中处理信号HUP。您在python's signal doc中有一个示例。您需要处理signal.SIGHUP

© www.soinside.com 2019 - 2024. All rights reserved.