Python:使用yaml配置记录器以写模式打开日志文件

7
我在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:

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

我能否通过yaml文件或修改源代码中的配置来完成这个任务?

1个回答

8
尝试使用以下配置:
file_handler:
    class: logging.FileHandler
    level: INFO
    formatter: simple
    filename: info.log
    encoding: utf8
    mode: w

默认模式是 'a' ,意味着 追加。更多信息,请在此处查看


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接