最近遇到生产环境某个应用的日志丢失,但是其他应用的日志却没丢失,通过查看日志库及其源码,发现,日志在滚动删除时,并不是线程安全的,如果多个进程或者线程,并发进行滚动时,可能导致后一个执行的把之前执行的滚动给删除了。
源码:
class TimedRotatingFileHandler(BaseRotatingHandler):
def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix.
"""
if self.stream:
self.stream.close()
self.stream = None
# get the time that this sequence started at and make it a TimeTuple
currentTime = int(time.time())
dstNow = time.localtime(currentTime)[-1]
t = self.rolloverAt - self.interval
if self.utc:
timeTuple = time.gmtime(t)

本文探讨了一种生产环境中日志丢失问题的解决方案,通过修改`TimedRotatingFileHandler`,实现多进程/线程下日志滚动的线程安全,确保不会因并发操作导致旧日志被误删。
最低0.47元/天 解锁文章
896

被折叠的 条评论
为什么被折叠?



