【问题标题】:Logging handlers not working without basicConfig没有 basicConfig 日志处理程序无法工作
【发布时间】:2013-02-19 13:31:43
【问题描述】:

我有一个 Flask Web 应用程序,Python 日志记录配置是在应用程序启动时通过 dictConfig 完成的。将某些日志写入数据库的处理程序附加到记录器'test.module' 仅当在应用程序启动时还调用logging.basicConfig(level=logging.DEBUG) 时,才会将写入该记录器的日志写入数据库。否则,不会将任何日志写入数据库。我知道 basicConfig 只是将一个 streamHandler 附加到根记录器。我认为这应该无关紧要,因为我不希望根记录器做任何事情。为什么没有 basicConfig 就不行?

我在下面添加了我如何启动记录器和我的配置。

class DbHandler(logging.Handler):
    def __init__(self, level=logging.NOTSET):
        logging.Handler.__init__(self, level)

    def emit(self, record):
        record.message = self.format(record)
        log = DbModel()
        log.message = record.message
        log.save()


LOGGING = {
    'version': 1,
    'handlers': {
        'db_log': {
            'level': 'DEBUG',
            'class': 'test.handlers.DbHandler',
        },
    },
    'loggers': {
        'test.important_module': {
            'handlers': [
                'db_log'
            ],
    },
}

# logging.basicConfig(level=logging.DEBUG) # Doesnt work without this
logging.config.dictConfig(LOGGING)

logger = logging.getLogger('test.important_module')
logger.info('Making a test')

【问题讨论】:

  • 您能否提供用于设置记录器的代码以及它与执行实际记录的代码有何关系?到目前为止,您提供的内容有些模糊...
  • @isedev 我现在添加了它
  • 仅从可用性的角度来看,我会重新考虑让处理程序修改 record.message 作为副作用。直接设置log.message = self.format(record)即可。

标签: python logging java.util.logging


【解决方案1】:

您没有设置“test.important_module”记录器本身的级别(您只设置了处理程序的级别)。

你可以这样做:

logger = logging.getLogger('test.important_module')
logger.setLevel(logging.DEBUG)

或者像这样:

'loggers': {
    'test.important_module': {
        'level': 'DEBUG',         # <<< HERE
        'handlers': [
            'db_log'
        ],
},

【讨论】:

  • 哦,谢谢。只是好奇,为什么 basicConfig 有让它工作的副作用?它是否为所有记录器设置了级别?
  • 据我所知,当我在“test.important_module”上调用 logger.info 时,记录没有进入 db_log 处理程序,因为 logger 没有级别。调用 basicConfig 后,root 获得 DEBUG 级别。所以现在当我在“test.important_module”上调用 logger.info 时,记录器仍然没有级别,所以记录仍然不应该进入 db_log 处理程序。后来记录传播到根,我看到它打印在控制台上。但这并不能解释为什么在 root 升级后记录会记录在数据库中。我错了吗?
  • doh,对不起......我的错,不知道我在想什么。我的意思是说 test.important_module 具有 NOTSET 级别,因此将从根记录器继承。
  • 呵呵不知道。再次感谢
猜你喜欢
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2014-10-23
相关资源
最近更新 更多