Data and monitoring · Intermediate · 26 min
Track application errors the way Sentry and Bugsnag do
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · sentry-sdk 3.0.1 · FastAPI 0.165.0 · uvicorn 0.54.0
You will connect a FastAPI app to sentry-sdk 3.0 with release and environment tags, scrub emails and tokens before events leave the app, and watch a local stand-in tracker group repeats, count affected users and alert on new and regressed errors.
On this page
Logs tell you what happened. An error tracker tells you which failures matter. Products such as Sentry and Bugsnag do the same handful of things underneath their dashboards, and once you know them you can set up either one well, or judge a third:
- Capture. An SDK inside your app catches unhandled exceptions, adds the stack trace and context, and sends an event over HTTPS.
- Group. Thousands of events from the same bug become one issue. The tracker builds a grouping key, called a fingerprint in Sentry and a grouping hash in Bugsnag, mostly from the exception type and the stack frames in your own code.
- Context. Each event carries the release (which deploy), the environment (staging or production), the user it happened to and breadcrumbs: the short trail of things that happened just before.
- Impact. Because events carry a user ID, the tracker counts how many people an issue hurts, not just how many times it fired.
- Alerts. The tracker notifies you when an issue is new, and again when an issue you marked as fixed comes back in a later release. That is a regression.
- Privacy. Events contain request data, messages and local variables, which often hold personal data. Scrubbing has to happen in the app, before anything is sent.
In this tutorial you build each of these and watch it work. You install sentry-sdk 3.0 in a small FastAPI shop app. Instead of a real Sentry project, the app sends to a stand-in tracker you write yourself, about 100 lines of standard-library Python. It accepts the same requests Sentry's servers do, prints what arrives, groups events, counts users and prints alerts. Its grouping is a simplified version of what the real products do, but the data it works from is exactly what would reach them. At the end you map every setting to the Bugsnag notifier.
Step 1 · Create the project
Install curl, make a folder for the demo and create a virtual environment. Pin the packages so what you see matches this page. On macOS, curl is already installed, so skip the two apt lines:
sudo apt update
sudo apt install -y curl
mkdir -p ~/errors-demo
cd ~/errors-demo
python3.15 -m venv .venv
.venv/bin/pip install "sentry-sdk==3.0.1" "fastapi==0.165.0" "uvicorn==0.54.0"sentry-sdk 3.0 is a major release. If you have used 2.x, the biggest change for this tutorial is that send_default_pii is gone: a data_collection dictionary now controls what the SDK collects on its own, and it collects more by default than 2.x did. That makes the scrubbing step below more important, not less.
Check it worked
.venv/bin/python -c "from importlib.metadata import version as v; print(v('sentry-sdk'), v('fastapi'), v('uvicorn'))"The command prints 3.0.1 0.165.0 0.54.0.
Step 2 · Write a stand-in tracker
The SDK finds its server from a DSN, a URL of the form https://<public key>@<host>/<project id>. It sends each event as an envelope: a line of JSON for the envelope header, then for each item a line of JSON describing it (type, length) followed by the item itself. The request body is gzip-compressed and goes to /api/<project id>/envelope/ on that host. Envelopes also carry other item types, such as session updates, which the stand-in ignores.
Create collector.py. It decompresses each envelope, appends every error event to events.jsonl so you can inspect it, and keeps issues in memory. Its grouping rule is the core idea of every tracker, cut down: if the event carries a fingerprint, use it; otherwise use the exception type plus the top stack frame from your own code (frames marked in_app). It also lets you list issues and mark one as resolved:
cat > collector.py <<'PY'
import gzip
import json
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ISSUES = {} # grouping key -> issue
def parse_envelope(body):
"""Split a Sentry envelope into (item header, payload) pairs."""
_envelope_header, _, rest = body.partition(b"\n")
items = []
while rest.strip():
raw_header, _, rest = rest.partition(b"\n")
item_header = json.loads(raw_header)
length = item_header.get("length")
if length is None:
payload, _, rest = rest.partition(b"\n")
else:
payload, rest = rest[:length], rest[length + 1:]
items.append((item_header, payload))
return items
def grouping_key(event):
"""A fingerprint wins; otherwise exception type plus the top in-app frame."""
if event.get("fingerprint"):
return "fingerprint:" + "/".join(event["fingerprint"])
exc = event.get("exception", {}).get("values", [{}])[-1]
frames = exc.get("stacktrace", {}).get("frames", [])
frames = [f for f in frames if f.get("in_app")] or frames
top = frames[-1] if frames else {}
return f"{exc.get('type')} at {top.get('module')}.{top.get('function')}"
def title(event):
exc = event.get("exception", {}).get("values", [{}])[-1]
return f"{exc.get('type')}: {exc.get('value')}"
def record(event):
key = grouping_key(event)
issue = ISSUES.setdefault(key, {"id": len(ISSUES) + 1, "key": key, "status": "new",
"events": 0, "users": set()})
issue["title"] = title(event)
release = event.get("release")
if issue["status"] == "new":
issue["status"] = "unresolved"
print(f"ALERT new issue #{issue['id']} in {release}: {issue['title']}", flush=True)
elif issue["status"] == "resolved":
issue["status"] = "regressed"
print(f"ALERT regressed issue #{issue['id']} in {release}: {issue['title']}", flush=True)
issue["events"] += 1
user_id = (event.get("user") or {}).get("id")
if user_id:
issue["users"].add(user_id)
print(f" issue #{issue['id']} [{key}] events={issue['events']} "
f"users={len(issue['users'])} env={event.get('environment')}", flush=True)
def public(issue):
return {**issue, "users": len(issue["users"])}
class Handler(BaseHTTPRequestHandler):
def reply(self, status, payload):
body = json.dumps(payload, indent=2).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/issues":
return self.reply(200, [public(i) for i in ISSUES.values()])
self.reply(404, {"error": "not found"})
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
resolve = re.fullmatch(r"/issues/(\d+)/resolve", self.path)
if resolve:
for issue in ISSUES.values():
if issue["id"] == int(resolve.group(1)):
issue["status"] = "resolved"
return self.reply(200, public(issue))
return self.reply(404, {"error": "no such issue"})
if not re.fullmatch(r"/api/\d+/envelope/", self.path):
return self.reply(404, {"error": "not found"})
if self.headers.get("Content-Encoding") == "gzip":
body = gzip.decompress(body)
for item_header, payload in parse_envelope(body):
if item_header.get("type") == "event":
with open("events.jsonl", "ab") as f:
f.write(payload.strip() + b"\n")
record(json.loads(payload))
self.reply(200, {})
def log_message(self, format, *args):
pass
print("collector listening on http://127.0.0.1:9000", flush=True)
ThreadingHTTPServer(("127.0.0.1", 9000), Handler).serve_forever()
PYStart it in the first terminal, from ~/errors-demo, and leave it running:
.venv/bin/python collector.pyIt listens only on 127.0.0.1, has no authentication and keeps issues only in memory. It is a learning tool, not a tracker to run for real.
Check it worked
The first terminal prints collector listening on http://127.0.0.1:9000. From your command terminal, ask it for issues:
curl -s http://127.0.0.1:9000/issuesIt answers []: no issues yet.
Step 3 · Connect a FastAPI app to the SDK
Keep the SDK set-up in its own module, so you can change it without touching the routes. Create monitoring.py. It reads the DSN, the release and the environment from environment variables. A real DSN does not give access to your data, but it does let anyone send events to your project, so keep it out of the code and out of Git:
cat > monitoring.py <<'PY'
import os
import sentry_sdk
def init():
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
release=os.environ["APP_RELEASE"],
environment=os.environ.get("APP_ENV", "development"),
)
PYSet the release to something that changes with every deploy, such as shop@1.0.0 or a Git commit hash. Without it, the tracker cannot tell you which deploy broke something, or that a fix shipped. Set the environment explicitly too: Sentry's default is production, so a laptop that forgets to set it reports into your production issues.
Now create app.py, a small shop with two routes that fail on purpose. Each request records who the user is, adds a tag and leaves two breadcrumbs before it can fail. The FastAPI integration switches itself on when the SDK sees FastAPI installed, and it gives each request its own scope, so the user and breadcrumbs of one request do not leak into another:
cat > app.py <<'PY'
import sentry_sdk
from fastapi import FastAPI, Header
import monitoring
monitoring.init()
app = FastAPI()
class PaymentDeclined(Exception):
pass
class GatewayTimeout(Exception):
pass
@app.post("/checkout")
async def checkout(email: str, card_token: str, x_user_id: str = Header("anonymous")):
sentry_sdk.set_user({"id": x_user_id})
sentry_sdk.set_tag("payment_provider", "demo-pay")
sentry_sdk.add_breadcrumb(category="cart", message="cart loaded with 3 items", level="info")
sentry_sdk.add_breadcrumb(category="payment", message=f"charging card for {email}", level="info")
if card_token.startswith("tok_declined"):
raise PaymentDeclined(f"card declined for {email} (token {card_token})")
if card_token.startswith("tok_slow"):
raise GatewayTimeout("payment gateway did not answer in 10 seconds")
return {"status": "paid"}
@app.post("/refund")
async def refund(order_id: int, x_user_id: str = Header("anonymous")):
sentry_sdk.set_user({"id": x_user_id})
sentry_sdk.add_breadcrumb(category="refund", message=f"refunding order {order_id}", level="info")
raise GatewayTimeout("refund gateway did not answer in 10 seconds")
PYThe user ID is an internal account ID, not an email address. That is enough to count affected users and to look the person up in your own systems, without sending their name or email to a third party. It is not the whole story, though: the next step shows that the SDK also sends the user's IP address unless you tell it not to.
In the second terminal, from ~/errors-demo, point the SDK at the stand-in and start the app. The DSN below is only for the stand-in; for a real project, put the DSN your tracker gives you in an environment file or your deployment's secret settings instead of typing it:
export SENTRY_DSN="http://localkey@127.0.0.1:9000/1"
export APP_RELEASE="shop@1.0.0"
export APP_ENV="staging"
.venv/bin/uvicorn app:app --port 8000In your command terminal, make a checkout fail as user u-1001:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1001" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_declined_4242"Check it worked
curl prints 500. Within a second the stand-in prints an alert and the issue line, something like:
ALERT new issue #1 in shop@1.0.0: PaymentDeclined: card declined for ada@example.com (token tok_declined_4242)
issue #1 [PaymentDeclined at app.checkout] events=1 users=1 env=stagingThe user's email address and card token are now in the tracker. The next step shows everywhere they went.
Step 4 · Read what an event carries
Create show_last.py, which prints the main fields of the newest event and says whether the email or the token appear anywhere in it:
cat > show_last.py <<'PY'
import json
with open("events.jsonl") as f:
event = json.loads(f.readlines()[-1])
exc = event["exception"]["values"][-1]
print("error: ", exc["type"], "-", exc["value"])
print("release: ", event.get("release"))
print("environment:", event.get("environment"))
print("user: ", event.get("user"))
print("tags: ", event.get("tags"))
print("request: ", event.get("request", {}).get("query_string"))
print("client ip: ", event.get("request", {}).get("env", {}).get("REMOTE_ADDR"))
for crumb in event.get("breadcrumbs", {}).get("values", []):
print("breadcrumb: ", crumb.get("category"), "-", crumb.get("message"))
text = json.dumps(event)
print("has email: ", "ada@example.com" in text)
print("has token: ", "tok_declined_4242" in text)
PY
.venv/bin/python show_last.pyCheck it worked
The output looks like this:
error: PaymentDeclined - card declined for ada@example.com (token tok_declined_4242)
release: shop@1.0.0
environment: staging
user: {'id': 'u-1001'}
tags: {'payment_provider': 'demo-pay'}
request: email=ada%40example.com&card_token=%5BFiltered%5D
client ip: 127.0.0.1
breadcrumb: cart - cart loaded with 3 items
breadcrumb: payment - charging card for ada@example.com
has email: True
has token: TrueRead it closely. The SDK's built-in denylist replaced card_token in the query string with [Filtered], because the key contains token. But the token is still in the exception message, and the email is in the message, the query string and a breadcrumb. The client ip line is the address the request came from: in sentry-sdk 3.0 the user_info category of data_collection is on by default, so the FastAPI integration adds it to every event as REMOTE_ADDR. Here it is 127.0.0.1; in production it is your user's address, which is personal data in most privacy laws. Search the raw event and you will also find both inside stack frame local variables, which sentry-sdk 3.0 collects by default:
grep -o "\"card_token\":\"'tok_declined_4242'\"" events.jsonl | head -n 1That prints "card_token":"'tok_declined_4242'": the card_token local variable of checkout, its value written the way Python prints a string. The denylist filtered the query string but left this variable as it was. Built-in filters work on key names in the places they know about. They cannot know that your message strings or variables hold personal data.
Step 5 · Scrub personal data before it leaves the app
before_send is a function the SDK calls with every error event just before sending it. Whatever it returns is sent; if it returns None, nothing is. It runs inside your process, so scrubbed data never crosses the network. Bugsnag's before_notify callback plays the same role.
Replace monitoring.py with a version that walks the whole event. It replaces the value of any key that names a secret or an email, and rewrites any string that contains an email address, in plain or URL-encoded form, or a card token. It also sets data_collection={"user_info": False}, so the SDK stops adding the client IP address. The user ID you set yourself with set_user is still sent, so user counts keep working. Add the formats of your own secrets to the patterns:
cat > monitoring.py <<'PY'
import os
import re
import sentry_sdk
EMAIL = re.compile(r"[\w.+-]+(?:@|%40)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
CARD_TOKEN = re.compile(r"\btok_\w+")
SECRET_KEYS = ("authorization", "cookie", "email", "password", "secret", "token")
def scrub(value, key=""):
if any(word in key.lower() for word in SECRET_KEYS):
return "[Filtered]"
if isinstance(value, str):
return CARD_TOKEN.sub("[token]", EMAIL.sub("[email]", value))
if isinstance(value, dict):
return {k: scrub(v, str(k)) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [scrub(v, key) for v in value]
return value
def before_send(event, hint):
return scrub(event)
def init():
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
release=os.environ["APP_RELEASE"],
environment=os.environ.get("APP_ENV", "development"),
data_collection={"user_info": False},
before_send=before_send,
)
PYThe email pattern insists that the domain ends in letters. Without that, the release name shop@1.0.0 looks like an email address and gets scrubbed too.
Scrubbing is the safety net. Two habits make it less necessary: keep personal data out of exception messages and breadcrumbs in the first place, and collect less. The data_collection option of sentry_sdk.init turns off whole categories, as user_info does above; add "stack_frame_variables": False to the same dictionary to stop sending local variables too.
Restart the app: press Ctrl+C in the second terminal and run .venv/bin/uvicorn app:app --port 8000 again. The exported variables are still set in that terminal.
Send the same failure, this time as user u-1002, then inspect the new event:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1002" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_declined_4242".venv/bin/python show_last.pyCheck it worked
The error line now reads card declined for [email] (token [token]), the payment breadcrumb reads charging card for [email], the release is still shop@1.0.0, the client IP line reads None because the event no longer carries one, and the last two lines are has email: False and has token: False. The stand-in prints issue #1 ... events=2 users=2: the same issue, now hurting two users.
The first event is still stored unscrubbed. In a real tracker, delete events like that one; scrubbing only protects what is sent after you add it.
Step 6 · Group repeats and count affected users
Grouping decides whether you see one issue or a thousand. Send the declined checkout once more as u-1001, then make the two gateway timeouts happen, one from each route:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1001" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_declined_4242"
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1001" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_slow_1"
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1003" "http://127.0.0.1:8000/refund?order_id=7"The stand-in now shows issue #1 at events=3 users=2: three events, but u-1001 counts once. That is why trackers sort by users affected as well as by event count. One user retrying ten times is less urgent than ten users failing once.
It also opened two new issues, GatewayTimeout at app.checkout and GatewayTimeout at app.refund, because the failures were raised in different functions. Sentry and Bugsnag group by the stack in the same spirit, with far more care. But here both are the same problem: the payment gateway is down. Tell the tracker so with a fingerprint. Replace before_send in monitoring.py so that every GatewayTimeout gets one, whatever code raised it:
cat > monitoring.py <<'PY'
import os
import re
import sentry_sdk
EMAIL = re.compile(r"[\w.+-]+(?:@|%40)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
CARD_TOKEN = re.compile(r"\btok_\w+")
SECRET_KEYS = ("authorization", "cookie", "email", "password", "secret", "token")
def scrub(value, key=""):
if any(word in key.lower() for word in SECRET_KEYS):
return "[Filtered]"
if isinstance(value, str):
return CARD_TOKEN.sub("[token]", EMAIL.sub("[email]", value))
if isinstance(value, dict):
return {k: scrub(v, str(k)) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [scrub(v, key) for v in value]
return value
def before_send(event, hint):
exc_info = hint.get("exc_info")
if exc_info and exc_info[0].__name__ == "GatewayTimeout":
event["fingerprint"] = ["payment-gateway-timeout"]
return scrub(event)
def init():
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
release=os.environ["APP_RELEASE"],
environment=os.environ.get("APP_ENV", "development"),
data_collection={"user_info": False},
before_send=before_send,
)
PYThe hint holds the original exception as exc_info, so you can decide by type rather than by parsing text. Use fingerprints sparingly: too broad a rule merges unrelated bugs into one issue, and then a new bug hides inside an old one.
Restart the app in the second terminal (Ctrl+C, then .venv/bin/uvicorn app:app --port 8000) and send both timeouts again:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1001" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_slow_1"
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1003" "http://127.0.0.1:8000/refund?order_id=7"Check it worked
Both timeouts land in one new issue, #4 [fingerprint:payment-gateway-timeout], ending at events=2 users=2. List all issues to compare:
curl -s http://127.0.0.1:9000/issuesThe JSON shows four issues: #1 with "events": 3 and "users": 2, #2 and #3 from before the fingerprint, and #4 with "events": 2 and "users": 2.
Step 7 · Alert on new and regressed errors
Alerting on every event would bury you. The two alerts worth having from an error tracker are new issue, the first time a grouping key appears, and regression, an event for an issue you marked as resolved. Sentry shows these as the New and Regressed issue states and can alert on them. Bugsnag can send the same kind of notification to email, chat or a pager through its integrations. Everything else, such as error rates, is better handled by the alerting described in writing alerts that page only when users are hurt.
You have already seen new-issue alerts: each ALERT new issue line. Now act out a regression. Say you fixed the declined-checkout bug, so mark issue #1 as resolved:
curl -s -X POST http://127.0.0.1:9000/issues/1/resolveThe reply shows issue #1 with "status": "resolved". Deploy the next release: stop the app in the second terminal with Ctrl+C and start it with a new release name:
export APP_RELEASE="shop@1.0.1"
.venv/bin/uvicorn app:app --port 8000The bug was not really fixed. Send the failure again:
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "X-User-Id: u-1004" "http://127.0.0.1:8000/checkout?email=ada@example.com&card_token=tok_declined_4242"Check it worked
The stand-in prints:
ALERT regressed issue #1 in shop@1.0.1: PaymentDeclined: card declined for [email] (token [token])
issue #1 [PaymentDeclined at app.checkout] events=4 users=3 env=stagingThe alert names the release, which is the point of setting it: you know that shop@1.0.1 brought the bug back, and the title is scrubbed. In Sentry you can also resolve an issue "in the next release", so that events from older versions still running somewhere do not count as a regression.
If many of your users are on prepaid mobile data, as is common across much of Africa, remember that a browser or Android SDK spends their data on every report it sends. Keep breadcrumbs short, avoid attaching large payloads, and if one bug fires thousands of times use the SDK's sample_rate option (a number from 0 to 1) to send only a share of error events. Grouping and user counts still work on the sample.
Step 8 · Map the same set-up to Bugsnag
Everything you set has a direct equivalent in the Bugsnag notifier for Python (pip install bugsnag, version 4.9.2 at the time of writing). The names differ; the ideas do not:
dsnbecomesapi_key, plusendpointfor a self-hosted server.releasebecomesapp_version.environmentbecomesrelease_stage.- Sentry's built-in key denylist corresponds to Bugsnag's
params_filters, which you set yourself. before_sendbecomes abefore_notifycallback.set_user({"id": ...})becomesconfigure_request(user={"id": ...}).add_breadcrumb(...)becomesleave_breadcrumb(...).event["fingerprint"]becomesevent.grouping_hash.- The FastAPI integration becomes
bugsnag.asgi.BugsnagMiddleware.
Here is the same configuration written for Bugsnag. It reuses the scrub function from monitoring.py, and reads the API key from the BUGSNAG_API_KEY environment variable:
cat > bugsnag_setup.py <<'PY'
import os
import bugsnag
from bugsnag.asgi import BugsnagMiddleware
from monitoring import scrub
bugsnag.configure(
api_key=os.environ["BUGSNAG_API_KEY"],
app_version=os.environ["APP_RELEASE"],
release_stage=os.environ.get("APP_ENV", "development"),
params_filters=["authorization", "cookie", "email", "password", "secret", "token"],
)
def scrub_and_group(event):
if type(event.original_error).__name__ == "GatewayTimeout":
event.grouping_hash = "payment-gateway-timeout"
for error in event.errors:
error.error_message = scrub(error.error_message)
for crumb in event.breadcrumbs:
crumb.message = scrub(crumb.message)
event.metadata = scrub(event.metadata)
bugsnag.before_notify(scrub_and_group)
def install(app):
app.add_middleware(BugsnagMiddleware)
PYTo use it, install bugsnag, import bugsnag_setup in app.py in place of monitoring.init(), keep app = FastAPI() and add bugsnag_setup.install(app) on the next line, which registers the middleware with Starlette's add_middleware so @app.post still works, and replace the sentry_sdk calls with their Bugsnag equivalents from the table. Bugsnag's default params_filters already cover password, password_confirmation, cookie and authorization. The list above adds the rest. As with Sentry, the callback is where messages and breadcrumbs get cleaned, because key filters cannot see inside them.
Front-end stacks and source maps
A browser app sends stack traces from minified bundles, so frames point at app.4f3a.js:1:20431 instead of your source. Both trackers fix that with source maps: your build writes a .map file next to each bundle, you upload the maps tagged with the same release or app version that the browser SDK reports, and the tracker uses them to show the original file, line and function. Upload the maps to the tracker instead of serving them publicly if you do not want your source readable by anyone. A release name that differs by one character between the build and the SDK is the usual reason source maps "do not work".
Check it worked
Check that the file is valid Python. This does not need Bugsnag installed:
.venv/bin/python -m py_compile bugsnag_setup.py && echo "bugsnag_setup.py compiles"It prints bugsnag_setup.py compiles. With a real Bugsnag project, a deliberate failure shows up in its dashboard with the app version, release stage, user ID and scrubbed breadcrumbs you set here.
Step 9 · Clean up
Stop the app and the stand-in with Ctrl+C in their terminals. Then remove the demo folder, which holds the virtual environment, the code and events.jsonl. curl stays installed:
cd ~
rm -rf ~/errors-demoCheck it worked
ls ~/errors-demo reports No such file or directory. If you created a real Sentry or Bugsnag project to try this, delete it or the events you sent in the tracker's project settings too.
Next steps
- Put the same request ID and trace ID in your logs, so an error leads you to the lines around it: write structured JSON logs in Python.
- See the slow request behind an error, not only the failure: trace a Python web app with OpenTelemetry.
- Page on user pain, not on every new exception: write alerts that page only when users are hurt.
- Place error tracking among the other signals: understand metrics, logs and traces.
Related tutorials
- Write structured JSON logs in Python with structlogYou will switch a FastAPI app to structlog 26.1, ending with one JSON object per line that carries a request ID, the route, the OpenTelemetry trace ID and redacted secrets, plus readable output for development and jq queries that answer real questions.
- Trace a Python web app with OpenTelemetryYou will add OpenTelemetry tracing to a FastAPI app that calls a second service with httpx, with named resources, your own spans, events and recorded errors, exported first to the terminal and then to a Collector, with sampling set from environment variables.
- How to Build a REST API with FastAPIYou will build a small items API with FastAPI 0.163 on Python 3.15 that validates its input, returns the right HTTP status codes, never shows a stack trace to callers, documents itself, and has automated tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials