代码之家  ›  专栏  ›  技术社区  ›  Dave

Python:使用yaml配置logger以在写入模式下打开日志文件

  •  5
  • Dave  · 技术社区  · 6 年前

    我在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')
    

    并在日志记录中指定参数。conf文件:

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

    有什么方法可以使用yaml文件或在源代码中操纵配置来实现这一点吗?

    1 回复  |  直到 6 年前
        1
  •  6
  •   ma3oun    6 年前

    尝试使用以下配置:

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

    默认模式为“a”,表示 追加 .更多信息 here