python通过yaml文件配置日志记录

时间:2019-01-11 14:51:03

标签: python logging pyyaml

我正在尝试使用yaml文件和logging.config.dictConfig为我的应用程序配置日志记录,但这实际上没有用,我不认为logging正在使用该配置。

这是我的Yaml文件:

  version: 1
  logging:
    disable_existing_loggers: true
    formatters:
      multi-process:
        class: logging.Formatter
        style:
        datefmt: "%I:%M:%S"
        format: "{levelname:8s}; {process:5d}; {asctime:s}; {name:<15s} {lineno:4d}; {message:s}"
      multi-thread:
        class: logging.Formatter
        style:
        datefmt: "%I:%M:%S"
        format: "{levelname:8s}; {threadName:5d}; {asctime:s}; {name:<15s} {lineno:4d}; {message:s}"
      verbose:
        class: logging.Formatter
        style:
        datefmt: "%I:%M:%S"
        format: "{levelname:8s}; {process:5d}; {threadName:8s}; {asctime:s}; {name:<15s} {lineno:4d}; {message:s}"
    handlers:
      console:
        level: DEBUG
        class: logging.StreamHandler
        formatter: verbose
        stream: ext://sys.stdout
      file_handler:
        level: INFO
        class: logging.handlers.WatchedFileHandler
        formatter: verbose
        filename: backtest.log
        mode: a
        encoding: utf-8
    loggers:
      example:
        level: DEBUG
        handlers: 
          - console
    root:
      handlers:
        - console
      level: DEBUG

这是我的加载方式:

with open('logging.yaml', 'r') as stream:
    yamld = yaml.load(stream)
    logging.config.dictConfig(yamld)

logger = logging.getLogger("example")

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

这是我在控制台上的输出:

warn message
error message
critical message

好像我的配置根本没有加载

1 个答案:

答案 0 :(得分:0)

明白了,logging dict并不是日志记录模块要查找的内容。

我只需将我的Yaml放置在没有logging:的位置即可