Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch python warnings with sentry?

With sentry_sdk, the sentry documentation explain how to automatically catch exceptions or logging messages. However, how can I catch a python warning, like a DeprecationWarning that would be raised with

warnings.warn(DeprecationWarning, "warning message")
like image 359
azmeuk Avatar asked Jun 14 '26 12:06

azmeuk


1 Answers

First, We tell python to redirect warnings to the logging system (as mentioned in Ahmed Hany's answer). From: https://docs.python.org/3/library/logging.html#logging.captureWarnings

logging.captureWarnings(capture)

If capture is True, warnings issued by the warnings module will be redirected to the logging system.

Second, Sentry will capture error-level log records by default, but we can adjust this behaviour to also capture warnings. See: https://docs.sentry.io/platforms/python/guides/logging/

Here's a complete example (for django):

settings.py

import logging
import os
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.logging import LoggingIntegration

# Ensure that warnings are enabled
os.environ["PYTHONWARNINGS"] = "default"

# Ensure that logging captures warnings issued by warnings.warn()
logging.captureWarnings(True)

sentry_sdk.init(
    dsn="...",
    integrations=[
        LoggingIntegration(
            level = logging.INFO,           # Capture info and above as breadcrumbs (this is the default)
            event_level = logging.WARNING,  # Send warnings as events (default is logging.ERROR)
        ),
        DjangoIntegration(),
    ],
    ...
)
like image 160
Aaron Avatar answered Jun 17 '26 00:06

Aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!