简体   繁体   English

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

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

Redirecting the output of normal logging works fine: 重定向正常日志记录的输出工作正常:

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: 输出:

output: ERROR:root:Hi.

However when changing the log format using logging.basicConfig 但是,使用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}')

the output is: 输出是:

output: 
[MainThread] [ERROR] Hi.

So the output is not captured any more. 因此不再捕获输出。

My guess is this is because 我猜这是因为

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. logging.basicConfig(** kwargs):通过使用默认Formatter创建StreamHandler并将其添加到根记录器来为日志记录系统进行基本配置。

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

and StreamHandler is working in a separate thread, so it's output is not captured. StreamHandler在一个单独的线程中工作,因此不会捕获它的输出。

For unit testing I would like to capture it anyways. 对于单元测试,我想要捕获它。 How can I do this? 我怎样才能做到这一点?

You'll have to pull the logging configuration into the with statement-body so StreamHandler already gets initialized with the altered stderr : 您必须将日志记录配置拉入with statement-body,因此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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM