|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import random |
| 16 | +import time |
| 17 | +from typing import Iterable |
| 18 | + |
| 19 | +from opentelemetry.metrics import ( |
| 20 | + CallbackOptions, |
| 21 | + Observation, |
| 22 | + get_meter_provider, |
| 23 | + set_meter_provider, |
| 24 | +) |
| 25 | +from opentelemetry.sdk.metrics import MeterProvider, ObservableGauge |
| 26 | +from opentelemetry.sdk.metrics.export import ( |
| 27 | + ConsoleMetricExporter, |
| 28 | + PeriodicExportingMetricReader, |
| 29 | +) |
| 30 | +from opentelemetry.sdk.metrics.view import View |
| 31 | + |
| 32 | +# Create a view matching the observable gauge instrument `observable_gauge` |
| 33 | +# and configure the attributes in the result metric stream |
| 34 | +# to contain only the attributes with keys with `k_3` and `k_5` |
| 35 | +view_with_attributes_limit = View( |
| 36 | + instrument_type=ObservableGauge, |
| 37 | + instrument_name="observable_gauge", |
| 38 | + attribute_keys={"k_3", "k_5"}, |
| 39 | +) |
| 40 | + |
| 41 | +exporter = ConsoleMetricExporter() |
| 42 | + |
| 43 | +reader = PeriodicExportingMetricReader(exporter, export_interval_millis=1_000) |
| 44 | +provider = MeterProvider( |
| 45 | + metric_readers=[ |
| 46 | + reader, |
| 47 | + ], |
| 48 | + views=[ |
| 49 | + view_with_attributes_limit, |
| 50 | + ], |
| 51 | +) |
| 52 | +set_meter_provider(provider) |
| 53 | + |
| 54 | +meter = get_meter_provider().get_meter("reduce-cardinality-with-view", "0.1.2") |
| 55 | + |
| 56 | + |
| 57 | +def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]: |
| 58 | + attrs = {} |
| 59 | + for i in range(random.randint(1, 100)): |
| 60 | + attrs[f"k_{i}"] = f"v_{i}" |
| 61 | + yield Observation(1, attrs) |
| 62 | + |
| 63 | + |
| 64 | +# Async gauge |
| 65 | +observable_gauge = meter.create_observable_gauge( |
| 66 | + "observable_gauge", |
| 67 | + [observable_gauge_func], |
| 68 | +) |
| 69 | + |
| 70 | +while 1: |
| 71 | + time.sleep(1) |
0 commit comments