Line data Source code
1 : // Copyright The OpenTelemetry Authors
2 : // SPDX-License-Identifier: Apache-2.0
3 :
4 : import 'package:dartastic_opentelemetry_api/dartastic_opentelemetry_api.dart';
5 :
6 : /// Implementation of the APIObservableResult interface for asynchronous instruments.
7 : ///
8 : /// ObservableResult is used by asynchronous instruments to collect measurements
9 : /// during observation callbacks. When a callback is invoked, it receives an
10 : /// ObservableResult that it can use to record observations.
11 : ///
12 : /// More information:
13 : /// https://opentelemetry.io/docs/specs/otel/metrics/api/#asynchronous-instruments
14 : class ObservableResult<T extends num> implements APIObservableResult<T> {
15 : /// The list of measurements recorded during this observation.
16 : final List<Measurement<T>> _measurements = [];
17 :
18 : /// Records an observation with this result.
19 : ///
20 : /// This method records a measurement with the specified value and optional
21 : /// attributes. The measurement will be associated with the current timestamp.
22 : ///
23 : /// @param value The observed value to record
24 : /// @param attributes Optional attributes to associate with this observation
25 10 : @override
26 : void observe(T value, [Attributes? attributes]) {
27 : // Make sure we have a valid OTelFactory
28 : if (OTelFactory.otelFactory == null) {
29 1 : if (OTelLog.isWarn()) {
30 1 : OTelLog.warn(
31 : 'Warning: OTelFactory.otelFactory is null in ObservableResult.observe',
32 : );
33 : }
34 : return;
35 : }
36 :
37 : // Add the measurement
38 10 : final measurement = OTelFactory.otelFactory!.createMeasurement<T>(
39 : value,
40 : attributes,
41 : );
42 20 : _measurements.add(measurement);
43 : }
44 :
45 : /// Records an observation with attributes specified as a map.
46 : ///
47 : /// This is a convenience method that converts the map to Attributes
48 : /// and calls observe().
49 : ///
50 : /// @param value The observed value to record
51 : /// @param attributes Map of attribute names to values
52 1 : @override
53 : void observeWithMap(T value, Map<String, Object> attributes) {
54 : if (OTelFactory.otelFactory == null) {
55 1 : if (OTelLog.isWarn()) {
56 1 : OTelLog.warn(
57 : 'Warning: OTelFactory.otelFactory is null in '
58 : 'ObservableResult.observeWithMap',
59 : );
60 : }
61 : return;
62 : }
63 2 : observe(value, attributes.toAttributes());
64 : }
65 :
66 : /// Returns all measurements recorded by this result.
67 : ///
68 : /// This method is used by the SDK to collect measurements after
69 : /// an observation callback has been executed.
70 : ///
71 : /// @return An unmodifiable list of all measurements recorded
72 10 : @override
73 20 : List<Measurement<T>> get measurements => List.unmodifiable(_measurements);
74 : }
|