繁体   English   中英

在运行时更改 pytest 的实时日志级别

[英]Change pytest's live log level during runtime

我正在使用 pytest 的实时日志功能来查看生成的日志记录。 根据文档,我目前正在使用log_cli_level条目在pytest.ini文件中设置日志级别。 但是,能够从代码中更改日志级别是相当实用的。

在检查了 pytest 代码后,我可以看到它在LoggingPlugin class 中设置了self.log_cli_level字段 该插件在此处的插件管理器中注册,密钥为"logging-plugin"

我想这将是使用 PytestPluginManager 的PytestPluginManager getplugin访问插件以获得 LoggingPlugin 的问题,但恐怕我还没有找到访问该管理器的方法。

恐怕我还没有找到访问该经理的方法。

使用request夹具访问测试中的插件管理器:

def test_spam(request):
    mgr = request.session.config.pluginmanager
    logging_plugin = mgr.get_plugin("logging-plugin")

但是,这对于更改实时日志级别不是必需的(并且 IIRC 更改LoggingPlugin.log_cli_level只会在运行测试挂钩中产生影响,而不是在测试用例或夹具中)。 日志捕获和实时日志共享相同的日志级别,因此只需使用caplog固定装置。 这是一个简单的例子:

import logging
import pytest


logger = logging.getLogger(__name__)


def emit_logs():
    logger.info('sample info')
    logger.warning('sample warning')
    logger.error('sample error')
    logger.critical('sample critical')


def test_spam():
    emit_logs()

将产生

-------------------------------- live log call --------------------------------
2020-12-11 16:27:41 [    INFO] sample info (test_spam.py:9)
2020-12-11 16:27:41 [ WARNING] sample warning (test_spam.py:10)
2020-12-11 16:27:41 [   ERROR] sample error (test_spam.py:11)
2020-12-11 16:27:41 [CRITICAL] sample critical (test_spam.py:12)

现在例如将级别提高到CRITICAL

def test_spam(caplog):
    caplog.set_level(logging.CRITICAL)
    emit_logs()

仅产出

-------------------------------- live log call --------------------------------
2020-12-11 16:27:41 [CRITICAL] sample critical (test_spam.py:12)

使用caplog作为上下文管理器:

def test_spam(caplog):
    with caplog.at_level(logging.ERROR):
        emit_logs()

将产生

-------------------------------- live log call --------------------------------
2020-12-11 16:27:41 [   ERROR] sample error (test_spam.py:11)
2020-12-11 16:27:41 [CRITICAL] sample critical (test_spam.py:12)

动态变化的实时日志级别也可以,

def test_eggs(caplog):
    with caplog.at_level(logging.WARNING):
        logger.info("i am not logged")
    logger.info("but i am")

以及将实时日志级别切换到固定装置:

@pytest.fixture
def errors_only(caplog):
    with caplog.at_level(logging.ERROR):
        yield


@pytest.mark.usefixtures("errors_only")
def test_bacon():
    logger.error("i am printed")
    logger.info("but i am not")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM