You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python测试用例中启用日志?解决unittest无日志输出问题

问题原因及解决方法

核心问题

看不到日志的主要原因有两点:

  • logging.basicConfig 在类定义中执行时机太晚,unittest框架初始化时可能已修改日志配置,导致你的配置不生效。
  • unittest 默认会将根日志级别调整为 WARNING,即使你设置了 DEBUG 级别也会被覆盖。

解决方法

方法1:将日志配置移到模块外部

把 logging.basicConfig 放在模块最顶部,确保在unittest初始化前完成配置:

import unittest
import logging

# 移到模块顶部配置日志
logging.basicConfig(
    format='%(asctime)s %(module)s %(levelname)s: %(message)s',
    datefmt='%m/%d/%Y %I:%M:%S %p',
    level=logging.DEBUG
)

class TestUnitTest(unittest.TestCase):
    logger = logging.getLogger(__name__)

    def setUp(self):
        self.logger.debug("inside setup")

    def test_method1(self):
        self.logger.debug("inside test_method1")
        self.assertTrue(True)

if __name__ == '__main__':
    unittest.main()

方法2:在测试类的 setUpClass 中配置日志

如果想把配置和测试类绑定,用类方法初始化日志:

import unittest
import logging

class TestUnitTest(unittest.TestCase):
    logger = logging.getLogger(__name__)

    @classmethod
    def setUpClass(cls):
        logging.basicConfig(
            format='%(asctime)s %(module)s %(levelname)s: %(message)s',
            datefmt='%m/%d/%Y %I:%M:%S %p',
            level=logging.DEBUG
        )
        # 显式设置当前logger级别,避免被根logger覆盖
        cls.logger.setLevel(logging.DEBUG)

    def setUp(self):
        self.logger.debug("inside setup")

    def test_method1(self):
        self.logger.debug("inside test_method1")
        self.assertTrue(True)

方法3:直接为logger添加处理器

若 basicConfig 因根日志已被配置而不生效,可直接给当前logger设置级别并添加控制台处理器:

import unittest
import logging

class TestUnitTest(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        
        # 添加控制台输出处理器
        handler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s %(module)s %(levelname)s: %(message)s',
            datefmt='%m/%d/%Y %I:%M:%S %p'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        # 关闭日志传播,避免重复输出
        self.logger.propagate = False

    def setUp(self):
        self.logger.debug("inside setup")

    def test_method1(self):
        self.logger.debug("inside test_method1")
        self.assertTrue(True)

验证效果

修改后运行测试,会看到类似如下的输出:

10/05/2024 10:30:00 AM __main__ DEBUG: inside setup
10/05/2024 10:30:00 AM __main__ DEBUG: inside test_method1
Running tests...
----------------------------------------------------------------------
  test_method1(__main__.TestUnitTest) ... OK (0.000s)

----------------------------------------------------------------------
Ran 1 test in 0.000s

内容的提问来源于stack exchange,提问作者n179911a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 17:15:17