Python,日志:如何使用字典配置自定义处理程序?
这段内容是关于Python 3.2中的日志模块(在GNU/Linux x86_64系统上)的:有没有办法用字典配置来设置一个自定义的处理器?
这是我尝试的代码:
import logging
import logging.config
class CustomHandler(logging.StreamHandler):
pass
logconfig = {
'version': 1,
'handlers': {
'console': {
'class': 'CustomHandler',
}
},
'loggers': {
'custom': {
'handlers': ['console'],
}
}
}
logging.config.dictConfig(logconfig)
logger = logging.getLogger('custom')
logger.error('Error message')
当然,这段代码是无法运行的。输出结果是:
Traceback (most recent call last):
File "/usr/lib/python3.2/logging/config.py", line 390, in resolve
found = self.importer(used)
ImportError: No module named CustomHandler
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.2/logging/config.py", line 569, in configure
handler = self.configure_handler(handlers[name])
File "/usr/lib/python3.2/logging/config.py", line 698, in configure_handler
klass = self.resolve(config.pop('class'))
File "/usr/lib/python3.2/logging/config.py", line 403, in resolve
raise v
File "/usr/lib/python3.2/logging/config.py", line 390, in resolve
found = self.importer(used)
ValueError: Cannot resolve 'CustomHandler': No module named CustomHandler
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./prova.py", line 91, in <module>
logging.config.dictConfig(logconfig)
File "/usr/lib/python3.2/logging/config.py", line 777, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python3.2/logging/config.py", line 574, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'console': Cannot resolve 'CustomHandler': No module named CustomHandler
在源代码中有一个我完全不理解的importer
方法……你有什么想法吗?
谢谢!
1 个回答
17
你需要告诉程序在哪里可以找到 CustomHandler
这个类。这个字符串应该包含它所在的模块(可能还有包名)。如果你直接运行这个脚本,可以用 __main__.CustomHandler
。如果不是,就用 your_module.CustomHandler
,其中 your_module
需要替换成包含这个类的模块的名字。