如何使用 StreamHandler 捕获记录器 stderr 上的输出?

How to capture the output on stderr of a logger using a StreamHandler?

重定向正常日志记录的输出工作正常:

import contextlib
import io
import logging

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')

输出:

output: ERROR:root:Hi.

但是当使用 logging.basicConfig

更改日志格式时
import contextlib
import io
import logging

log_format = '[%(threadName)s] [%(levelname)s] %(message)s'
logging.basicConfig(format=log_format)

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')

输出为:

output: 
[MainThread] [ERROR] Hi.

因此不再捕获输出。

我猜这是因为

logging.basicConfig(**kwargs): Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.

(https://docs.python.org/3/library/logging.html#logging.basicConfig)

StreamHandler在一个单独的线程中工作,所以它的输出没有被捕获。

对于单元测试,无论如何我都想捕获它。我该怎么做?

您必须将日志记录配置拉入 with 语句主体,以便 StreamHandler 已经使用更改后的 stderr 初始化:

import contextlib
import io
import logging

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    log_format = '[%(threadName)s] [%(levelname)s] %(message)s'
    logging.basicConfig(format=log_format)
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')
# output: [MainThread] [ERROR] Hi.