Python,记录 : use custom handler with dictionary configuration?

标签 python logging configuration dictionary handler

这是关于 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 方法...有什么想法吗?

谢谢!

最佳答案

您需要告诉它在哪里可以找到 CustomHandler 类。该字符串应包含可以找到它的模块(可能还有包)。如果您直接运行此脚本,则可以使用 __main__.CustomHandler。否则,使用 your_module.CustomHandler,将 your_module 替换为包含该类的模块的名称。

关于Python,记录 : use custom handler with dictionary configuration?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346661/

相关文章:

python - KeyError 是适当的异常吗?

java - Tomcat 上使用 Log4j2 的 Access.log 作为 JSON

linux - 在 linux 中执行指定命令时触发警报

java - IntelliJ IDEA找不到Tomcat Lib目录

java - Spring - 捕获 bean 创建异常

c++ - 如何从 python SWIG 包装器向下转换 c++ 对象?

python - 如何通过替换 python 中的 for 循环来减少算法的执行时间

python - 基于类的装饰器和 repr() 保护

node.js - 如何从 winston@3 记录器输出中删除 [Symbol] 字段?

java - 能够在 Seam 3 中 @Inject EntityManager 的配置