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

标签 python python-3.x logging stdout stderr

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

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/

相关文章:

Python Openpyxl 在 xlsx 中找不到数字

python - 如何使用python docx将表格边框添加到word doc

java - 抛出异常的记录方法

php - 记录事件 : How to record time using a PHP application?

java - 谁控制output.log和error.log文件?

python - 测试时模拟 Oauth 提供者

python - 如何在 python 中执行 <xor> 例如enc_price = pad <xor> 价格

python - 无法在 python 3.7.0 上导入 ijson 模块

python - 如何从字符串中删除列表中的所有元素?

python - 一副纸牌的随机迭代