How to Disable Logging While Running Unit Tests in Python Django
It is never necessary to log everything while testing because it may flood the terminal with unnecessary log messages. These logs are useful during development but can be distracting when focusing on the actual test results. Disabling logging during unit tests can make our output cleaner and easier to understand.
There are different ways to disable logging in Django. However, the most common ones are:
- Check whether 'test' is in sys.args
- Customize the test runner.
This article guides us through the step-by-step process of disabling logging while running unit tests in Python Django:
Step-by-Step Guide to Disabling Logging in Django while Running Tests
We can disable or suppress logging while running unit tests by configuring Django’s LOGGING setting differently for tests. Follow the steps below:
Step 1: Set up a Django Project
Let's quickly set up the Django project
python -m venv venv
venv\Scripts\activate
pip install django
djnago-admin startproject myproject
cd my project
python manage.py startapp myapp
Add myapp to the INSTALLED_APPS.
Step 2: Configure Logging
First, ensure our Django project has logging configured in our settings.py
file. We may already have a logging configuration, but for demonstration purposes, let's add a basic configuration:
settings.py
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
# Default level to WARNING
'level': 'WARNING',
},
'loggers': {
'django': {
'handlers': ['console'],
# We might be using INFO or DEBUG for development
'level': 'INFO',
'propagate': False,
},
},
}
This configuration logs all messages from Django at the INFO
level or higher to the console.
Step 3: Add a View with Logging
In myapp/views.py, add a view that will log messages:
# myapp/views.py
import logging
from django.http import HttpResponse
# Set up a logger for this module
logger = logging.getLogger('django')
def sample_view(request):
logger.info("This is a debug message from sample_view.")
return HttpResponse("Hello, world!")
Step 4: Create a URL Pattern for the View
Add a URL pattern for the view in 'myapp/urls.py'. If 'urls.py' doesn’t exist, create it:
# myapp/urls.py
from django.urls import path
from .views import sample_view
urlpatterns = [
path('sample/', sample_view, name='sample_view'),
]
Include this URL configuration in our project’s 'urls.py':
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Step 5: Write a Basic Test Case
Create a basic test case in 'myapp/tests.py' to demonstrate logging output.
# myapp/tests.py
from django.test import TestCase
from django.urls import reverse
class SampleViewTest(TestCase):
def test_sample_view(self):
response = self.client.get(reverse('sample_view'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content.decode(), "Hello, world!")
Step 6: Run the Test and Observe the Logging Output
Run the test case to see the logging output in our terminal.
python manage.py runserver
Output:

python manage.py test myapp
Output:

Step 7: Disable Logging While Testing
When running tests, we can override logging configuration to either suppress all logging or adjust the log level to a higher threshold.
Option 1: Disable Logging Completely During Tests
To completely disable logging during tests, we can modify our LOGGING
configuration in the test settings to disable loggers or reduce the log level.
- Open the
settings.py
and find the logging configuration. - Modify the logging setup for the test environment by disabling loggers:
# settings.py
if 'test' in sys.argv:
LOGGING = {
'version': 1,
'disable_existing_loggers': True, # Disable all existing loggers
}
Run the Test Again
Run the test case again to verify that logging has been disabled.
python manage.py test
Output:

This approach effectively disables all logging when tests are run.
Option 2: Create a Custom Test Runner
For more advanced use cases, we can create a custom test runner that overrides the logging configuration specifically for tests. This gives us more granular control over the logging output for our test environment.
Step 1 - Modify Test Runner
# myapp/mytestrunner.py
import logging
from django.test.runner import DiscoverRunner
class NoLoggingTestRunner(DiscoverRunner):
def setup_test_environment(self, **kwargs):
super().setup_test_environment(**kwargs)
# Disable all logging during tests
logging.disable(logging.INFO)
def teardown_test_environment(self, **kwargs):
super().teardown_test_environment(**kwargs)
# Re-enable logging after tests
logging.disable(logging.NOTSET)
Step2 - Update settings.py
Modify 'myproject/settings.py' to use the custom test runner:
# myproject/settings.py
TEST_RUNNER = 'myapp.mytestrunner.NoLoggingTestRunner'
Step 3 - Run Tests
Use the following command to run our tests:
python manage.py test
The custom test runner will suppress all logging messages during test execution.
Output:

Conclusion
By adjusting the logging behavior during tests, we can ensure a cleaner, more focused output while running our Django unit tests. Whether we choose to completely disable logging, suppress specific log levels, or customize logging for individual tests, these steps offer flexibility in controlling how logs are handled during test runs.