python 日志滚动多进程导致日志丢失

解决日志丢失:并发安全的定时文件滚轮处理
本文探讨了一种生产环境中日志丢失问题的解决方案,通过修改`TimedRotatingFileHandler`,实现多进程/线程下日志滚动的线程安全,确保不会因并发操作导致旧日志被误删。

      最近遇到生产环境某个应用的日志丢失,但是其他应用的日志却没丢失,通过查看日志库及其源码,发现,日志在滚动删除时,并不是线程安全的,如果多个进程或者线程,并发进行滚动时,可能导致后一个执行的把之前执行的滚动给删除了。

源码:

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)
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值