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

Pytest中caplog返回空文本问题排查与解决求助

解决pytest caplog捕获日志为空的问题

问题背景

我在测试套件中尝试捕获函数运行时的INFO级日志内容,但caplog返回空文本,测试始终失败。

主函数代码(main.py)

import logging
# 注:原代码未导入os,实际运行会报错,需补充该导入
import os

log = logging.getLogger()
log.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO'))

def _get_item(var: str):
    item = other_function.get_item(var)
    return item

测试代码(tests/test_logging.py)

import logging
import main

def test__processing(caplog):
    caplog.set_level(logging.INFO, main.__name__)
    item = main._get_item('variable')
    assert 'log output expected from main._get_item' in caplog.text

测试报错信息

FAILED tests/test_logging.py::test__processing - AssertionError: assert 'log output expected from main._get_item' in ''

已尝试的写法(未解决)

with caplog.at_level(logging.INFO, main.__name__):    
    item = main._get_item('variable')    
    assert 'log output expected from main._get_item' in caplog.text

解决办法

1. 确保函数实际输出目标日志

你的_get_item函数中没有任何log.info()调用,这是核心问题——没有日志输出,caplog自然捕获不到内容。需要在函数中添加日志代码:

def _get_item(var: str):
    log.info('log output expected from main._get_item')  # 添加该行日志输出
    item = other_function.get_item(var)
    return item

2. 修正日志器初始化方式

主函数中使用的是根日志器(logging.getLogger()),而测试代码针对的是main.__name__对应的模块日志器,两者不匹配,导致caplog的级别设置无法作用到根日志器。

修改main.py中的日志器初始化:

# 改为使用模块专属日志器,而非根日志器
log = logging.getLogger(__name__)
log.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO'))

若必须使用根日志器,测试时需针对根日志器设置级别:

def test__processing(caplog):
    # 针对根日志器设置级别
    caplog.set_level(logging.INFO, logger=None)
    item = main._get_item('variable')
    assert 'log output expected from main._get_item' in caplog.text

# 或使用上下文管理器写法
def test__processing(caplog):
    with caplog.at_level(logging.INFO, logger=None):
        item = main._get_item('variable')
        assert 'log output expected from main._get_item' in caplog.text

3. 排查环境变量影响

如果环境变量LOGGING_LEVEL被设置为WARNING或更高级别,会过滤掉INFO日志。可在测试中强制覆盖日志级别:

def test__processing(caplog):
    # 直接设置主模块日志器的级别
    main.log.setLevel(logging.INFO)
    caplog.set_level(logging.INFO, main.__name__)
    item = main._get_item('variable')
    assert 'log output expected from main._get_item' in caplog.text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:48:32