如何为测试失败自动附加最近 10 条日志到报告?
解读
面试官抛出此题,核心想验证三件事:
- 你是否真的在生产环境定位过失败用例,知道“日志是现场第一要素”;
- 你是否熟悉 Pytest 的钩子(hook)体系,能用“官方推荐方式”而非野路子改源码;
- 你是否能把“日志收集”与“报告生成”解耦,做到失败才收集、不影响通过用例性能、不污染全局日志。
国内一线厂(阿里、腾讯、字节、美团)的 CI 平均一次全量用例 3k~2w 条,失败率 2%~8%。如果每条用例都把完整日志落盘,一天就是几百 GB 的无效 IO。因此“失败才捞最近 10 行”是性价比最高的方案,也是面试官心中的“标准答案”。
知识点
- pytest_runtest_makereport:最权威的用例结果钩子,可以拿到 outcome、nodeid、用例对象。
- caplog 内置 fixture:Pytest 自动帮你把日志收集到内存(logging 模块的 StringIO),无需手动切流。
- report.longrepr.addsection:官方 API,可在终端、HTML、Allure、Jenkins 等任何格式报告里追加自定义段落,不会丢格式。
- logging 队列长度控制:用
caplog.handler.records[-10:]切片即可,O(1) 复杂度,内存恒定。 - 并发安全:pytest-xdist 并行时,caplog 是 per-worker 隔离的,不会串行;钩子函数里禁止写全局可变对象,避免 race condition。
- 国内合规:日志里常带手机号、订单号,需脱敏。可在钩子层统一正则替换,防止泄露到 CI 报告。
答案
下面给出“开箱即用”的 conftest.py 代码,满足:
- 仅失败用例触发;
- 无论终端、HTML、Allure 都能看见;
- 并发安全;
- 10 行以内日志,不额外落盘。
# conftest.py
import logging
import pytest
from _pytest.reports import TestReport
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report: TestReport = outcome.get_result()
# 只在 call 阶段失败且是实际失败(非 setup/teardown)才收集
if report.when == "call" and report.failed:
# 拿到当前用例的 caplog 实例
caplog = item.funcargs.get("caplog")
if caplog:
# 取最近 10 条
recent = caplog.records[-10:]
# 拼接成易读格式
content = "\n".join(
f"{rec.levelname} {rec.name} {rec.getMessage()}" for rec in recent
)
# 追加到报告
report.longrepr.addsection("最近 10 条日志", content, sep="-")
使用方式:
- 用例里正常写
logging.info(...),无需任何改动; - 运行
pytest --html=report.html或pytest --alluredir=./allure,失败用例下方会自动出现“最近 10 条日志”段落; - 通过用例零额外开销。
拓展思考
- 动态条数:可用
pytest.ini里加log_recent_lines = 20,在钩子中读item.config.getini("log_recent_lines"),实现项目级可配。 - 日志级别过滤:只拿 ERROR 以上?在切片前加
errors = [r for r in caplog.records if r.levelno >= logging.ERROR][-10:]。 - 异步代码:pytest-asyncio 的 caplog 同样适用,因为底层是同一个 LogCaptureHandler。
- 分布式追踪:国内微服务普遍接入 SkyWalking、Jaeger,可把 trace-id 注入日志,钩子中把 trace-id 也打到报告,方便一键跳转链路平台。
- 性能极限压测:若单条用例日志 >10k 行,可把 caplog 换成
queuehandler + deque(maxlen=10),避免内存暴涨。