我正在使用以下功能逐行跟踪和处理日志文件:
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会移动文件并创建一个新文件,而程序仍在等待旧文件中的行。
什么是处理此问题的好方法-发生旋转时重新打开文件?
标准的通常方法是告诉logrotate将HUP信号发送到处理日志的服务/程序。
在logrotate配置中,这是通过postrotate脚本完成的:
postrotate
/usr/bin/killall -HUP your_process
endscript
然后您必须在python程序中处理信号HUP。您在python's signal doc中有一个示例。您需要处理signal.SIGHUP