我正致力于在我的 Python 项目中实现日志记录,但遇到了一些障碍。我正在尝试设置我的日志记录,以便将处理程序和格式化程序全部组织到一个配置文件中。我现在想做的是设置我的 fileHandler
这样它将创建一个看起来像这样的日志文件: YYYY_MM_DD.log
显然 Y 代表年份, M代表月份,D代表日期。
这是我尝试使用我的配置文件所做的:
[loggers]
keys=root,MainLogger
[handlers]
keys=fileHandler, consoleHandler
[formatters]
keys=logFormatter, consoleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[logger_MainLogger]
level=DEBUG
handlers=fileHandler, consoleHandler
qualname=MainLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
args=(datetime.now().strftime('%Y_%m_%d.log'), 'a')
[formatter_logFormatter]
format=%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s
[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(fillname)s-%(funcName)s-%(lineno)04d | %message)s
我用来测试配置的文件非常简单:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('MainLogger')
logger.debug("TEST")
我现在遇到的具体错误是:
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: "%Y_%m_%d.log'), 'a')"
我试过更改 %Y
、 %m
和 %d
如错误所述,但这并不能解决问题。我如何着手设置配置文件,以便我的日志文件看起来像我想要的那样?
我应该注意,当我将文件名更改为 test.log
一切正常时,所以这是我似乎遇到的唯一错误。
原文由 Skitzafreak 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不能在配置文件中使用
datetime
,因为它不知道它的含义。但是,您可以在 python 文件本身中添加Filehandler
:这样您就可以在处理程序中将日期设置为文件名。
This is the config file, note that you had a typo in the last formatter, you put
fillname
instead offilename
and you forgot(
inmessage
。这应该工作得很好。