【问题标题】:logging disabled when used with pytest与 pytest 一起使用时禁用日志记录
【发布时间】:2019-06-03 05:33:49
【问题描述】:

我在同时使用 pytest 和记录时遇到问题。当我自己运行一个程序时,我可以看到它的消息打印在屏幕上以及文件 test.log 中。

python3 main.py -> prints on terminal, and also in test.log

但是,当我使用 pytest 运行相同的程序时,我只在屏幕上看到消息,但没有创建文件 test.log。

pytest -vs test -> prints only on terminal, but not in test.log

为什么 pytest 会干扰日志记录实用程序,使用 pytest 时我应该如何创建这些日志文件?

我的版本如下:

platform linux -- Python 3.6.7, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 -- /usr/bin/python3

目录结构如下:

├── logger.py
├── main.py
└── test
    ├── __init__.py
    └── test_module01.py

这些文件的代码如下:

# logger.py ===================================
import logging

def logconfig(logfile, loglevel):
    print('logconfig: logfile={} loglevel={}..'.format(logfile,loglevel))
    logging.basicConfig(filename=logfile, level=logging.INFO, format='%(asctime)s :: %(message)s')

def logmsg(log_level, msg):
    print(log_level,': ',msg)
    logging.info('INFO: ' + msg)

# main.py =====================================
from datetime import datetime
from logger import *

def main(BASE_DIR):
    LOG_FILE = BASE_DIR + 'test.log'
    logconfig(LOG_FILE,'INFO')
    logmsg('INFO',"Starting PROGRAM@[{}] at {}=".format(BASE_DIR,datetime.now()))
    logmsg('INFO',"Ending PROGRAM at {}=".format(datetime.now()))

if __name__ == "__main__":
    main('./')

# __init__.py =================================
all = ["test_module01"]

# test_module01.py ============================
import pytest
import main

class TestClass01:
    def test_case01(self):
        print("In test_case01()")
        main.main('./test/')

【问题讨论】:

  • 默认情况下,pytest 会捕获您的程序发出的所有日志记录。这是一个功能 - 这样,如果您想验证程序的日志记录是否按预期工作,您不需要实际解析生成的日志文件并检查测试函数运行时发出的日志记录。您只需使用 caplog 固定装置并获取所有发出的日志记录的列表,这非常方便。
  • 如果您想禁用此功能,请关闭logging 插件:pytest -p no:logging 应该可以解决问题。
  • @hoefling:“-p no:logging”有效,谢谢!请将此作为答案提交,我会接受。另外请补充一些关于如何使用caplog获取日志记录的细节。

标签: python-3.x logging pytest


【解决方案1】:

默认情况下,pytest 会捕获您的程序发出的所有日志记录。这意味着您的代码中定义的所有日志处理程序都将替换为内部使用的自定义处理程序pytest;如果你通过-s,它会将发出的记录打印到终端,否则它什么也不打印,也不做进一步的输出。内部处理程序将捕获从您的代码发出的所有记录。要在测试中访问它们,请使用 caplog 固定装置。示例:假设您需要测试以下程序:

import logging
import time


def spam():
    logging.basicConfig(level=logging.CRITICAL)
    logging.debug('spam starts')
    time.sleep(1)
    logging.critical('Oopsie')
    logging.debug('spam ends')


if __name__ == '__main__':
    spam()

如果你运行程序,你会看到输出

CRITICAL:root:Oopsie

但没有明显的方法可以访问调试消息。使用caplog时没问题:

def test_spam(caplog):
    with caplog.at_level(logging.DEBUG):
        spam()
    assert len(caplog.records) == 3
    assert caplog.records[0].message == 'spam starts'
    assert caplog.records[-1].message == 'spam ends'

如果您不需要日志捕获(例如,使用pytest 编写系统测试时),您可以通过禁用logging 插件将其关闭:

$ pytest -p no:logging

或将其保留在pytest.cfg 中,不必每次都输入:

[pytest]
addopts = -p no:logging

当然,一旦日志捕获被明确禁用,你就不能再依赖caplog了。

【讨论】:

    猜你喜欢
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2011-06-22
    • 2015-04-21
    • 2015-02-01
    • 2012-09-21
    相关资源
    最近更新 更多