Profiling and monitoring in Django are essential for identifying performance bottlenecks, optimizing queries, and ensuring smooth application behavior in production. This includes analyzing database queries, CPU/memory usage, and request processing times.
Django provides built-in logging for SQL queries. You can enable it in your settings:
# settings.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"loggers": {
"django.db.backends": {
"level": "DEBUG",
"handlers": ["console"],
},
},
}
This prints all SQL queries executed by Django in the console.
django.db.connection
To analyze queries programmatically:
from django.db import connection
def debug_queries():
queryset = MyModel.objects.filter(name="Django")
print(queryset.query) # Prints the raw SQL query
print(connection.queries) # Prints the list of executed queries
debug_queries()
django-debug-toolbar
django-debug-toolbar
is a powerful tool for profiling Django applications.
pip install django-debug-toolbar
# settings.py
INSTALLED_APPS += ["debug_toolbar"]
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
INTERNAL_IPS = ["127.0.0.1"] # Enable toolbar only for local development
Once configured, django-debug-toolbar
appears in the browser, showing:
✅ Query execution times
✅ Number of queries per request
✅ Slow queries
✅ Cache hits/misses
cProfile
cProfile
is a built-in Python module for profiling execution times.
import cProfile
def slow_function():
sum([i**2 for i in range(10**6)])
cProfile.run("slow_function()")
This prints execution time per function call.
line_profiler
for Function-Level ProfilingInstall line_profiler
:
pip install line-profiler
Example usage:
from line_profiler import LineProfiler
def my_function():
for i in range(1000000):
_ = i ** 2
profiler = LineProfiler()
profiler.add_function(my_function)
profiler.enable()
my_function()
profiler.disable()
profiler.print_stats()
This helps identify slow lines of code.
django-silk
for Request Profilingdjango-silk
provides request profiling and SQL query analysis.
pip install django-silk
INSTALLED_APPS += ["silk"]
MIDDLEWARE += ["silk.middleware.SilkyMiddleware"]
Visit /silk/
to view logs.
New Relic
for Advanced MonitoringNew Relic provides deep performance monitoring for Django apps.
pip install newrelic
To run the server with New Relic monitoring:
newrelic-admin run-program gunicorn myapp.wsgi
Sentry
Sentry is a popular logging tool for tracking performance and errors.
pip install sentry-sdk
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn="YOUR_SENTRY_DSN",
integrations=[DjangoIntegration()],
traces_sample_rate=1.0, # Set lower in production
)
Sentry logs errors and performance bottlenecks automatically.
locust
locust
helps simulate heavy loads and measure response times.
pip install locust
Create a locustfile.py
:
from locust import HttpUser, task, between
class MyLoadTest(HttpUser):
wait_time = between(1, 5)
@task
def test_homepage(self):
self.client.get("/")
Run the test:
locust -f locustfile.py
Visit http://localhost:8089
to simulate traffic.