Pytest:如何将日志重定向到使用tmp_path夹具创建的控制台和tmp文件

问题描述 投票:2回答:1

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

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

关于我所缺少的任何指针以及如何解决这个问题?如果我使用相同的代码但没有固定装置,则在这种情况下,将同时记录到文件和控制台的日志]

python logging pytest fixtures
1个回答
0
投票

您需要将logger(“”)级别设置为INFO或以下,仅设置处理程序级别是不够的。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.