Search code examples
pythonwarningssentry

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

  • There's no certain API in sentry for sending warnings, However, you need to ensure you're logging these with the general logging infrastructure that you are using.

    For example, if you are using Django, you have to change the logging level to be Warning like below in the settings.py file

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'verbose': {
                'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s'
            }
        },
        'handlers': {
            'console': {
                'level': 'WARNING',
                'class': 'logging.StreamHandler'
            },
        },
        'loggers': {
            "": {
                "level": "WARNING",
                'handlers': ['console'],
                "propagate": True
            }
        }
    }
    

    and no change in sentry config

    import sentry_sdk
    from sentry_sdk.integrations.django import DjangoIntegration
    
    sentry_config = {
        'dsn': os.getenv("SENTRY_DSN", "YOUR CDN"),
        'integrations': [DjangoIntegration()],
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        'traces_sample_rate': 1.0,
        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        'send_default_pii': True
    }
    sentry_sdk.init(**sentry_config)
    

    In case you don't have Logging infrastructure, you can implement your own, check this Question, it has a lot of examples of how you would create a custom logger.

    It's all about changing your level to be WARNING and creating a console handler(StreamHandler), then Sentry will take care of the rest

    Edit: I meant to capture logging.warning(), but for warnings.warn() you have to log them, Python provides a built-in integration between the logging module and the warnings module to let you do this; just call logging.captureWarnings(True) at the start of your script or your custom logger and all warnings emitted by the warnings module will automatically be logged at level WARNING.