Skip to content

Instantly share code, notes, and snippets.

@piraka9011
Last active March 16, 2022 11:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save piraka9011/8289055959bb48e4df46c188dfa1bf94 to your computer and use it in GitHub Desktop.
How to filter Sentry transactions for Django + Celery
"""This is a full example of a trace sampler that filters transactions for:
1. Django views/routes/urls (whatever you want to call them)
2. Celery tasks
Generally, you would put this in your `settings.py` file, but you can put format it as needed for your project of course.
We are assuming you use `django-environ` for secrets management.
"""
import environ
import sentry_sdk
env = environ.Env()
environ.Env.read_env()
SENTRY_ROUTE_RATES = {
"/health/": 0.0,
"/v1/app/view/": 0.01,
"/v1/app2/view2/": 0.01,
}
SENTRY_TRANSACTION_RATES = {
"app.tasks.async_task_1": 0.0,
"app2.tasks.async_task_2": 0.0,
}
DEBUG = True
SENTRY_DSN = env.str("SENTRY_DSN", "")
DEPLOY_ENV = env.str("DEPLOY_ENV", "")
def traces_sampler(sampling_context):
"""Sampling function for Sentry.
See https://docs.sentry.io/platforms/python/guides/django/configuration/sampling/ for more details.
"""
# Sentry's HTTP transactions start before the URL is resolved into a route
# (meaning the transaction's name don't help with filtering).
# Use `wsgi_environ` from the Django integration as it contains the parsed URL data.
if sampling_context.get("wsgi_environ"):
request_route = sampling_context["wsgi_environ"]["PATH_INFO"]
if request_route in SENTRY_ROUTE_RATES:
return SENTRY_ROUTE_RATES[request_route]
transaction_name = sampling_context["transaction_context"]["name"]
if transaction_name in SENTRY_TRANSACTION_RATES:
return SENTRY_TRANSACTION_RATES[transaction_name]
return 0.1 if DEPLOY_ENV == "PRODUCTION" else 1.0
# The actual Sentry SDK initialization.
# Generally you would put this behind a flag to only run it in a deployment environment.
sentry_sdk.init(
dsn=SENTRY_DSN,
integrations=[
CeleryIntegration(),
DjangoIntegration(),
LoggingIntegration(),
RedisIntegration(),
],
traces_sampler=traces_sampler,
environment=DEPLOY_ENV,
release=f"my-app@{my_app.__version__}",
send_default_pii=True,
debug=DEBUG,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment