![](/img/trans.png)
[英]Using logging.info instead of logger.info wrecks StreamHandler
[英]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.