前几天填了一个前人留下的“日志”坑,程序日志只有程序重启才可以生成一个新日志文件,这样就会导致程序长时间运行之后,会生成一个巨大的日志文件,不方便后期问题查询或磁盘清理,所以日志按天切割势在必行。
python 原生logging日志模块可以满足大部分需求,但是唯独不适合多进程下日志切割,具体的原因可以自行百度一下,网上有很多讲解的,我就说一下,如何用最小的改动logging源码的方法来实现pyhon多进程下日志按天(分钟、小时)切割。
直接上代码:
1、修改logging模块中的TimedRotatingFileHandler(BaseRotatingHandler)类方法doRollover(self):
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 s