structlog-sentry

2.2.1 · active · verified Fri Apr 10

structlog-sentry is a Python library that provides seamless integration between structlog, a structured logging library, and Sentry, an error tracking and performance monitoring platform. It allows users to send structured log events from their applications directly to Sentry, enhancing debugging and observability. The current version is 2.2.1, and the library is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `structlog` to use `SentryProcessor` to send structured logs and exceptions to Sentry. Ensure `sentry_sdk.init()` is called with your DSN and `structlog.stdlib.add_log_level` (and optionally `add_logger_name`) are placed before `SentryProcessor`.

import sentry_sdk
import structlog
import logging
import os

from structlog_sentry import SentryProcessor

sentry_sdk.init(
    dsn=os.environ.get('SENTRY_DSN', 'YOUR_SENTRY_DSN_HERE'),
    # Optional: Disable Sentry SDK's default logging integration if structlog-sentry handles all Sentry logging
    # integrations=[sentry_sdk.integrations.logging.LoggingIntegration(event_level=None, level=None)]
)

structlog.configure(
    processors=[
        structlog.stdlib.add_logger_name,  # Optional, but recommended. Must be before SentryProcessor
        structlog.stdlib.add_log_level,    # Required. Must be before SentryProcessor
        SentryProcessor(event_level=logging.ERROR), # Sends events ERROR or higher to Sentry
        structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
    ],
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
)

# Standard library logging setup (optional, for non-structlog compatible handlers)
# import sys
# logging.basicConfig(
#     format="%(message)s",
#     stream=sys.stdout,
#     level=logging.INFO,
# )

log = structlog.get_logger()

try:
    1 / 0
except ZeroDivisionError:
    log.error("A division by zero error occurred!", operation="calculate_ratio", user_id=42)

log.info("User activity log.", action="login", username="testuser")

view raw JSON →