How To Disable Logging While Running Django Unit Tests?

Better Stack Team
Updated on May 4, 2022

By Disabling Tests At The Start Of The Application

Suppose you want to do it the quick way. In that case, the following line of code will disable any log messages less severe or equal to CRITICAL:


In Globally

You can also paste these lines of code in your file, so you do not need to paste the first line multiple times:

import sys
import logging

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

sys.argv list contains the command-line arguments passed to the script. If some tests are found, logging will be disabled.

Using Filters

While this will not disable the logging globally, you will have more options to go with while developing your application. Create your filter in the file:

from logging import Filter

class NotInTestingFilter(Filter):

    def filter(self, record):
        from django.conf import settings

        return not settings.TESTING_MODE

In the same file, create a variable in which you will say to the program if you are running in the testing mode:


Then add this filter to your logging configuration:

'filters': {
        'testing': {
            '()': NotInTestingFilter

And assign it to a handler:

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack