-->
Written by: Marlon Colca
Posted on 05 May 2025 - 10 days ago
python logging loguru sentry
In this post, you'll learn how to connect Loguru with Sentry for full visibility over your app's issues.
Loguru gives you elegant logs.
Sentry gives you stack traces, alerts, context and error history.
Together, they make production debugging a breeze.
In this post, you’ll learn how to connect Loguru with Sentry for full visibility over your app’s issues.
Sentry tracks:
pip install sentry-sdk
Then initialize it in your app:
import sentry_sdk
sentry_sdk.init(
dsn="https://<your-key>@o0.ingest.sentry.io/<project-id>",
traces_sample_rate=1.0, # Enable performance monitoring (optional)
)
The key is to forward exceptions to Sentry.
from loguru import logger
import sentry_sdk
def sentry_excepthook(exc_type, exc_value, traceback):
logger.error("Exception caught", exc_info=(exc_type, exc_value, traceback))
sentry_sdk.capture_exception(exc_value)
logger.remove()
logger.add(sys.stderr, backtrace=True, diagnose=True)
logger.configure(
handlers=[
{"sink": sys.stderr, "level": "INFO"},
],
exception_hook=sentry_excepthook
)
Now any uncaught exception is logged and sent to Sentry.
You can manually send to Sentry in critical areas:
try:
1 / 0
except ZeroDivisionError as e:
logger.exception("Division error occurred")
sentry_sdk.capture_exception(e)
You can add user IDs, environments, etc.:
with sentry_sdk.push_scope() as scope:
scope.set_tag("user_id", 42)
scope.set_extra("context", {"foo": "bar"})
sentry_sdk.capture_exception(e)
This helps you debug issues faster in Sentry UI.
from fastapi import FastAPI
from loguru import logger
import sentry_sdk
sentry_sdk.init(dsn="https://...")
app = FastAPI()
@app.get("/")
def crash():
raise RuntimeError("Something exploded!")
With the Loguru hook, this crash is logged and visible in your Sentry dashboard with full context.
Thanks for joining this mini-series on Loguru, one of Python’s most underrated logging tools.
We’ve covered:
Whether you’re building a CLI tool, a FastAPI app, or a distributed system — Loguru has your back with elegant, powerful logging.
Logging doesn’t have to be painful.
With the right setup, it becomes a superpower. 💥
If you found this helpful, feel free to:
Thanks for reading — and happy logging! 🚀