如何使用 python 的 fileConfig 进行日志记录并配置日志文件文件名
- 作者: Mr点BUG
- 来源: 51数据库
- 2022-11-15
问题描述
我有一个用于记录到控制台的日志配置文件和一个具有不同格式和级别的文件.在我的 python 脚本中,我可以加载这个配置,基本上控制台和文件输出都可以.
I have a logging configuration file for logging to console and a file with different formats and levels. In my python script I can load this configuration and basically console and file output are ok.
我在config文件中设置文件名如下图.
I set the file name in the config file as shown below.
是否可以在 python 脚本本身中设置该文件名?
Is it possible to set that file name in the python script itself?
python 代码:
# set up logging
logging.config.fileConfig(loginipath)
logger = logging.getLogger('sLogger')
# log something
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
日志记录配置文件:
[loggers]
keys=root,sLogger
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=fileFormatter,consoleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_sLogger]
level=DEBUG
handlers=consoleHandler,fileHandler
qualname=sLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('logfile.log',)
[formatter_fileFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
[formatter_consoleFormatter]
format=%(levelname)s - %(message)s
datefmt=
推荐答案
像这样改变你的 handler_fileHandler 部分:
Change your handler_fileHandler section like so:
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('%(logfilename)s',)
然后在 fileConfig 调用中添加一个 defaults 参数
and then add a defaults argument to the fileConfig call
logging.config.fileConfig(loginipath, defaults={'logfilename': '/var/log/mylog.log'})
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
