在 Django 中排除某些 URL 以进行 Sentry 性能跟踪

Arv*_*and 2 django sentry

我有一个 Django 应用程序,其运行状况检查端点使用django-health-check

url_patterns我添加了以下行:

  url(r'^ht/', include('health_check.urls')),
Run Code Online (Sandbox Code Playgroud)

问题在于健康检查正在满足所有 Sentry 事务限制。

如何排除 Sentry 中的健康检查端点?

Ant*_*ard 9

处理这种情况的方法是使用采样函数根据URL或其他参数来控制采样率。

def traces_sampler(ctx):
    if 'wsgi_environ' in ctx:
        url = ctx['wsgi_environ'].get('PATH_INFO', '')
        if url.startswith('/ht/'):
            return 0  # Don't trace any
    return 1  # Trace all

sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)
Run Code Online (Sandbox Code Playgroud)

这是一个更完整的示例。

def traces_sampler(ctx):
    if ctx['parent_sampled'] is not None:
        # If this transaction has a parent, we usually want to sample it
        # if and only if its parent was sampled.
        return ctx['parent_sampled']
    op = ctx['transaction_context']['op']
    if 'wsgi_environ' in ctx:
        # Get the URL for WSGI requests
        url = ctx['wsgi_environ'].get('PATH_INFO', '')
    elif 'asgi_scope' in ctx:
        # Get the URL for ASGI requests
        url = ctx['asgi_scope'].get('path', '')
    else:
        # Other kinds of transactions don't have a URL
        url = ''
    if op == 'http.server':
        # Conditions only relevant to operation "http.server"
        if url.startswith('/ht/'):
            return 0  # Don't trace any of these transactions
    return 0.1  # Trace 10% of other transactions

sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)
Run Code Online (Sandbox Code Playgroud)