我正在尝试使用标准库logging
模块,使用配置文件来组织日志记录器。
我尝试了一个简单的设置,像这样:
配置文件:
[loggers]
keys=root,main,second
[handlers]
keys=consoleHandler, exportHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_main]
level=DEBUG
handlers=consoleHandler,exportHandler
qualname=simpleExample
propagate=0
[logger_second]
level=DEBUG
handlers=consoleHandler,exportHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_exportHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
filename='LogBookmain.log'
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
File1
import logging
import logging.config
import os
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('main')
os.system('test2.py')
logger.info('script was executed correctly')
File2
import logging
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('second')
a = 8
b = 4
result = a + b
logger.debug('result of a + b is '+ result)
result2 = a / b
logger.debug('result of a / b is '+ result)
,但我得到一个错误,当我尝试运行第二个文件:
Traceback (most recent call last):
File "D:\Loggingtest2.py", line 4, in <module>
logging.config.fileConfig('logging.conf')
File "C:\anaconda3libloggingconfig.py", line 79, in fileConfig
handlers = _install_handlers(cp, formatters)
File "C:\anaconda3libloggingconfig.py", line 145, in _install_handlers
h = klass(*args, **kwargs)
TypeError: __init__() missing 1 required positional argument: 'filename'
当我在google上查找错误信息时,它只讨论python类,但我并没有试图在这里编写自己的类。出了什么问题,我该如何解决?
你写了
logging.config.fileConfig('logging.conf')
我认为你想要
logging.config.fileConfig('logging.conf',
defaults={'logfilename': 'LogBookmain.log'})
不是'logfilename'就是'filename'。或者类似地调整配置文件。
我的logging.config
有两个错误:
- 对于
Logger_main
和logger_second
,qualname
具有相同的名称('simpleExample'),并且在使用中不指代任何内容。 - Handler声明错误:
class=FileHandler
level=DEBUG
formatter=simpleFormatter
filename='LogBookmain.log'
到正确的:
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('LogBookmain.log',)
这个问题帮助了我很多,特别是如何定义args
,并看到一个工作配置是什么样子的。