在Python Django中运行单元测试时如何禁用日志记录? [英] How can I disable logging while running unit tests in Python Django?

查看:122
本文介绍了在Python Django中运行单元测试时如何禁用日志记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的基于单元测试的测试运行器来测试我的Django应用程序。

I am using a simple unit test based test runner to test my Django application.

我的应用程序本身配置为在settings.py中使用基本的记录器:

My application itself is configured to use a basic logger in settings.py using:

logging.basicConfig(level=logging.DEBUG)

在我的应用程序代码中使用:

And in my application code using:

logger = logging.getLogger(__name__)
logger.setLevel(getattr(settings, 'LOG_LEVEL', logging.DEBUG))

但是,当运行单元测试时,我想禁用日志记录,这样就不会使测试结果输出混乱。有没有一种简单的方式来以全局方式关闭日志记录,以便在运行测试时,应用程序特定的记录器不会将东西写入控制台?

However, when running unittests, I'd like to disable logging so that it doesn't clutter my test result output. Is there a simple way to turn off logging in a global way, so that the application specific loggers aren't writing stuff out to the console when I run tests?

推荐答案

logging.disable(logging.CRITICAL)

将禁用所有级别低于或等于 CRITICAL 的日志记录。可以使用

will disable all logging calls with levels less severe than or equal to CRITICAL. Logging can be re-enabled with

logging.disable(logging.NOTSET)

这篇关于在Python Django中运行单元测试时如何禁用日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆