How To Disable Logging While Running Django Unit Tests?

Better Stack Team
Updated on December 13, 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:

 
logging.disable(logging.CRITICAL)

In settings.py Globally

You can also paste these lines of code in your settings.py 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':
    logging.disable(logging.CRITICAL)

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 settings.py 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:

 
TESTING_MODE = True

Then add this filter to your logging configuration:

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

And assign it to a handler:

 
'filters': ['testing']

🔭 Want to centralize and monitor your python logs?

Go to Logtail and start your log management in 5 minutes.

Better Uptime Dashboard

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github