与pytest一起使用时禁用日志记录

时间:2019-01-08 13:50:26

标签: python-3.x logging pytest

使用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/')

1 个答案:

答案 0 :(得分:2)

默认情况下,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