open-telemetry / opentelemetry-js

OpenTelemetry JavaScript Client
https://opentelemetry.io
Apache License 2.0
2.74k stars 805 forks source link

How to add fields to a fetch request, or adding custom fields to a span. #4873

Closed bitttttten closed 4 weeks ago

bitttttten commented 3 months ago

We can see in our otel viewer that we get fetch requests listed as spans.

Screenshot 2024-07-21 at 01 07 34

How can we attach custom attributes to these fetch requests? For example with graphql, we want to attach what queries are being sent.

    import { trace } from '@opentelemetry/api'

    const res = await fetch(GRAPHQL_URL, {
        method: 'POST',
        body: JSON.stringify({ query, variables }),
    })

    trace.getActiveSpan()?.setAttributes({
        'fetch.query': cleanQuery(query),
    })

    const json = await res.json()

    return json

However this does not seem to work since the active span has finished. Any tips or help would be appreciated 🫶

github-actions[bot] commented 1 month ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 14 days.

pichlermarc commented 4 weeks ago

You can use the applyCustomAttributesOnSpan option when instantiating the fetch instrumentation. This allows you to add a function to add custom attributes there. The fetch span completes before the body is being read as defined by the semantic conventions for http, so that's why it's ended already after the await.

I do, however, usually recommend to add any application specific data to custom spans instead of spans created by instrumentations, as spans created by instrumentations are often following semantic conventions. On a custom span you'll also get full control over what's there so it gives you a certain kind of freedom to add whatever you like.