Allure report中添加log日志

转自:Pytest allure中steps中添加日志

 

是否在使用allure时,为了更好的定位问题,会把日志添加上去。类似如下的情行:

复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/7/18 9:12
# @Author  : huzq
# @File    : test_allure.py
import logging

import allure
import pytest

LOG = logging.getLogger(__name__)


def test_example(testfixture):
    with allure.step("First step"):
        LOG.info("There is first step")

    LOG.info("Between steps")

    second = "second"
    with allure.step("Second step"):
        LOG.info("There is %s step", second)
        LOG.info("Another message in second step")

    with allure.step("Outer step"):
        LOG.info("First line outer step")
        LOG.info("Seconds line outer step")
        with allure.step("Inner step"):
            LOG.info("First line for inner step")
            LOG.info("Second line for inner step")
        LOG.info("Lets close outer step with another line")

def test_print():
    ssss()
    ssss2()
    pytest.assume(1==2)

    logging.info("Logging an info message")
    logging.debug("Logging a DEBUG message")
    logging.warning("Sample time is too low!")
    raise Exception

def test_print22():
    ssss()
    ssss2()
    pytest.assume(1==2)

    logging.info("Logging an info message")
    logging.debug("Logging a DEBUG message")
    logging.warning("Sample time is too low!")
    raise Exception

@allure.step('first step')
def ssss():
    logging.info('this is the first step')

@allure.step('2 step')
def ssss2():
    logging.info('this is the first step')
复制代码

执行后,allure显示的日志如下:

有step,有日志。

 是不是感觉还行。但问题来了,一旦日志多了怎么定位问题。要是能在step中将这个step的日志显示出来就更好了。

解决方案:

翻遍了allure及pytest的API文档,倾情奉献:

只需要在conftest.py中加入如下代码:

复制代码
class AllureLogStep:
    def __init__(
        self, capture_handler: _pytest.logging.LogCaptureHandler = None
    ):
        self._capture_handler = capture_handler
        self._io_stack = []

    @allure_commons.hookimpl
    def start_step(self, uuid, title, params):
        if self._capture_handler:
            stream = self._capture_handler.setStream(io.StringIO())
            self._io_stack.append(stream)

    @allure_commons.hookimpl
    def stop_step(self, uuid, exc_type, exc_val, exc_tb):
        if self._capture_handler:
            previous_stream = self._io_stack.pop()
            stream = self._capture_handler.setStream(previous_stream)
            step_logs = stream.getvalue().strip()
            allure.attach(
                step_logs,
                name="log",
                attachment_type=allure.attachment_type.TEXT,
            )


@pytest.hookimpl(trylast=True)
def pytest_configure(config: _pytest.config.Config):
    logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
    handler = _pytest.logging.LogCaptureHandler()
    handler.setFormatter(logging_plugin.formatter)
    handler.setLevel(logging_plugin.log_level)

    logger = logging.getLogger()
    logger.addHandler(handler)

    step_plugin = AllureLogStep(handler)
    allure_commons.plugin_manager.register(step_plugin)

    def unregister_plugin(plugin):
        def unregister():
            allure_commons.plugin_manager.unregister(plugin)

        return unregister

    config.add_cleanup(unregister_plugin(step_plugin))
复制代码

再次执行用例,结果就会如下:

 看,步骤中是不是有log文件了。而且还是单独的step中的日志。

 

posted @ 2023-11-05 15:48  cloudolt  阅读(584)  评论(0编辑  收藏  举报