1

我有一个日志记录配置文件:

logger_config.yml

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
  file:
    class: logging.FileHandler
    level: DEBUG
    formatter: simple
    filename: train.log
loggers:
  trainLogger:
    level: DEBUG
    handlers: [console]
    propagate: 1
root:
  level: DEBUG
  handlers: [console]
  propagate: 1

还有一个简单的脚本:

测试.py

import logging
import logging.config
import yaml


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

logging.config.dictConfig(config)

# create logger
logger = logging.getLogger(__name__)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

当我运行test.py时,假设脚本将只登录控制台,因为handlerforrootconsole,但也创建了一个空的 train.log。为什么这个附加?

4

1 回答 1

0

fileHandler即使您只使用. consoleHandler如果您只是在 shell 中运行以下命令:

import logging
fh = logging.FileHandler("mylogger.txt")
quit()

您会看到“mylogger.txt”已创建。这是因为在幕后,处理程序创建文件时__init__,而不是在使用时。这样设计更好,因为您可能会多次使用该处理程序,可能同时使用,并且您不想每次都检查文件是否存在,因为这会很慢并且您可能会引入竞争条件在尝试创建文件时

于 2019-01-02T21:44:11.207 回答