重定向正常日志记录的输出工作正常:
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.
关于python - 如何使用 StreamHandler 捕获记录器 stderr 上的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841368/