是否可以使用
TimedRotatingFileHandler
创建具有自定义日期格式的日志文件?
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from datetime import datetime
import time
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
log_dir = 'logs'
log_file = os.path.join(log_dir, datetime.now().strftime('%Y%m%d-%H%M%S') + f'_.log')
handler = TimedRotatingFileHandler(log_file, when='s', interval=1, backupCount=0)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
i = 0
while True:
logger.info(i)
print(i)
time.sleep(1)
i += 1
产品
20230810-100547_.log.2023-08-10_10-05-47
20230810-100547_.log.2023-08-10_10-05-48
20230810-100547_.log
而不是
20230810-100547_.log
20230810-100548_.log
20230810-100549_.log
午夜后是否需要重置处理程序(是否可能)?看起来不太优雅。
日志处理程序中似乎有一个 namer 属性
rotation_filename
方法,您可以将其分配给 namer 函数。它将在轮换期间更改日志文件的名称。工作代码应该如下所示:
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from datetime import datetime
import time
def namer(self):
now = datetime.now()
log_dir = './logs'
return os.path.join(log_dir, datetime.now().strftime('%Y%m%d-%H%M%S') + f'_.log')
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
log_dir = './logs'
log_file = os.path.join(log_dir, datetime.now().strftime('%Y%m%d-%H%M%S') + f'_.log')
handler = TimedRotatingFileHandler(log_file, when='s', interval=1, backupCount=0)
handler.rotation_filename = namer
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
i = 0
while True:
logger.info(i)
print(i)
time.sleep(1)
i += 1