gpt4 book ai didi

python - 检测日志文件轮换(同时观察日志文件进行修改)

转载 作者:IT王子 更新时间:2023-10-29 00:56:45 24 4
gpt4 key购买 nike

我使用以下代码来跟踪 ssh 登录:

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

if __name__ == '__main__':
logfile = open('/var/log/auth.log', 'r')
loglines = follow(logfile)
for line in loglines:
print 'do something here'

我注意到这个脚本在几天后突然停止工作。我没有收到任何错误,它没有终止,只是停止工作,就好像 readline() 永远不会返回一样。

所以我执行了一个 echo 'test' >> auth.log.1 并且这确实最终被脚本处理了,因为前一段时间 auth.log 得到了重命名为 auth.log.1

我如何跟踪此类日志轮换发生的时间并进行相应调整?

最佳答案

使用 e4c5 的答案我得到了这段代码,它也解决了每秒多次调用 readline() 的问题。

在第一次调用期间,它会跳到文件末尾并等待修改。当文件被移动时,它会重新打开文件并读取全部内容,然后开始等待。

import os
import time
import traceback
import threading
import inotify.adapters

logfile = b'/var/log/auth.log'
#logfile = b'logfile.log'

##################################################################

def process(line, history=False):
if history:
print '=', line.strip('\n')
else:
print '>', line.strip('\n')

##################################################################

from_beginning = False
notifier = inotify.adapters.Inotify()
while True:
try:
#------------------------- check
if not os.path.exists(logfile):
print 'logfile does not exist'
time.sleep(1)
continue
print 'opening and starting to watch', logfile
#------------------------- open
file = open(logfile, 'r')
if from_beginning:
for line in file.readlines():
process(line, history=True)
else:
file.seek(0,2)
from_beginning = True
#------------------------- watch
notifier.add_watch(logfile)
try:
for event in notifier.event_gen():
if event is not None:
(header, type_names, watch_path, filename) = event
if set(type_names) & set(['IN_MOVE_SELF']): # moved
print 'logfile moved'
notifier.remove_watch(logfile)
file.close()
time.sleep(1)
break
elif set(type_names) & set(['IN_MODIFY']): # modified
for line in file.readlines():
process(line, history=False)
except (KeyboardInterrupt, SystemExit):
raise
except:
notifier.remove_watch(logfile)
file.close()
time.sleep(1)
#-------------------------
except (KeyboardInterrupt, SystemExit):
break
except inotify.calls.InotifyError:
time.sleep(1)
except IOError:
time.sleep(1)
except:
traceback.print_exc()
time.sleep(1)

##################################################################

关于python - 检测日志文件轮换(同时观察日志文件进行修改),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com