diff --git a/docs/examples/basic_meter/calling_conventions.py b/docs/examples/basic_meter/calling_conventions.py index 58aeed6c6ff..9ccbeae3901 100644 --- a/docs/examples/basic_meter/calling_conventions.py +++ b/docs/examples/basic_meter/calling_conventions.py @@ -35,7 +35,10 @@ ) clicks_counter = meter.create_counter( - name="clicks", description="number of clicks", unit="1", value_type=int, + name="clicks", + description="number of clicks", + unit="1", + value_type=int, ) labels = {"environment": "staging"} diff --git a/docs/examples/metrics/grocery/grocery.py b/docs/examples/metrics/grocery/grocery.py index ea7f2107a79..dce7f522402 100644 --- a/docs/examples/metrics/grocery/grocery.py +++ b/docs/examples/metrics/grocery/grocery.py @@ -12,11 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from math import inf - -from opentelemetry.sdk.metrics.export import ConsoleExporter from opentelemetry.metrics import get_meter_provider - +from opentelemetry.sdk.metrics.export import ConsoleExporter exporter = ConsoleExporter() @@ -55,25 +52,15 @@ class GroceryStore: - def __init__(self, name): self._name = name def process_order(self, customer_name, potatoes=0, tomatoes=0): - order_counter.add( - 1, - { - "store": self._name, - "customer": customer_name - } - ) + order_counter.add(1, {"store": self._name, "customer": customer_name}) amount_counter.add( (potatoes * 1) + (tomatoes * 3), - { - "store": self._name, - "customer": customer_name - } + {"store": self._name, "customer": customer_name}, ) sold_items_counter.add( @@ -82,7 +69,7 @@ def process_order(self, customer_name, potatoes=0, tomatoes=0): "store": self._name, "customer": customer_name, "item": "potato", - } + }, ) sold_items_counter.add( @@ -91,25 +78,17 @@ def process_order(self, customer_name, potatoes=0, tomatoes=0): "store": self._name, "customer": customer_name, "item": "tomato", - } + }, ) def enter_customer(self, customer_name, account_type): customers_in_store.add( - 1, - { - "store": self._name, - "account_type": account_type - } + 1, {"store": self._name, "account_type": account_type} ) def exit_customer(self, customer_name, account_type): customers_in_store.add( - -1, - { - "store": self._name, - "account_type": account_type - } + -1, {"store": self._name, "account_type": account_type} ) diff --git a/docs/getting_started/otlpcollector_example.py b/docs/getting_started/otlpcollector_example.py index fa2af822613..cb31d7be6f1 100644 --- a/docs/getting_started/otlpcollector_example.py +++ b/docs/getting_started/otlpcollector_example.py @@ -15,10 +15,13 @@ # otcollector.py import time -from opentelemetry import trace +from opentelemetry import metrics, trace +from opentelemetry.exporter.otlp.metrics_exporter import OTLPMetricsExporter from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( OTLPSpanExporter, ) +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PushController from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor diff --git a/exporter/opentelemetry-exporter-opencensus/tests/test_otcollector_metrics_exporter.py b/exporter/opentelemetry-exporter-opencensus/tests/test_otcollector_metrics_exporter.py index d949c6cd334..ec156b3d118 100644 --- a/exporter/opentelemetry-exporter-opencensus/tests/test_otcollector_metrics_exporter.py +++ b/exporter/opentelemetry-exporter-opencensus/tests/test_otcollector_metrics_exporter.py @@ -91,13 +91,22 @@ def test_get_collector_metric_type(self): def test_get_collector_point(self): aggregator = aggregate.SumAggregator() int_counter = self._meter.create_counter( - "testNameIntCounter", "testDescription", "unit", int, + "testNameIntCounter", + "testDescription", + "unit", + int, ) float_counter = self._meter.create_counter( - "testNameFloatCounter", "testDescription", "unit", float, + "testNameFloatCounter", + "testDescription", + "unit", + float, ) valuerecorder = self._meter.create_valuerecorder( - "testNameValueRecorder", "testDescription", "unit", float, + "testNameValueRecorder", + "testDescription", + "unit", + float, ) result = metrics_exporter.get_collector_point( ExportRecord( @@ -142,7 +151,10 @@ def test_export(self): client=mock_client, host_name=host_name ) test_metric = self._meter.create_counter( - "testname", "testdesc", "unit", int, + "testname", + "testdesc", + "unit", + int, ) record = ExportRecord( test_metric, @@ -168,7 +180,10 @@ def test_export(self): def test_translate_to_collector(self): test_metric = self._meter.create_counter( - "testcollector", "testdesc", "unit", int, + "testcollector", + "testdesc", + "unit", + int, ) aggregator = aggregate.SumAggregator() aggregator.update(123) @@ -181,7 +196,8 @@ def test_translate_to_collector(self): ) start_timestamp = Timestamp() output_metrics = metrics_exporter.translate_to_collector( - [record], start_timestamp, + [record], + start_timestamp, ) self.assertEqual(len(output_metrics), 1) self.assertIsInstance(output_metrics[0], metrics_pb2.Metric) @@ -204,26 +220,30 @@ def test_translate_to_collector(self): "environment", ) self.assertEqual( - output_metrics[0].metric_descriptor.label_keys[1].key, "number", + output_metrics[0].metric_descriptor.label_keys[1].key, + "number", ) self.assertIsNotNone(output_metrics[0].resource) self.assertEqual( - output_metrics[0].resource.type, "", + output_metrics[0].resource.type, + "", ) self.assertEqual( output_metrics[0].resource.labels["key_with_str_value"], self._resource_labels["key_with_str_value"], ) self.assertIsInstance( - output_metrics[0].resource.labels["key_with_int_val"], str, + output_metrics[0].resource.labels["key_with_int_val"], + str, ) self.assertEqual( output_metrics[0].resource.labels["key_with_int_val"], str(self._resource_labels["key_with_int_val"]), ) self.assertIsInstance( - output_metrics[0].resource.labels["key_with_true"], str, + output_metrics[0].resource.labels["key_with_true"], + str, ) self.assertEqual( output_metrics[0].resource.labels["key_with_true"], diff --git a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/metrics_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/metrics_exporter/__init__.py index 8e388e9f9e1..2ab7fd2dc88 100644 --- a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/metrics_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/metrics_exporter/__init__.py @@ -315,9 +315,11 @@ def _translate_data( ) argument = type_class[value_type]["gauge"]["argument"] - instrumentation_library_metrics = sdk_resource_instrumentation_library_metrics[ - export_record.resource - ] + instrumentation_library_metrics = ( + sdk_resource_instrumentation_library_metrics[ + export_record.resource + ] + ) instrumentation_library_metrics.metrics.append( OTLPMetric( diff --git a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_metric_exporter.py b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_metric_exporter.py index 841dcff03e4..1887c9ad209 100644 --- a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_metric_exporter.py +++ b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_metric_exporter.py @@ -64,9 +64,9 @@ class TestOTLPMetricExporter(TestCase): def setUp(self): # pylint: disable=arguments-differ self.exporter = OTLPMetricsExporter(insecure=True) self.resource = SDKResource(OrderedDict([("a", 1), ("b", False)])) - self.meter = MeterProvider(resource=self.resource,).get_meter( - "name", "version" - ) + self.meter = MeterProvider( + resource=self.resource, + ).get_meter("name", "version") @patch.dict( "os.environ", @@ -114,14 +114,16 @@ def test_otlp_headers_from_env(self, mock_ssl_channel, mock_secure): exporter = OTLPMetricsExporter() # pylint: disable=protected-access self.assertEqual( - exporter._headers, (("key1", "value1"), ("key2", "value2")), + exporter._headers, + (("key1", "value1"), ("key2", "value2")), ) exporter = OTLPMetricsExporter( headers=(("key3", "value3"), ("key4", "value4")) ) # pylint: disable=protected-access self.assertEqual( - exporter._headers, (("key3", "value3"), ("key4", "value4")), + exporter._headers, + (("key3", "value3"), ("key4", "value4")), ) @patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials") @@ -137,7 +139,14 @@ def test_translate_counter_export_record(self, mock_time_ns): mock_time_ns.configure_mock(**{"return_value": 1}) counter_export_record = ExportRecord( - Counter("c", "d", "e", int, self.meter, ("f",),), + Counter( + "c", + "d", + "e", + int, + self.meter, + ("f",), + ), [("g", "h")], SumAggregator(), self.resource, @@ -161,7 +170,8 @@ def test_translate_counter_export_record(self, mock_time_ns): instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( - name="name", version="version", + name="name", + version="version", ), metrics=[ OTLPMetric( @@ -203,7 +213,15 @@ def test_translate_counter_export_record(self, mock_time_ns): def test_translate_sum_observer_export_record(self, mock_time_ns): mock_time_ns.configure_mock(**{"return_value": 1}) counter_export_record = ExportRecord( - SumObserver(Mock(), "c", "d", "e", int, self.meter, ("f",),), + SumObserver( + Mock(), + "c", + "d", + "e", + int, + self.meter, + ("f",), + ), [("g", "h")], SumAggregator(), self.resource, @@ -227,7 +245,8 @@ def test_translate_sum_observer_export_record(self, mock_time_ns): instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( - name="name", version="version", + name="name", + version="version", ), metrics=[ OTLPMetric( @@ -294,7 +313,8 @@ def test_translate_updowncounter_export_record(self, mock_time_ns): instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( - name="name", version="version", + name="name", + version="version", ), metrics=[ OTLPMetric( @@ -335,7 +355,15 @@ def test_translate_updowncounter_export_record(self, mock_time_ns): def test_translate_updownsum_observer_export_record(self, mock_time_ns): mock_time_ns.configure_mock(**{"return_value": 1}) counter_export_record = ExportRecord( - UpDownSumObserver(Mock(), "c", "d", "e", int, self.meter, ("f",),), + UpDownSumObserver( + Mock(), + "c", + "d", + "e", + int, + self.meter, + ("f",), + ), [("g", "h")], SumAggregator(), self.resource, @@ -359,7 +387,8 @@ def test_translate_updownsum_observer_export_record(self, mock_time_ns): instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( - name="name", version="version", + name="name", + version="version", ), metrics=[ OTLPMetric( diff --git a/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py b/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py index 5813fba33ca..f96bf67c416 100644 --- a/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py +++ b/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py @@ -37,7 +37,10 @@ def setUp(self): set_meter_provider(metrics.MeterProvider()) self._meter = get_meter_provider().get_meter(__name__) self._test_metric = self._meter.create_counter( - "testname", "testdesc", "unit", int, + "testname", + "testdesc", + "unit", + int, ) labels = {"environment": "staging"} self._labels_key = get_dict_as_key(labels) @@ -101,7 +104,12 @@ def test_min_max_sum_aggregator_to_prometheus(self): def test_counter_to_prometheus(self): meter = get_meter_provider().get_meter(__name__) - metric = meter.create_counter("test@name", "testdesc", "unit", int,) + metric = meter.create_counter( + "test@name", + "testdesc", + "unit", + int, + ) labels = {"environment@": "staging", "os": "Windows"} key_labels = get_dict_as_key(labels) aggregator = SumAggregator() @@ -165,5 +173,10 @@ def __init__( enabled: bool = True, ): super().__init__( - name, description, unit, value_type, meter, enabled=enabled, + name, + description, + unit, + value_type, + meter, + enabled=enabled, ) diff --git a/opentelemetry-api/src/opentelemetry/metrics/__init__.py b/opentelemetry-api/src/opentelemetry/metrics/__init__.py index 050a521ada6..1ef7e869406 100644 --- a/opentelemetry-api/src/opentelemetry/metrics/__init__.py +++ b/opentelemetry-api/src/opentelemetry/metrics/__init__.py @@ -13,27 +13,26 @@ # limitations under the License. -from re import ASCII, compile as compile_ +from abc import ABC, abstractmethod +from logging import getLogger +from re import ASCII +from re import compile as compile_ from typing import cast from opentelemetry.environment_variables import OTEL_PYTHON_METER_PROVIDER -from opentelemetry.util.types import Attributes -from abc import ABC, abstractmethod -from logging import getLogger from opentelemetry.util._providers import _load_provider +from opentelemetry.util.types import Attributes _logger = getLogger(__name__) class Measurement(ABC): - @abstractmethod def __init__(self, value, **attributes: Attributes): pass class DefaultMeasurement(Measurement): - def __init__(self, value, **attributes: Attributes): super().__init__(value, **attributes) @@ -55,7 +54,6 @@ def __init__(self, name, unit_of_measure="", description=""): class _Instrument(Instrument): - def __init__(self, name, unit_of_measure="", description=""): super().__init__( name, unit_of_measure=unit_of_measure, description=description @@ -67,7 +65,6 @@ class Synchronous(Instrument): class Asynchronous(Instrument): - @abstractmethod def __init__(self, name, callback, unit_of_measure="", description=""): super().__init__( @@ -92,7 +89,6 @@ class NonMonotonic(Adding): class Counter(Monotonic, Synchronous): - @abstractmethod def add(self, amount, **attributes): if amount < 0: @@ -100,7 +96,6 @@ def add(self, amount, **attributes): class UpDownCounter(NonMonotonic, Synchronous): - @abstractmethod def add(self, amount, **attributes): pass @@ -115,7 +110,6 @@ class ObservableUpDownCounter(NonMonotonic, Asynchronous): class Histogram(Synchronous, Grouping): - @abstractmethod def record(self, amount, **attributes): pass @@ -126,13 +120,11 @@ class ObservableGauge(Asynchronous, Grouping): class DefaultCounter(Counter, _Instrument): - def add(self, amount, **attributes): return super().add(amount, **attributes) class DefaultUpDownCounter(UpDownCounter, _Instrument): - @abstractmethod def add(self, amount, **attributes): return super().add(amount, **attributes) @@ -156,7 +148,6 @@ class DefaultObservableGauge(ObservableGauge, _Instrument): class Meter(ABC): - @abstractmethod def create_counter( self, name, unit_of_measure="", description="" @@ -195,7 +186,6 @@ def create_observable_up_down_counter( class DefaultMeter(Meter): - def create_counter( self, name, unit_of_measure="", description="" ) -> Counter: @@ -233,7 +223,6 @@ def create_asynchronous_up_down_counter( class MeterProvider(ABC): - @abstractmethod def get_meter( self, name: str, version: str = "", schema_url: str = "" diff --git a/opentelemetry-api/tests/metrics/test_metrics.py b/opentelemetry-api/tests/metrics/test_metrics.py index 6006a94eabf..c652381e1f5 100644 --- a/opentelemetry-api/tests/metrics/test_metrics.py +++ b/opentelemetry-api/tests/metrics/test_metrics.py @@ -15,26 +15,25 @@ from unittest import TestCase from opentelemetry.metrics import ( - Instrument, - Synchronous, - Asynchronous, Adding, + Asynchronous, + Counter, + DefaultCounter, Grouping, + Histogram, + Instrument, Monotonic, NonMonotonic, - Counter, - UpDownCounter, ObservableCounter, - ObservableUpDownCounter, - Histogram, ObservableGauge, - DefaultCounter, + ObservableUpDownCounter, + Synchronous, + UpDownCounter, ) from opentelemetry.test import AssertNotRaisesMixin class TestMetrics(AssertNotRaisesMixin, TestCase): - def test_name_regex(self): with self.assertNotRaises(Exception): diff --git a/opentelemetry-distro/src/opentelemetry/distro/__init__.py b/opentelemetry-distro/src/opentelemetry/distro/__init__.py index 28554401508..6f0a08d7e4c 100644 --- a/opentelemetry-distro/src/opentelemetry/distro/__init__.py +++ b/opentelemetry-distro/src/opentelemetry/distro/__init__.py @@ -21,14 +21,18 @@ from opentelemetry import trace from opentelemetry.environment_variables import ( + OTEL_METRICS_EXPORTER, OTEL_PYTHON_ID_GENERATOR, OTEL_TRACES_EXPORTER, ) from opentelemetry.instrumentation.configurator import BaseConfigurator from opentelemetry.instrumentation.distro import BaseDistro -from opentelemetry.sdk.resources import SERVICE_NAME, Resource from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter +from opentelemetry.sdk.trace.export import ( + BatchSpanProcessor, + MetricsExporter, + SpanExporter, +) from opentelemetry.sdk.trace.id_generator import IdGenerator logger = getLogger(__file__) @@ -36,6 +40,7 @@ EXPORTER_OTLP = "otlp" EXPORTER_OTLP_SPAN = "otlp_proto_grpc_span" +EXPORTER_OTLP_METRIC = "otlp_proto_grpc_metric" RANDOM_ID_GENERATOR = "random" _DEFAULT_ID_GENERATOR = RANDOM_ID_GENERATOR @@ -47,6 +52,7 @@ def _get_id_generator() -> str: def _get_exporter_names() -> Sequence[str]: trace_exporters = environ.get(OTEL_TRACES_EXPORTER) + metrics_exporters = environ.get(OTEL_METRICS_EXPORTER) exporters = set() @@ -80,8 +86,8 @@ def _get_exporter_names() -> Sequence[str]: def _init_tracing( exporters: Sequence[SpanExporter], id_generator: IdGenerator ): - # if env var OTEL_RESOURCE_ATTRIBUTES is given, it will read the service_name - # from the env variable else defaults to "unknown_service" + # if env var OTEL_RESOURCE_ATTRIBUTES is given, it will read the + # service_name from the env variable else defaults to "unknown_service" provider = TracerProvider( id_generator=id_generator(), ) @@ -105,7 +111,8 @@ def _import_tracer_provider_config_components( entry_point = component_entry_points.get(selected_component, None) if not entry_point: raise RuntimeError( - "Requested component '{}' not found in entry points for '{}'".format( + "Requested component '{}' " + "not found in entry points for '{}'".format( selected_component, entry_point_name ) ) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py index d6f683ed352..379830071f2 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py @@ -12,24 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -<<<<<<< HEAD -======= from opentelemetry.metrics import ( Asynchronous, - Instrument, Counter, - UpDownCounter, - ObservableCounter, - ObservableUpDownCounter, Histogram, - ObservableGauge, + Instrument, + Measurement, Meter, MeterProvider, - Measurement, + ObservableCounter, + ObservableGauge, + ObservableUpDownCounter, + UpDownCounter, ) - ->>>>>>> More metrics from opentelemetry.util.types import Attributes @@ -40,7 +36,6 @@ def __init__(self, value, **attributes: Attributes): class _Instrument(Instrument): - def __init__(self, name, unit_of_measure="", description=""): super().__init__( name, unit_of_measure=unit_of_measure, description=description @@ -51,13 +46,12 @@ def __init__(self, name, unit_of_measure="", description=""): class _Asynchronous(Asynchronous, _Instrument): - def __init__(self, name, callback, unit_of_measure="", description=""): super().__init__( name, callback, unit_of_measure=unit_of_measure, - description=description + description=description, ) self._callback = callback @@ -88,7 +82,6 @@ class ObservableGauge(ObservableGauge, _Asynchronous): class Meter(Meter): - def create_counter( self, name, unit_of_measure=None, description=None ) -> Counter: @@ -123,7 +116,6 @@ def create_asynchronous_up_down_counter( class MeterProvider(MeterProvider): - def __init__(self, **configuration): self._configuration = configuration diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/view.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/view.py index 0dd75c6887b..2d827252b9c 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/view.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/view.py @@ -86,7 +86,7 @@ def __init__( def get_view_data(self, labels): """Find an existing ViewData for this set of labels. If that ViewData - does not exist, create a new one to represent the labels + does not exist, create a new one to represent the labels """ active_labels = [] if self.view_config == ViewConfig.LABEL_KEYS: