如何在不破坏原有协议的前提下,插入自定义的日志采集逻辑?
解读
“不破坏原有协议”在国内面试语境里有两层含义:
- 不能改动被测业务代码(保持“开闭原则”);
- 不能破坏 pytest 自身的运行协议(即不能 monkey-patch 核心引擎导致升级就崩)。
因此,面试官想考察的是:
- 你是否熟悉 pytest 的“钩子(hook)”体系与插件规范;
- 能否用官方推荐的“入口点 + hookwrapper”方式,把日志采集做成可插拔组件;
- 是否知道用
pytest-structlog/pytest-reportportal等思路,把日志与用例、fixture、阶段自动关联,而不是裸写print或logging.basicConfig。
一句话:把日志当成“测试资产”而非“调试语句”,且对存量代码零侵入。
知识点
- pytest hook 规范
- 命名规则:
pytest_xxx(config, items)等,放在conftest.py或独立插件包; - hookwrapper:带
yield的钩子,可在 setup/call/teardown 前后插入逻辑,且异常安全。
- 命名规则:
- 官方插件入口点
setuptools的entry_points={"pytest11": "mylog=mycompany.pytest_logplugin"},安装即生效,无需-p;- 符合 PEP 517/518,国内私有 PyPI 同样适用。
- 日志上下文绑定
logging.LoggerAdapter或structlog.bind(),把nodeid、worker_id、timestamp、stage注入每条日志;- 多进程并行(
pytest-xdist)时,用pytest_configure(config)给每个 worker 写独立文件,再归并。
- 阶段细分
pytest_runtest_setup/call/teardown三个 hookwrapper,可统计每个阶段耗时、异常类型;- fixture 级别的日志,通过
pytest_fixture_setup/pytest_fixture_post_finalizer采集。
- 协议兼容
- 不修改
sys.modules['pytest']的任何属性,升级 pytest 主版本无感知; - 日志格式与 CI 侧(Jenkins、GitLab CI、阿里云的云效)的解析规则对齐,避免正则失效。
- 不修改
答案
步骤一:创建独立插件包 mycompany-pytest-logger
mycompany/
├── pytest_logger/
│ ├── __init__.py
│ └── plugin.py
├── setup.py
步骤二:在 plugin.py 实现 hook,不碰业务代码
import json, logging, time, os
import pytest
# 统一 logger,避免重复初始化
logger = logging.getLogger("testaudit")
def pytest_configure(config):
# 仅主进程或单进程模式下初始化一次
if not hasattr(config, "workerinput"):
log_dir = config.option.log_dir or "logs"
os.makedirs(log_dir, exist_ok=True)
fh = logging.FileHandler(os.path.join(log_dir, "testaudit.log"), encoding="utf-8")
fh.setFormatter(logging.Formatter(
"%(asctime)s|%(levelname)s|%(nodeid)s|%(stage)s|%(message)s"))
logger.setLevel(logging.INFO)
logger.addHandler(fh)
@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_setup(item):
nodeid = item.nodeid
logger.info("stage=start_setup", extra={"nodeid": nodeid, "stage": "setup"})
start = time.time()
yield
logger.info("stage=end_setup", extra={"nodeid": nodeid, "stage": "setup",
"duration": time.time() - start})
@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_call(item):
nodeid = item.nodeid
logger.info("stage=start_call", extra={"nodeid": nodeid, "stage": "call"})
start = time.time()
outcome = yield # 捕获用例结果
logger.info("stage=end_call", extra={"nodeid": nodeid, "stage": "call",
"duration": time.time() - start,
"outcome": outcome.excinfo[0].__name__ if outcome.excinfo else "passed"})
@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_runtest_teardown(item):
... # 同上
步骤三:注册插件,不破坏 pytest 协议
setup.py 中写:
setup(
name="mycompany-pytest-logger",
entry_points={"pytest11": ["mylogger = mycompany.pytest_logger.plugin"]},
py_modules=["mycompany.pytest_logger"],
install_requires=["pytest>=6.0"],
)
打包后 pip install 即可,无需项目侧改一行代码。
步骤四:CI 侧消费日志
日志已带 nodeid、stage、duration、outcome,可直接被 ELK / Loki / SLS 采集;
若需结构化,可在 pytest_configure 里把 handler 换成 logging.handlers.HTTPHandler 直推日志中台,实现“测试结束即报表生成”。
拓展思考
- 多进程并行场景
当使用pytest-xdist时,每个 worker 的workerinput属性存在差异,可在pytest_configure里根据workerid写独立文件,再用pytest_xdist_make_scheduler钩子归并,解决日志交叉问题。 - 与覆盖率结合
在pytest_runtest_call的yield前后插入coverage.process_startup(),可把“哪条用例覆盖了哪行代码”写进同一条日志,实现“用例—代码—日志”三维追踪,方便精准回归。 - 敏感信息脱敏
国内金融、医疗项目需过等保/国密测评,可在日志 handler 前加logging.Filter,把身份证号、银行卡号正则脱敏,避免泄密。 - 插件热插拔
利用pytest -p no:mylogger可在一次执行中动态关闭日志,方便开发本地调试;也可通过pytest.ini的addopts = -p mycompany.pytest_logger强制开启,保证生产 CI 不漏采。