'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")


Solution 1:[1]

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(),
    ],
    ...
)

Solution 2:[2]

In Python you can either capture a caught exception or the one currently held in sys.exc_info() by not passing an argument:

from sentry_sdk import capture_exception

try:
    a_potentially_failing_function()
except Exception as e:
    # Alternatively the argument can be omitted
    capture_exception(e)

Another common operation is to capture a bare message. A message is textual information that should be sent to Sentry. Typically messages are not emitted, but they can be useful for some teams.

from sentry_sdk import capture_message

capture_message('Something went wrong')

Solution 3:[3]

if Exception:

try:
    ...
except Exception as exc:
    sentry_sdk.capture_exception(exc)

if message:

sentry_sdk.capture_message("xxx")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aaron
Solution 2 Faisal Shahbaz
Solution 3 systemime