关键字 开发-07 log日志配置

1. pytest内置fixture 的caplog的配置

pytest 自动捕获级别为 WARNING 或以上的日志消息,并以与捕获的 stdout 和 stderr 相同的方式在每个失败测试的各自部分中显示它们。
日志级别如下,级别由低到高

  1. DEBUG
  2. INFO
  3. WARNING
  4. ERROR
  5. CRITICAL

在pytest.ini文件中,增加如下log日志配置信息

# pytest.ini
log_cli = true
log_cli_level = info
log_cli_format = %(asctime)s %(filename)s:%(lineno)s [%(levelname)s]: %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file =
log_file_level = info
log_file_format = %(asctime)s %(filename)s:%(lineno)s [%(levelname)s]: %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S

配置文件说明:

log_cli = true: log_cli 是控制台实时输出日志,可以设置True 和 False,也可以设置1 和 0,默认是关闭状态,当 log_cli = 0 或默认的 False 状态时,命令行输入 pytest 运行用例,在控制台输出是按每个模
块显示运行结果
log_cli_level = info:设置日志等级
log_cli_format: 参数是设置日志格式
log_cli_date_format 参数设置日期显示格式
log_file 参数指定日志文件报存的文件的地址
log_file_level = info: 保存日志文件中的级别
log_file_format:保存log文件中的日志格式
log_file_date_format: 保存log文件中的日志日期格式

2. 封装读取log配置

在 utils.py 下新建一个 log.py 文件封装读取pytest的log日志相关配置。

# utils/log.py
import logging
from datetime import datetime
from pathlib import Path

log = logging.getLogger(__name__)

def remove_log_by_create_time(log_dir: Path, count=4, suffix='.log'):
    """
    判断log目录文件大于4个,按文件创建时间删除
    :param log_dir: log日志目录
    :param count: 保留log文件数量
    :param suffix: 查找log文件后缀
    :return: None
    """
    if isinstance(log_dir, Path):
        p = log_dir
    elif isinstance(log_dir, str):
        p = Path(log_dir)
    else:
        log.error(f"文件路径参数不合法: {log_dir}")
        return
    if not p.exists():
        log.error(f"文件路径不存在: {log_dir}")
        return
    # p.iterdir(): 获取全部p路径下的目录和文件,返回迭代器,
    all_logs = [item for item in p.iterdir() if item.is_file() and item.suffix == suffix] # 找出.log后缀名的文件
    # 按创建时间倒叙
    #stat()函数返回一个包含文件信息的对象。其中,st_mtime属性表示了文件的最后修改时间。它以浮点数形式表示,单位是秒
    all_logs.sort(key=lambda x: x.stat().st_mtime, reverse=True)  # 倒叙,从大到小
    for item in all_logs[count:]:  # count=4,说明指定只能存5个log日志文件,这里删除表示只保留4个log文件,因为程序运行会自动新增一个,所以删完保留4个。
        item.unlink()  # 删除多余的

def set_log_format(config):
    """设置 log 日志格式"""
    current_time = datetime.now().strftime('%Y%m%d_%H%M%S')
    # 只保留最近 5 个 log 文件
    remove_log_by_create_time(log_dir=Path(config.rootdir).joinpath('logs'))
    if not config.getini('log_file') and not config.getoption('log_file'):
        config.option.log_file = Path(config.rootdir).joinpath('logs', f'{current_time}.log')
    if config.getini('log_file_format') == '%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s' \
            and not config.getoption('log_file_format'):
        config.option.log_file_format = "%(asctime)s [%(levelname)s]: %(message)s"
    if config.getini('log_file_date_format') == '%H:%M:%S' and not config.getoption('log_file_date_format'):
        config.option.log_file_date_format = "%Y-%m-%d %H:%M:%S"
    # 设置 日志文件在控制台的输出格式
    if not config.getini('log_cli_format') and not config.getoption('log_cli_format'):
        config.option.log_cli_format = '%(asctime)s [%(levelname)s]: %(message)s'
    if not config.getini('log_cli_date_format') and not config.getoption('log_cli_date_format'):
        config.option.log_cli_date_format = '%Y-%m-%d %H:%M:%S'

2.1 初始化加载log日志配置

我们可以使用pytest_configure钩子,初始化加载log配置。

# conftest.py
from utils.log import set_log_format
def pytest_configure(config):
    # 配置日志文件和格式,钩子函数
    set_log_format(config)

然后我们将print打印的信息,全部写成log.info进行输出。之前忘记在execute_yaml_case函数中,添加request数据的渲染,所以现在加进去。

                    elif item == "request":
                        # 渲染读取的request数据
                        t2 = jinja2.Template(json.dumps(value),variable_start_string='${', variable_end_string='}')
                        request_value = json.loads(t2.render(**self.context))
                        log.info(f"发送request 请求: {request_value}")
                        request_session = args.get('requests_session')
                        BASE_URL = base_url if base_url else args.get('base_url')
                        response = request_session.send_request(base_url=BASE_URL, **request_value)
                        log.info(f'执行结果:{response.text}')

最后运行:pytest .\data\test_login.yml,输入结果如下:

日志文件创建成功

posted @ 2023-12-01 10:09  dack_deng  阅读(65)  评论(0编辑  收藏  举报