程序员

Python 日志模块 logging rotate 的坑儿

2016-05-25  本文已影响6176人  混沌中的菜菜

本文的坑儿,主要是在日志滚动这一块,当然,如果你的应用一直在打日志,系统时间一直是正确的,那么 python(2.6.6) 自己的日志模块是 ok 的。

先说现象:
初始化日志按照时间滚动,TimedRotatingFileHandler(when='D', interval=1...)
在 2016-05-23 查看 cap-sync.log 日志的滚动情况,发现下面的诡异现象:

ls -l
head -n 1cap-sync.log.2016-05-19
tail -n 1cap-sync.log.2016-05-19
head -n 1cap-sync.log.2016-05-20
tail -n 1cap-sync.log.2016-05-20
head -n 1cap-sync.log
tail -n 1cap-sync.log
 
total30460
-rw-rw-r-- 1 admin admin     1440 May 23 10:56 cap-sync.log
-rw-rw-r-- 1 admin admin   531572 May 20 18:34 cap-sync.log.2016-05-19
-rw-rw-r-- 1 admin admin     1330 May 23 10:56 cap-sync.log.2016-05-20

2016-05-20 09:28:40,411 - CAP-Sync - INFO - Consume has failed record in JMQ:{"action":"add","appCode":"config","ips":["10.255.255.1"]}.Put this message into retry queue
2016-05-20 18:34:16,265 - CAP-Sync - INFO - Consume OK with JMQ: {"action":"remove","appCode":"big.new","ips":["10.255.255.2"]}.

2016-05-22 21:34:40,133 - CAP-Sync - INFO - Consume OK with JMQ:{"action":"remove","appCode":"zk","ips":["10.1255.255.2"]}.
2016-05-23 10:56:56,373 - CAP-Sync - INFO - Consume OK with JMQ:{"action":"add","appCode":"service","ips":["10.255.255.1"]}.

2016-05-22 21:34:40,148 - JMQ-api - INFO - produce JMQ success! Detail Info:{"action":"remove","appCode":"zk","ips":["10.255.255.2"]}
2016-05-23 10:56:56,384 - JMQ-api - INFO - produce JMQ success! Detail Info:{"action":"add","appCode":"service","ips":["10.255.255.1"]} 

诡异点:

网上查到的已知 BUGs:

handler.suffix = "%Y-%m-%d"```

根本原因:
Addhandler,会多次追加,也就是说在 a.py 里 import b 的时候,已经在 logger 实例里加了一个 handler,
然后 a.py 去初始化一个同名的 logger 时,又追加了一个同样的 handler。

所以产生的效果是:

  1. 没有 rotate 的情况下,一条日志会被打印N次(N 是全部代码里初始化 logger 的次数)
  2. Rotate 的时候,会导致同时往昨天以及今天的日志文件里写日志
    这个情形,没想明白,为什么会往昨天的日志文件继续写日志

解决方法:

  1. 确保只有一个 get_logger 的实例
  2. 按天 rotate,尽量用 midnight
  3. 在 global_logger.py 中,addhandler 之前先判断当前 handler 个数:
    if not len(logger.handlers):
        logger.addHandler(handler)

参考资料:
http://stackoverflow.com/questions/6333916/python-logging-ensure-a-handler-is-added-only-once

上一篇 下一篇

猜你喜欢

热点阅读