Skip to content

otelgrpc: Allow adding custom attributes to a request's metrics based on its payload #6026

@pembletonj2-sonrai

Description

@pembletonj2-sonrai

Problem Statement

It's not possible to add custom attributes to the metrics generated by otelgrpc based on the data in the request payloads.

Proposed Solution

A new option can be added to pass a function which will be run on each payload received to generate metric attributes for that request. Example:

otelgrpc.NewServerHandler(otelgrpc.WithMetricAttributesFromPayload(func(payload any) []attribute.KeyValue {
    data1 := extractSomeDataFromPayload(payload)
    data2 := extractOtherDataFromPayload(payload)
    return []attribute.KeyValue{
        attribute.String("key1", data1),
        attribute.String("key2", data2),
    }
}))

key1 and key2 will then be included in the metrics' attributes for this request.

Alternatives

We found an alternative way to add the needed attributes to spans. The span's attributes can be modified from an interceptor:

span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.String("key", value))

The payload can also be accessed from an interceptor, so its data can be used to set a span's attribute. However, it's not possible to do this with metrics.

Prior Art

#3894 discusses setting constant values for metric/span attributes and a PR has been made for it: #5133. This issue builds on this by allowing custom attributes to be computed on a per-request basis rather than being set to a constant value.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions