【发布时间】:2021-11-21 10:08:11
【问题描述】:
我想捕获发送到 Stream 的日志。
MyCode.py 将日志传递到控制台:2021-09-29 15:06:11,382 - root - ERROR - Started。但是,captured.records 什么也不返回。 (输出中的前 2 行)
来源
问题
- 为什么
captured什么都不返回? - 如何捕获发送到
StreamHandler(sys.stdout)的日志?
MyCode.py:
import logging
import sys
logger = logging.getLogger()
streamHandler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
logger.error('Started')
main.py:
import unittest
from unittest import TestCase
import MyCode
class TestExample(TestCase):
def test_logging(self):
with self.assertLogs() as captured:
print('captured.records: ', captured.records)
self.assertEqual(len(captured.records), 1)
self.assertTrue("Started" in captured.records[0].getMessage())
if __name__ == '__main__':
unittest.main()
控制台:
2021-09-29 15:06:11,382 - root - ERROR - Started
captured.records: []
F
======================================================================
FAIL: test_logging (__main__.TestExample)
----------------------------------------------------------------------
Traceback (most recent call last):
File "main.py", line 9, in test_logging
self.assertEqual(len(captured.records), 1)
AssertionError: 0 != 1
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
repl process died unexpectedly: exit status 1
如果还有什么需要补充的,请告诉我。
【问题讨论】:
标签: python unit-testing logging pytest