在python日志文件中包含当前日期

2 python logging

我有一个每天都在运行的流程.它使用Python日志记录.如何配置python日志记录模块以写入包含文件名中当前日期的文件?

因为我每天早上重新启动进程,所以TimedRotatingFileHandler将无法正常工作.该项目较大,因此我有兴趣保留登录日志配置文件所需的代码.

小智 8

您可以使用TimedRotatingFileHandler.例如:

import logging
import logging.handlers

LOG_FILENAME = '/tmp/log'

# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)

但是,如果您的程序运行超过一天,这可能只会起作用.如果您的脚本每天在cron作业中启动,那么最好手动格式化您传递给日志处理程序的文件名以包含时间戳.