首页 > 解决方案 > Python日志记录不输出调试消息

问题描述

我正在尝试使用 python 日志记录模块将消息输出到文件,我在网上找到了一些配置并将其定制为我需要的内容,但它没有打印我想要打印的内容。DEBUG 级别的文件处理程序中没有出现 DEBUG 级别的消息。

我正在为记录器使用这个 JSON 配置:

{
  "version": 1,
  "formatters": {
    "simple": {
      "format": "%(asctime)s : %(levelname)-8s - %(name)s : %(message)s",
      "datefmt": "%Y-%m-%d %H:%M:%S"
    }
  },
  "handlers": {
    "file_handler": {
      "class": "logging.handlers.RotatingFileHandler",
      "level": "DEBUG",
      "formatter": "simple",
      "filename": "info.log",
      "maxBytes": 1E6,
      "backupCount": 5,
      "encoding": "utf8"
    },
    "error_file_handler": {
      "class": "logging.handlers.RotatingFileHandler",
      "level": "ERROR",
      "formatter": "simple",
      "filename": "errors.log",
      "maxBytes": 1E6,
      "backupCount": 5,
      "encoding": "utf8"
    }
  },
  "root": {
    "level": "INFO", # EDIT - change this to DEBUG to fix
    "handlers": ["file_handler", "error_file_handler"]
  }
}

我执行这段代码:

import logging
import logging.config as lconfig

import json

with open('logger.json', 'rt') as f:
    config = json.load(f)
lconfig.dictConfig(config)

logger = logging.getLogger(__name__)

logger.info('info')
logger.warning('warning')
logger.debug('debug')
logger.error('error')
logger.critical('critical')

这里的问题是文件info.log没有调试行,输出是这样的:

2020-01-03 15:32:23 : INFO     - __main__ : info
2020-01-03 15:32:23 : WARNING  - __main__ : warning
2020-01-03 15:32:23 : ERROR    - __main__ : error
2020-01-03 15:32:23 : CRITICAL - __main__ : critical

我应该怎么做才能解决这个问题并将调试消息打印到info.log文件中?

标签: pythonlogging

解决方案


您需要将根记录器的级别设置为 DEBUG 而不是 INFO。

"root": { 
  "level": "DEBUG",

推荐阅读