【问题标题】:Python: Configure logger with yaml to open logfile in write modePython:使用yaml配置记录器以写入模式打开日志文件
【发布时间】:2018-09-20 00:59:01
【问题描述】:

我在文件 loggingConfig.yml 中有以下记录器配置

version: 1
disable_existing_loggers: False
    formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

handlers:
    console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout

file_handler:
    class: logging.FileHandler
    level: INFO
    formatter: simple
    filename: info.log
    encoding: utf8

loggers:
    my_module:
        level: ERROR
        handlers: [console]
        propagate: no

root:
     level: INFO
     handlers: [console, file_handler]

还有下面的python代码:

import logging
import logging.config
import yaml

with open('loggingConfig.yml', 'rt') as f:
    config = yaml.safe_load(f.read())
    logging.config.dictConfig(config)

logger = logging.getLogger(__name__)

logger.info('TestLogger')

这工作正常,但现在我想以写入模式而不是附加模式打开日志文件。 我找不到任何使用 yaml 文件并以写入模式打开日志文件的示例。

我才发现,在写模式下打开可以使用fileConfig来完成

logging.config.fileConfig('logging.conf')

并在 logging.conf 文件中指定参数:

args=('info.log', 'w')

有什么方法可以使用 yaml 文件或在源代码中操作配置来做到这一点?

【问题讨论】:

    标签: python logging yaml


    【解决方案1】:

    尝试使用以下配置:

    file_handler:
        class: logging.FileHandler
        level: INFO
        formatter: simple
        filename: info.log
        encoding: utf8
        mode: w
    

    默认模式是 'a',意思是 append 。更多信息here

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 2015-12-29
      • 2018-10-12
      相关资源
      最近更新 更多