簡體   English   中英

如何使用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):通過使用默認Formatter創建StreamHandler並將其添加到根記錄器來為日志記錄系統進行基本配置。

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

StreamHandler在一個單獨的線程中工作,因此不會捕獲它的輸出。

對於單元測試,我想要捕獲它。 我怎樣才能做到這一點?

您必須將日志記錄配置拉入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