How can I disable logging while running unit tests in Python Django?


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

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


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?

11/10/2015 6:49:13 PM

Accepted Answer


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

5/30/2015 9:18:21 PM

Since you are in Django, you could add these lines to your

import sys
import logging

if len(sys.argv) > 1 and sys.argv[1] == 'test':

That way you don't have to add that line in every setUp() on your tests.

You could also do a couple of handy changes for your test needs this way.

There is another "nicer" or "cleaner" way to add specifics to your tests and that is making your own test runner.

Just create a class like this:

import logging

from django.test.simple import DjangoTestSuiteRunner
from django.conf import settings

class MyOwnTestRunner(DjangoTestSuiteRunner):
    def run_tests(self, test_labels, extra_tests=None, **kwargs):

        # Don't show logging messages while testing

        return super(MyOwnTestRunner, self).run_tests(test_labels, extra_tests, **kwargs)

And now add to your file:

#(for example, 'utils.mytest_runner.MyOwnTestRunner')

This lets you do one really handy modification that the other approach doesn't, which is to make Django just tests the applications that you want. You can do that by changing the test_labels adding this line to the test runner:

if not test_labels:
    test_labels = ['my_app1', 'my_app2', ...]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow