|
5 | 5 |
|
6 | 6 | from collections import Counter |
7 | 7 | from collections.abc import Iterator |
8 | | -from contextlib import contextmanager |
| 8 | +from contextlib import AbstractContextManager, contextmanager |
9 | 9 | from dataclasses import dataclass |
10 | 10 | from time import perf_counter |
11 | | -from typing import TYPE_CHECKING |
| 11 | +from typing import TYPE_CHECKING, Protocol |
12 | 12 |
|
13 | 13 | from opentelemetry.metrics import MeterProvider, get_meter_provider |
14 | 14 | from opentelemetry.semconv._incubating.attributes.otel_attributes import ( |
@@ -46,6 +46,18 @@ class ExportResult: |
46 | 46 | error_attrs: Attributes = None |
47 | 47 |
|
48 | 48 |
|
| 49 | +class ExporterMetricsT(Protocol): |
| 50 | + def export_operation( |
| 51 | + self, num_items: int |
| 52 | + ) -> AbstractContextManager[ExportResult]: ... |
| 53 | + |
| 54 | + |
| 55 | +class NoOpExporterMetrics: |
| 56 | + @contextmanager |
| 57 | + def export_operation(self, num_items: int) -> Iterator[ExportResult]: |
| 58 | + yield ExportResult() |
| 59 | + |
| 60 | + |
49 | 61 | class ExporterMetrics: |
50 | 62 | def __init__( |
51 | 63 | self, |
@@ -75,14 +87,14 @@ def __init__( |
75 | 87 | elif endpoint.scheme == "http": |
76 | 88 | port = 80 |
77 | 89 |
|
78 | | - component_type = ( |
79 | | - component_type or OtelComponentTypeValues("unknown_otlp_exporter") |
80 | | - ).value |
81 | | - count = _component_counter[component_type] |
82 | | - _component_counter[component_type] = count + 1 |
| 90 | + component_type_value = ( |
| 91 | + component_type.value if component_type else "unknown_otlp_exporter" |
| 92 | + ) |
| 93 | + count = _component_counter[component_type_value] |
| 94 | + _component_counter[component_type_value] = count + 1 |
83 | 95 | self._standard_attrs: dict[str, AttributeValue] = { |
84 | | - OTEL_COMPONENT_TYPE: component_type, |
85 | | - OTEL_COMPONENT_NAME: f"{component_type}/{count}", |
| 96 | + OTEL_COMPONENT_TYPE: component_type_value, |
| 97 | + OTEL_COMPONENT_NAME: f"{component_type_value}/{count}", |
86 | 98 | } |
87 | 99 | if endpoint.hostname: |
88 | 100 | self._standard_attrs[SERVER_ADDRESS] = endpoint.hostname |
@@ -121,3 +133,21 @@ def export_operation(self, num_items: int) -> Iterator[ExportResult]: |
121 | 133 | else exported_attrs |
122 | 134 | ) |
123 | 135 | self._duration.record(end_time - start_time, duration_attrs) |
| 136 | + |
| 137 | + |
| 138 | +def create_exporter_metrics( |
| 139 | + component_type: OtelComponentTypeValues | None, |
| 140 | + signal: Literal["traces", "metrics", "logs"], |
| 141 | + endpoint: UrlParseResult, |
| 142 | + meter_provider: MeterProvider | None, |
| 143 | + enabled: bool, |
| 144 | +) -> ExporterMetricsT: |
| 145 | + if not enabled: |
| 146 | + return NoOpExporterMetrics() |
| 147 | + |
| 148 | + return ExporterMetrics( |
| 149 | + component_type, |
| 150 | + signal, |
| 151 | + endpoint, |
| 152 | + meter_provider, |
| 153 | + ) |
0 commit comments