pytest 日志模块的简单介绍

1.日志的作用

在程序中,日志主要的作用有:

  • 程序调试
  • 了解程序运行是否正常
  • 故障分析与问题定位
  • 用户行为分析

2.日志的等级

主要分为5种:

  • DEBUG:最详细的日志信息
  • info:仅次于DEBUG,通常是只记录关键节点信息、
  • WARNING:当某些不期望的事情发生时记录的信息,但是此时应用程序还是能正常运行
  • ERROR:由于一个严重的问题导致某些功能不能正常运行时记录的信息
  • CRITICAL:当发生严重错误,导致应用程序不能继续运行时记录的信息
    代码如下:
import logging

logging.basicConfig(level=logging.INFO)
logging.info("info")
logging.debug("debug")
logging.warning("warning")
logging.error("error")
logging.critical("critical")

导入logging模块,在该模块中设置了每个等级级别分数,critical是最高的,在上面代码中,若不设置level=logging.INFO,默认是WARNING,可用basicConfig设置级别。上面代码输出如下:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

输出:
第一列是日志级别,第二列是执行的用户,第三列是打印的信息

INFO:root:info
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical

3.logging模块的使用

logging模块使用有两种方式:

  1. 使用logging提供的模块级别的函数
  2. 使用Logging日志系统的四大组件

3.1 logging模块常用函数

在这里插入图片描述

3.2.logging模块的四大组件

  • loggers:提供应用程序代码直接使用的接口
  • handlers:用于将日志记录发送到指定的目的位置
  • filters:提供更细粒度的日志过滤功能,用于决定哪些日志将会被输出
  • formatters:用于控制日志信息的最终输出格式
pytest 测试框架中,封装日志功能可以通过自定义日志收集器和配置机制来实现,以提升日志的可读性、结构化程度以及便于后续分析。以下是一种可行的日志功能封装方式: ### 1. 封装日志收集器 可以在 `conftest.py` 文件中使用 pytest 提供的钩子函数 `pytest_configure` 和 `pytest_runtest_makereport` 来动态配置日志路径并记录测试过程中的异常信息。 例如,通过 `pytest_configure` 动态生成日志文件路径,并结合 Python 标准库 `logging` 模块进行日志格式设置: ```python import logging import os from datetime import datetime def pytest_configure(config): # 创建 log 存储目录 log_dir = os.path.join(config.rootdir, 'log') if not os.path.exists(log_dir): os.makedirs(log_dir) # 动态生成日志文件名 time_now = datetime.now().strftime('%Y_%m_%d_%H_%M_%S') log_file = os.path.join(log_dir, f'{time_now}.log') # 配置日志系统 logging.basicConfig( filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) # 可选:将日志输出到控制台 console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) logging.getLogger('').addHandler(console_handler) ``` 上述代码实现了日志路径的动态配置,并统一了日志输出格式。 ### 2. 记录测试失败信息 使用 `pytest_runtest_makereport` 钩子函数捕获测试失败时的异常信息,并将其结构化为 JSON 格式写入日志文件: ```python import json def pytest_runtest_makereport(item, call): outcome = item.ihook.pytest_runtest_make_report(item=item, call=call) if call.when == "call" and outcome.excinfo is not None: msg = { "module": item.location[0], "function": item.name, "line": item.location[1], "message": str(outcome.excinfo.value).replace("\n", ":") } logging.error(json.dumps(msg, indent=4, ensure_ascii=False)) return outcome ``` 该方法会在每次测试用例执行失败时,将模块名、函数名、错误行号及异常信息以结构化的 JSON 格式写入日志文件中[^2]。 ### 3. 日志管理与封装建议 为了进一步增强日志管理的灵活性和可扩展性,可以考虑将日志功能封装为一个独立的模块,如 `logger.py`: ```python # logger.py import logging class TestLogger: def __init__(self, name="test_logger"): self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) def info(self, message): self.logger.info(message) def error(self, message): self.logger.error(message) def warning(self, message): self.logger.warning(message) ``` 然后在 `conftest.py` 中调用该模块: ```python from logger import TestLogger test_logger = TestLogger() def pytest_runtest_setup(item): test_logger.info(f"Setting up {item.name}") def pytest_runtest_teardown(item, nextitem): test_logger.info(f"Tearing down {item.name}") ``` 通过这种方式,可以将日志逻辑从测试框架中解耦,便于维护和复用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值