How can I prevent sentry from capturing events for some uncaught exceptions and logging messages?

Question:

As recommended by Sentry’s docs [1][2] for their new unified python sdk (sentry_sdk), I’ve configured it with my Django application to capture events on all exceptions or “error”-level logs:

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

sentry_logging = LoggingIntegration(
    level=logging.DEBUG,
    event_level=logging.ERROR
)
sentry_sdk.init(
    dsn="{{sentry_dsn}}",
    integrations=[DjangoIntegration(), sentry_logging]
)

However, since this hooks directly into python’s logging module and internal exception handling, it means anything that uses this Django environment will be shipping events to sentry. There are some tasks (such as interactive manage.py commands, or work in the REPL) that need the Django environment, but for which I don’t want events created in Sentry.

Is there a way to indicate to sentry that I’d like it to not capture events from exceptions or logging calls for the current task? Or a way to temporarily disable it after it’s been globally configured?

Asked By: user85461

||

Answers:

Maybe there’s a better way but in any file you can import logging and disable it like so: logging.disable(logging.CRITICAL). This will disabling logging at the level at or below the parameter (since CRITICAL is the highest it’ll disable all logging).

Answered By: Dmitry M

You can run sentry_sdk.init() (notably without a DSN) again to disable the SDK.

According to the docs for .NET @ https://getsentry.github.io/sentry-dotnet/api/Sentry.SentrySdk.html#Sentry_SentrySdk_Init_System_String_ sentry_sdk.init() “An empty string is interpreted as a disabled SDK”. Yes, I know this is a Python question but their API is generally consistent across languages

Answered By: CAD bloke

Very late to the party, but for anyone that comes to this from April 2021 you can simply:

import sentry_sdk
sentry_sdk.Hub.current.stop_auto_session_tracking()

The call to stop_auto_session_tracking() will always stop sentry errors as long as you include it (1) after you do sentry_sdk.init (2) Before any errors in your application occur.

Answered By: jaitaiwan

The accepted answer to call init with no args did not work for me.

I had to explicitly pass an empty DSN:

import sentry_sdk
sentry_sdk.init(dsn="")

Tested with sentry_sdk 0.19.1 and 1.17.0.

>>> import sentry_sdk
>>> sentry_sdk.Hub.current.client.dsn
"https://[email protected]/..."
>>> sentry_sdk.init(dsn="")
>>> sentry_sdk.Hub.current.client.dsn
''

After calling init with no args, the DSN remained unchanged.

Answered By: A B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.