pytest-log

发布于:2025-07-22 ⋅ 阅读:(14) ⋅ 点赞:(0)

问题1:我们在运行测试用例的时候如何记录测试的log,如何使用?

问题2:我写的函数,为了方便log记录,但是在pytest运行时,会兼容pytest且不会重复记录,怎么解决?

1、pytest有内置的log功能,我们只需要配置使用即可。

配置方法:在项目根目录下配置pytest.ini日志内容

[pytest]
log_cli = true
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(name)s:%(filename)s:%(lineno)d - %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file = logs/pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(name)s:%(filename)s:%(lineno)d - %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S

有了上诉配置,pytest运行时,就会将配置参数传给log模块,在代码中直接使用即可。

2、在测试用例中如何使用?

在测试用例中,将日志模块传进去:caplog

class TestDemo:
    def test_log_capture(self,caplog):
        logging.debug("Debug message")

        res = add(1, 2)
        assert res == 3

然后直接调用logging相关的日志方法即可:示例

3、在非pytest环境运行时,如何使用log?

因为pytest有内置的log以及我们配置了相关参数,如果非pytest方式运行,我们就需要手动封装一个log功能,且兼容log不会重复记录。

代码:

# -*- coding: utf-8 -*-
# @Time    : 2025/7/19 22:39
# @Author  : 夏槐
# @Motto   : 遥遥领先,领先不止一点点
# @File    : log_util.py
# @ide     : PyCharm
# log_util.py
import logging
import sys
import os
from logging.handlers import RotatingFileHandler  # 添加日志轮转处理器


def setup_logger(name=None):
    """
    配置并返回一个日志记录器

    参数:
        name (str): 记录器名称,通常使用 __name__

    返回:
        logging.Logger: 配置好的日志记录器
    """
    logger = logging.getLogger(name)

    # 检查是否在 pytest 环境中运行
    if "pytest" in sys.modules:
        # pytest 会自动配置日志,无需额外设置
        logger.debug(f"在 pytest 环境中运行,使用 pytest 的日志配置")
        return logger

    # 如果不是在 pytest 环境中,配置基础日志
    if not logger.handlers:
        # 创建格式化器
        formatter = logging.Formatter(
    '%(asctime)s [%(levelname)8s] %(name)s %(filename)s:%(lineno)d - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)


        # 创建控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)

        # 创建日志目录(如果不存在)
        log_dir = r"..\logs"
        os.makedirs(log_dir, exist_ok=True)

        # 创建文件处理器(添加日志文件支持)
        log_file = os.path.join(log_dir, "单独调试.log")
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=10 * 1024 * 1024,  # 10MB
            backupCount=5,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)

        # 设置日志级别
        logger.setLevel(logging.DEBUG)
        console_handler.setLevel(logging.DEBUG)
        file_handler.setLevel(logging.INFO)  # 文件日志级别设为INFO

        # 添加到记录器
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)  # 添加文件处理器

        # 防止日志传播到根记录器
        logger.propagate = False

        logger.debug(f"初始化独立日志记录器: {name}")
        logger.info(f"日志文件保存在: {os.path.abspath(log_file)}")

    return logger

4、怎么使用?

一般测试case下面,还会封装一些功能,这些功能基本就没办法使用log,我们上诉3中封装了log之后,会检测当前的运行环境,如果是pytest,就用pytest.ini的配置,否则就使用自定义的log配置,且log兼容pytest,下面给出示例:

这里的log就会单独记录在一个调试文件内。pytest运行这个add时,log就会保存在pytest.ini的文件路径中。


网站公告

今日签到

点亮在社区的每一天
去签到