How to use logging with python#39;s fileConfig and configure the logfile filename(如何使用 python 的 fileConfig 进行日志记录并配置日志文件文件名)
问题描述
我有一个用于记录到控制台的日志配置文件和一个具有不同格式和级别的文件.在我的 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'})
这篇关于如何使用 python 的 fileConfig 进行日志记录并配置日志文件文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 python 的 fileConfig 进行日志记录并配置日
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
