避免在控制台中显示记录器条目

Avoid showing logger entries in console

我有一个“基本”日志记录配置,可以在我的项目中记录到标准输出。

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

我还有另一个记录器user_logger,它不应该打印任何东西。相反,它应该将日志条目存储在一个变量中。

user_logger = logging.getLogger('user_logger')
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(USER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

问题是当我调用:

user_logger.info('This should only be in "log_capture_string"')

它将它打印到控制台。

你知道如何避免吗?

你应该设置user_logger.propagate = Falselogging.propagate docs

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

因此,您的根记录器不会向 stderr 发送任何数据。

这个例子什么都不输出

import io
import logging

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

user_logger = logging.getLogger('user_logger')
user_logger.propagate = False
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(SERVER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

user_logger.info('This should only be in "log_capture_string"')