Skip to content

[Metrics API/SDK] ASync instruments - pass state to the callback #1389

@marcalff

Description

@marcalff

Greetings.

From the spec:

https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#asynchronous-counter-creation

The API SHOULD provide some way to pass state to the callback. OpenTelemetry API authors MAY decide what is the idiomatic approach (e.g. it could be an additional parameter to the callback function, or captured by the lambda closure, or something else).

For async counters creation, please change:

  • the callback functions to add a void * state parameter,
  • the create observable counter methods to pass a void * state parameter
    so this gets easier to use:
long counter_foo;
long counter_bar;
long counter_baz;

void generic_callback(void *state,
                      opentelemetry::metrics::ObserverResult<long> &obs) {
  long *counter = static_cast<long *>(state);
  obs.Observe(*counter);
}

void register_my_counter(const char *name, long *counter) {
  void *state = counter;
  g_otel_meter->CreateLongObservableCounter(name, generic_callback, state, "",
                                            "");
}

register_my_counter("foo", &counter_foo);
register_my_counter("bar", &counter_bar);
register_my_counter("baz", &counter_baz);

Without it, the user code would have to define a different callback function for each observable counter,
which is not only inconvenient, but assumes the list of counters is static and known at compile time (it's not).

Regards.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions