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

R71*_*R71 5 logging pytest python-3.x

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

python3 main.py -> prints on terminal, and also in test.log
Run Code Online (Sandbox Code Playgroud)

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

pytest -vs test -> prints only on terminal, but not in test.log
Run Code Online (Sandbox Code Playgroud)

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

我的版本如下:

platform linux -- Python 3.6.7, pytest-4.0.2, py-1.7.0, pluggy-0.8.0 -- /usr/bin/python3
Run Code Online (Sandbox Code Playgroud)

目录结构如下:

??? logger.py
??? main.py
??? test
    ??? __init__.py
    ??? test_module01.py
Run Code Online (Sandbox Code Playgroud)

这些文件的代码如下:

# 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/')
Run Code Online (Sandbox Code Playgroud)

hoe*_*ing 6

默认情况下,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()
Run Code Online (Sandbox Code Playgroud)

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

CRITICAL:root:Oopsie
Run Code Online (Sandbox Code Playgroud)

但是没有明显的方法来访问调试消息。使用时没问题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'
Run Code Online (Sandbox Code Playgroud)

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

$ pytest -p no:logging
Run Code Online (Sandbox Code Playgroud)

或者坚持它,pytest.cfg不必每次都输入它:

[pytest]
addopts = -p no:logging
Run Code Online (Sandbox Code Playgroud)

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