Search code examples
pythonfastapisentry

Sentry traces_sampler(sampling_context) how to use with FastAPI


In sentry docs there is example

https://docs.sentry.io/platforms/python/configuration/sampling/

def traces_sampler(sampling_context):
    # Examine provided context data (including parent decision, if any)
    # along with anything in the global namespace to compute the sample rate
    # or sampling decision for this transaction

    if "...":
        # These are important - take a big sample
        return 0.5
    else:
        # Default sample rate
        return 0.1

sentry_sdk.init(
    # ...

    traces_sampler=traces_sampler,
)

but there are no typing for sampling_context variable, I have no idea how to filter specific http route in case of FastAPI integration.

Pls advice how to set different sample rate for specific route ?


Solution

  • sampling_context is a dict. For asgi applications which enable asgi sentry integration, it has an asgi_scope key. This is an asgi scope dict, and I hope that base fields like http meta info fields (url, method, etc) must be presented here.
    https://github.com/getsentry/sentry-python/blob/1.19.1/sentry_sdk/integrations/asgi.py#L177 https://asgi.readthedocs.io/en/latest/specs/main.html#connection-scope

    So, I guess the better way to understand what's going on in this filter function is to use a debugger and look at the context variable.

    In my environment (python==3.11, fastapi==0.95.0, sentry-sdk==1.19.0) there is a asgi_scope key contains such info:

    {
      'type': 'http',
      'asgi': {
        'version': '3.0',
        'spec_version': '2.3'
      },
     'http_version': '1.0',
     'server': ('127.0.0.1', 8000),
     'client': ('127.0.0.1', 37458),
     'scheme': 'http',
     'method': 'GET',
     'root_path': '',
     'path': '/',
     'raw_path': b'/',
     'query_string': b'',
     'headers': [...],
     'state': {},
    }
    

    If I were faced with this issue, I would filter it by path, but keep in mind it seems to be easily broken