Python logging在Pytest fixture中使用时无法记录日志

4

我有一个 Pytest + Selenium 项目,希望使用 logging 模块。

然而,当我像这样在 conftest.py 中设置 logging 时:

@pytest.fixture(params=["chrome"], scope="class")
def init_driver(request):
    start = datetime.now()
    logging.basicConfig(filename='.\\test.log', level=logging.INFO)
    if request.param == "chrome":
        options = ChromeOptions()
        options.add_argument("--start-maximized")
        web_driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    if request.param == "firefox":
        web_driver = webdriver.Firefox(GeckoDriverManager().install())
    request.cls.driver = web_driver
    yield
    end = datetime.now()
    logging.info(f"{end}: --- DURATION: {end - start}")
    web_driver.close()

看起来 test.log 根本没有被创建,也没有任何错误消息或其他迹象表明出了什么问题。

我该如何使它工作?


你在实际记录日志之前进行了yield操作,你确定代码已经到达了logging.info部分吗?当你在logging.basisConfig行后直接放置一个logging.info时,你是否会得到一个文件? - Thymen
我尝试过,即使在 logging.basicConfig 之后直接进行日志记录,我也无法获取到文件。 - Mate Mrše
当我在终端直接运行logging.basisConfiglogging.info时,会得到一个test.log文件。这就引出了一个问题,你是否真正运行了代码的那部分?尝试在代码中加入一个打印语句,看看它是否正在运行。 - Thymen
但是你是否在pytest中运行它们?当我在logging.info()之前直接添加一个print语句时,它会被打印到控制台。 - Mate Mrše
我没有,但也许这篇文章可以帮到你? - Thymen
1个回答

7
首先,有两个事实:
  1. 只有在调用它之前没有进行任何日志记录配置(目标记录器没有注册处理程序),logging.basicConfig()才会生效。

  2. pytest向根记录器注册自定义处理程序,以便能够捕获代码中发出的日志记录,因此您可以测试程序的日志记录行为是否正确。

这意味着在夹具中调用logging.basicConfig(filename='.\\test.log', level=logging.INFO)将无效,因为测试运行已经开始,并且由pytest附加了根记录器的处理程序。因此,您有两个选择:
  1. Disable the builtin logging plugin completely. This will stop log records capturing - if you have tests where you are analyzing emitted logs (e.g. using the caplog fixture), those will stop working. Invocation:

    $ pytest -p no:logging ...
    

    You can persist the flag in pyproject.toml so it is applied automatically:

    [tool.pytest.ini_options]
    addopts = "-p no:logging"
    

    Or in pytest.ini:

    [pytest]
    addopts = -p no:logging
    
  2. Configure and use live logging. The configuration in pyproject.toml, equivalent to your logging.basicConfig() call:

    [tool.pytest.ini_options]
    log_file = "test.log"
    log_file_level = "INFO"
    

    In pytest.ini:

    [pytest]
    log_file = test.log
    log_file_level = INFO
    

    Of course, the logging.basicConfig() line can be removed from the init_driver fixture in this case.


我猜第三个选项可能是getLogger,而不是basicConfig,这将让你访问根记录器。不过我不确定它是否有效。 - bwdm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接