|
| 1 | +# Copyright 2020, 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 | +""" |
| 16 | +This example shows how the Observer metric instrument can be used to capture |
| 17 | +asynchronous metrics data. |
| 18 | +""" |
| 19 | +import psutil |
| 20 | + |
| 21 | +from opentelemetry import metrics |
| 22 | +from opentelemetry.sdk.metrics import LabelSet, MeterProvider |
| 23 | +from opentelemetry.sdk.metrics.export import ConsoleMetricsExporter |
| 24 | +from opentelemetry.sdk.metrics.export.batcher import UngroupedBatcher |
| 25 | +from opentelemetry.sdk.metrics.export.controller import PushController |
| 26 | + |
| 27 | +# Configure a stateful batcher |
| 28 | +batcher = UngroupedBatcher(stateful=True) |
| 29 | + |
| 30 | +metrics.set_preferred_meter_provider_implementation(lambda _: MeterProvider()) |
| 31 | +meter = metrics.get_meter(__name__) |
| 32 | + |
| 33 | +# Exporter to export metrics to the console |
| 34 | +exporter = ConsoleMetricsExporter() |
| 35 | + |
| 36 | +# Configure a push controller |
| 37 | +controller = PushController(meter=meter, exporter=exporter, interval=2) |
| 38 | + |
| 39 | + |
| 40 | +# Callback to gather cpu usage |
| 41 | +def get_cpu_usage_callback(observer): |
| 42 | + for (number, percent) in enumerate(psutil.cpu_percent(percpu=True)): |
| 43 | + label_set = meter.get_label_set({"cpu_number": str(number)}) |
| 44 | + observer.observe(percent, label_set) |
| 45 | + |
| 46 | + |
| 47 | +meter.register_observer( |
| 48 | + callback=get_cpu_usage_callback, |
| 49 | + name="cpu_percent", |
| 50 | + description="per-cpu usage", |
| 51 | + unit="1", |
| 52 | + value_type=float, |
| 53 | + label_keys=("cpu_number",), |
| 54 | +) |
| 55 | + |
| 56 | + |
| 57 | +# Callback to gather RAM memory usage |
| 58 | +def get_ram_usage_callback(observer): |
| 59 | + ram_percent = psutil.virtual_memory().percent |
| 60 | + observer.observe(ram_percent, LabelSet()) |
| 61 | + |
| 62 | + |
| 63 | +meter.register_observer( |
| 64 | + callback=get_ram_usage_callback, |
| 65 | + name="ram_percent", |
| 66 | + description="RAM memory usage", |
| 67 | + unit="1", |
| 68 | + value_type=float, |
| 69 | + label_keys=(), |
| 70 | +) |
| 71 | + |
| 72 | +input("Press a key to finish...\n") |
0 commit comments