Debugging and Logging - potatoscript/django GitHub Wiki
🐞 Debugging & Logging in Django
Debugging and logging are essential skills for every developer, and Django provides powerful tools to help you identify and fix issues in your web applications. In this tutorial, we’ll cover how to debug errors, how to use logging to track application behavior, and how to improve your workflow when developing and deploying Django applications.
🧩 Step 1: Django’s Debugging Features
🛠️ Step 1.1: Debug Mode in Django
Django comes with a powerful debugging tool that’s active when the DEBUG
setting is True
. When you encounter an error, Django’s built-in debugger provides detailed error reports in your browser, showing:
- The traceback of the error.
- The line of code where the error occurred.
- The values of variables at the time of the error.
To enable this feature, make sure DEBUG
is set to True
in your settings.py
:
# settings.py
DEBUG = True
With DEBUG=True
, you’ll see detailed error pages in the browser whenever an exception occurs.
Note: NEVER set
DEBUG=True
in production, as this can expose sensitive information about your application and database.
🛠️ Step 1.2: Django Debug Toolbar
For even more detailed insights into your Django project, you can use the Django Debug Toolbar. This is a third-party tool that provides an interactive panel in your browser with valuable information about each request, such as:
- SQL queries executed during the request.
- Cache hits and misses.
- Template rendering times.
- Request/response headers.
To install it:
-
Install the Debug Toolbar:
pip install django-debug-toolbar
-
Add it to your
INSTALLED_APPS
insettings.py
:# settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', # Add this line ]
-
Add middleware:
# settings.py MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', # other middleware... ]
-
Configure the internal IPs so it works only on your local machine:
# settings.py INTERNAL_IPS = [ '127.0.0.1', ]
-
Run your Django project:
python manage.py runserver
When you access your Django application in your browser, you'll see a panel with valuable debugging information.
🧩 Step 2: Logging in Django
While debugging is great for development, logging is essential for monitoring your application in production. Django provides a built-in logging framework that follows Python’s standard logging module.
🛠️ Step 2.1: Setting Up Logging in Django
To set up logging in Django, you’ll configure it in the settings.py
file. Django allows you to log messages at different levels, such as DEBUG, INFO, WARNING, ERROR, and CRITICAL.
Here’s a basic logging configuration:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # Logs to the console
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log', # Logs to a file
},
},
'loggers': {
'django': {
'handlers': ['console', 'file'], # Logs to both console and file
'level': 'DEBUG', # Adjust this level to control the verbosity
'propagate': True,
},
},
}
In this example:
handlers
: Defines where the logs should go (console or file).loggers
: Specifies which loggers will use the handlers and at what logging level.- Logging Level: You can adjust the logging level.
DEBUG
will show everything, whileERROR
will only log error messages.
🛠️ Step 2.2: Logging Messages
Once you’ve configured logging, you can log messages in your Django views, models, or any other part of your application.
Logging in Views:
import logging
from django.shortcuts import render
# Create a logger
logger = logging.getLogger(__name__)
def my_view(request):
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
return render(request, 'my_template.html')
You can then view the logs in the console or in the log file (debug.log
), depending on your configuration.
Logging in Models:
import logging
from django.db import models
# Create a logger
logger = logging.getLogger(__name__)
class MyModel(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
logger.info(f"Saving MyModel instance: {self.name}")
super().save(*args, **kwargs)
🛠️ Step 2.3: Logging Exceptions
Django also provides an easy way to log unhandled exceptions. You can use logger.exception()
to log an error along with the stack trace. This is especially useful for debugging unexpected errors.
For example, inside a view:
import logging
from django.http import HttpResponseServerError
logger = logging.getLogger(__name__)
def my_view(request):
try:
# Some code that might raise an exception
1 / 0 # Example: Division by zero
except Exception as e:
logger.exception("An error occurred")
return HttpResponseServerError("Something went wrong!")
This will log the exception details (including the traceback) to your log files.
🧩 Step 3: Customizing Logging for Different Environments
You can configure different logging setups based on your environment (development, production, etc.). For instance, in production, you might want to log only errors and critical issues, while in development, you might log everything.
You can use if DEBUG:
in settings.py
to customize logging settings for different environments.
# settings.py
if DEBUG:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
else:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': 'error.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'ERROR',
'propagate': True,
},
},
}
This allows for detailed logging during development and only critical logs in production.
🧩 Step 4: Using Third-Party Logging Tools
If you want more advanced logging features, such as real-time monitoring, alerting, or centralized log management, you can integrate Django with third-party tools like:
- Sentry: A service that helps you monitor and fix crashes in real time.
- Loggly, Papertrail, Splunk: Tools for centralized log management.
You can integrate these tools with Django’s logging framework by installing the relevant Python packages and configuring them in settings.py
.
📝 Summary
Feature | What Happens |
---|---|
Django Debug Mode | Enables detailed error reports in the browser when DEBUG=True . |
Django Debug Toolbar | Provides interactive debugging info, such as SQL queries and cache hits. |
Logging Configuration | Set up logging in settings.py to log messages to console or files. |
Logging Levels | Adjust logging levels (e.g., DEBUG , INFO , ERROR ) for different needs. |
Logging Exceptions | Use logger.exception() to log errors along with stack traces. |
Customizing Logs for Environments | Adjust logging setup for different environments (development/production). |
Third-Party Logging Tools | Integrate tools like Sentry or Loggly for advanced logging and monitoring. |