Pytest:如何将日志重定向到控制台和使用tmp_路径创建的tmp文件

2024-04-19 10:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pytest框架编写一个脚本,其中需要将日志重定向到控制台以及使用fixture(tmp_路径)创建的临时文件。我编写了以下代码,正在创建文件,但未观察控制台日志或文件中的日志:

import os
import logging
from datetime import datetime

global LOG_FILENAME

script_name = os.path.splitext(os.path.basename(__file__))[0]
LOG_FILENAME = datetime.now().strftime(script_name + "_%H_%M_%S_%d_%m_%Y.log")

def test_create_file(tmp_path):
    d = tmp_path / "Logs"
    d.mkdir()
    p = d / LOG_FILENAME

    p.write("content")
    logging.info(p.strpath)
    logging.basicConfig(filename=str(p), level=logging.INFO)
    logging.info(str(p))

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    console.setFormatter(formatter)
    logging.getLogger("").addHandler(console)

    logging.info("This is log1 message")
    logging.info("This is log2 message")
    assert p.read_text() == "content"

我希望我的log1和log2消息应该被捕获到我在上面创建的日志文件中,并且在控制台中可见。但这些要求都没有得到满足。 以下是我的输出:

nishantsaha@ztphost:~/home/nishantsaha/tests$ python3 -m pytest -v test_tmpdir.py -s
========================================================== test session starts ==========================================================
platform linux -- Python 3.6.9, pytest-5.1.2, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
Test order randomisation NOT enabled. Enable with --random-order or --random-order-bucket=<bucket_type>
metadata: {'Python': '3.6.9', 'Platform': 'Linux-4.15.0-76-generic-x86_64-with-Ubuntu-18.04-bionic', 'Packages': {'pytest': '5.1.2', 'py': '1.8.0', 'pluggy': '0.13.1'}, 'Plugins': {'random-order': '1.0.4', 'json-report': '1.2.0', 'metadata': '1.8.0'}}
rootdir: /home/nishantsaha/tests
plugins: random-order-1.0.4, json-report-1.2.0, metadata-1.8.0
collected 1 item

test_tmpdir.py::test_create_file FAILED

有没有关于我遗漏了什么以及如何解决这个问题的建议?若我使用相同的代码但并没有fixture,那个么在这种情况下,文件和控制台的日志都会被观察到


Tags: 文件pathpytestimportinfologdatetime
1条回答
网友
1楼 · 发布于 2024-04-19 10:20:24

您需要将记录器(“”)级别设置为INFO或更低,仅设置处理程序级别是不够的

logging.getLogger("").setLevel('INFO')

默认情况下,记录器的级别为WARNING(30)。有效级别是记录器级别和处理程序级别的交集,由getEffectiveLevel()提供

相关问题 更多 >