且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python日志记录-将日期设置为文件名

更新时间:2021-11-16 07:57:28

您无法在配置文件中使用datetime,因为它不知道这意味着什么.但是,您可以在python文件本身中添加Filehandler:

You can't use datetime in a config file, as it doesn't know what it means. You can however add the Filehandler in the python file itself:

import logging.config
from datetime import datetime

logging.config.fileConfig('aaa.conf')
logger = logging.getLogger('MainLogger')

fh = logging.FileHandler('{:%Y-%m-%d}.log'.format(datetime.now()))
formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s')
fh.setFormatter(formatter)

logger.addHandler(fh)
logger.debug("TEST")

这样,您可以在处理程序中将日期设置为文件名.

This way you can set the date as the file name in the handler.

这是配置文件,请注意,您在最后一个格式化程序中输入了错字,您将fillname代替了filename,并且在message中忘记了(.

This is the config file, note that you had a typo in the last formatter, you put fillname instead of filename and you forgot ( in message.

[loggers]
keys=root,MainLogger

[handlers]
keys=consoleHandler

[formatters]
keys=consoleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_MainLogger]
level=DEBUG
handlers=consoleHandler
qualname=MainLogger
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)

[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%(lineno)04d | %(message)s

这应该工作正常.