Production Error Tracking with Sentry in Django & React
Deploying code without error tracking is like flying a plane blindfolded. You might be flying smoothly, or you might be about to crash into a mountain—you have no idea until it's too late.
Sentry is an open-source error tracking tool that aggregates crashes and monitors performance. It is essential for any full-stack application.
Why not just read logs?
Server logs (Nginx/Gunicorn logs) are messy. They are text files with millions of lines. Sentry groups errors together. If 500 users hit the same bug, Sentry sends you one email saying "IndexError: list index out of range - impacted 500 users," rather than making you read 500 log lines.
Integration: Django (Backend)
1. Install the SDK
pip install --upgrade sentry-sdk
2. Configure settings.py
Initialize the SDK in your settings.py. This hooks into the Django logging framework automatically.
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn="https://[email protected]/0",
integrations=[
DjangoIntegration(),
],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production.
traces_sample_rate=1.0,
# If you wish to associate users to errors (recommended)
send_default_pii=True
)
Now, if you manually raise an exception raise Exception("Test Sentry"), it will appear in your dashboard instantly with the full stack trace, the user ID, and the browser version.
Integration: React (Frontend)
Frontend errors are notoriously hard to debug because they happen on the user's computer, not your server.
1. Install the SDK
npm install --save @sentry/react @sentry/tracing
2. Initialize in index.js
import * as Sentry from "@sentry/react";
import { BrowserTracing } from "@sentry/tracing";
Sentry.init({
dsn: "https://[email protected]/0",
integrations: [new BrowserTracing()],
tracesSampleRate: 1.0,
});
ReactDOM.render(<App />, document.getElementById("root"));
Error Boundaries
React components that crash can take down the whole page (White Screen of Death). Sentry provides an Error Boundary component.
<Sentry.ErrorBoundary fallback={<p>An error has occurred</p>}>
<MyComponent />
</Sentry.ErrorBoundary>
If MyComponent crashes, the user sees a polite error message, and the crash report is sent to you silently.
Performance Monitoring
Sentry isn't just for crashes. It also traces Latency. It can tell you:
"The endpoint /api/users/ took 4 seconds to load."
It breaks this down:
* 0.5s: React rendering
* 0.2s: Network transfer
* 3.3s: Django Database Query
This helps you pinpoint exactly where to optimize (likely using select_related, as we discussed in a previous post!).
Conclusion
Sentry gives you the confidence to deploy. If something breaks, you will know before your users even have time to tweet about it.