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" ) Configuration._reset() # pylint: disable=protected-access
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 = OTLPMetricsExporter( headers=(("key3", "value3"), ("key4", "value4")) ) # pylint: disable=protected-access self.assertEqual( exporter._headers, (("key3", "value3"), ("key4", "value4")), )
class TestOTLPMetricExporter(TestCase): def setUp(self): self.exporter = OTLPMetricsExporter() self.counter_metric_record = MetricRecord( Counter( "a", "b", "c", int, MeterProvider( resource=SDKResource(OrderedDict([("a", 1), ( "b", False)]))).get_meter(__name__), ("d", ), ), OrderedDict([("e", "f")]), SumAggregator(), ) def test_translate_metrics(self): # pylint: disable=no-member self.counter_metric_record.instrument.add(1, OrderedDict([("a", "b")])) expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics(metrics=[ OTLPMetric( name="a", description="b", unit="c", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="a", value="b") ], value=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_DELTA), is_monotonic=True, ), ) ]) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([self.counter_metric_record]) self.assertEqual(expected, actual)
def setUp(self): self.exporter = OTLPMetricsExporter() resource = SDKResource(OrderedDict([("a", 1), ("b", False)])) self.counter_metric_record = MetricRecord( Counter( "a", "b", "c", int, MeterProvider(resource=resource, ).get_meter(__name__), ("d", ), ), OrderedDict([("e", "f")]), SumAggregator(), resource, )
def setUp(self): self.exporter = OTLPMetricsExporter(insecure=True) resource = SDKResource(OrderedDict([("a", 1), ("b", False)])) self.counter_metric_record = MetricRecord( Counter( "c", "d", "e", int, MeterProvider(resource=resource, ).get_meter(__name__), ("f", ), ), [("g", "h")], SumAggregator(), resource, ) Configuration._reset() # pylint: disable=protected-access
def test_env_variables(self, mock_exporter_mixin): OTLPMetricsExporter() self.assertTrue(len(mock_exporter_mixin.call_args_list) == 1) _, kwargs = mock_exporter_mixin.call_args_list[0] self.assertEqual(kwargs["endpoint"], "collector:55680") self.assertEqual(kwargs["headers"], "key1:value1;key2:value2") self.assertEqual(kwargs["timeout"], 10) self.assertIsNotNone(kwargs["credentials"]) self.assertIsInstance(kwargs["credentials"], ChannelCredentials)
from opentelemetry.sdk.trace.export import BatchExportSpanProcessor span_exporter = OTLPSpanExporter( # optional # endpoint:="myCollectorURL:55678", # credentials=ChannelCredentials(credentials), # metadata=(("metadata", "metadata")), ) tracer_provider = TracerProvider() trace.set_tracer_provider(tracer_provider) span_processor = BatchExportSpanProcessor(span_exporter) tracer_provider.add_span_processor(span_processor) metric_exporter = OTLPMetricsExporter( # optional # endpoint:="myCollectorURL:55678", # credentials=ChannelCredentials(credentials), # metadata=(("metadata", "metadata")), ) # Meter is responsible for creating and recording metrics metrics.set_meter_provider(MeterProvider()) meter = metrics.get_meter(__name__) # controller collects metrics created from meter and exports it via the # exporter every interval controller = PushController(meter, metric_exporter, 5) # Configure the tracer to use the collector exporter tracer = trace.get_tracer_provider().get_tracer(__name__) with tracer.start_as_current_span("foo"): print("Hello world!")
class TestOTLPMetricExporter(TestCase): def setUp(self): self.exporter = OTLPMetricsExporter(insecure=True) resource = SDKResource(OrderedDict([("a", 1), ("b", False)])) self.counter_metric_record = MetricRecord( Counter( "c", "d", "e", int, MeterProvider(resource=resource, ).get_meter(__name__), ("f", ), ), [("g", "h")], SumAggregator(), resource, ) Configuration._reset() # pylint: disable=protected-access def tearDown(self): Configuration._reset() # pylint: disable=protected-access @patch.dict( "os.environ", { "OTEL_EXPORTER_OTLP_METRIC_ENDPOINT": "collector:55680", "OTEL_EXPORTER_OTLP_METRIC_CERTIFICATE": "fixtures/test.cert", "OTEL_EXPORTER_OTLP_METRIC_HEADERS": "key1:value1;key2:value2", "OTEL_EXPORTER_OTLP_METRIC_TIMEOUT": "10", }, ) @patch("opentelemetry.exporter.otlp.exporter.OTLPExporterMixin.__init__") def test_env_variables(self, mock_exporter_mixin): OTLPMetricsExporter() self.assertTrue(len(mock_exporter_mixin.call_args_list) == 1) _, kwargs = mock_exporter_mixin.call_args_list[0] self.assertEqual(kwargs["endpoint"], "collector:55680") self.assertEqual(kwargs["headers"], "key1:value1;key2:value2") self.assertEqual(kwargs["timeout"], 10) self.assertIsNotNone(kwargs["credentials"]) self.assertIsInstance(kwargs["credentials"], ChannelCredentials) @patch("opentelemetry.sdk.metrics.export.aggregate.time_ns") def test_translate_metrics(self, mock_time_ns): # pylint: disable=no-member mock_time_ns.configure_mock(**{"return_value": 1}) self.counter_metric_record.aggregator.checkpoint = 1 self.counter_metric_record.aggregator.initial_checkpoint_timestamp = 1 self.counter_metric_record.aggregator.last_update_timestamp = 1 expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics(metrics=[ OTLPMetric( name="c", description="d", unit="e", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="g", value="h") ], value=1, time_unix_nano=1, start_time_unix_nano=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_DELTA), is_monotonic=True, ), ) ]) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([self.counter_metric_record]) self.assertEqual(expected, actual)
def test_no_credentials_error( self, mock_ssl_channel, mock_secure, mock_stub ): OTLPMetricsExporter(insecure=False) self.assertTrue(mock_ssl_channel.called)
# create a CollectorSpanExporter span_exporter = OTLPSpanExporter( # optional: # endpoint="myCollectorUrl:55678", # service_name="test_service", # host_name="machine/container name", ) tracer_provider = TracerProvider() trace.set_tracer_provider(tracer_provider) span_processor = BatchExportSpanProcessor(span_exporter) tracer_provider.add_span_processor(span_processor) # create a CollectorMetricsExporter metric_exporter = OTLPMetricsExporter( # optional: # endpoint="myCollectorUrl:55678", # service_name="test_service", # host_name="machine/container name", ) # Meter is responsible for creating and recording metrics metrics.set_meter_provider(MeterProvider()) meter = metrics.get_meter(__name__) # controller collects metrics created from meter and exports it via the # exporter every interval controller = PushController(meter, metric_exporter, 5) # Configure the tracer to use the collector exporter tracer = trace.get_tracer_provider().get_tracer(__name__) with tracer.start_as_current_span("foo"): print("Hello world!")
latencyMetricName = "latency" if "INSTANCE_ID" in os.environ: instanceId = os.environ["INSTANCE_ID"] if not instanceId.strip() == "": latencyMetricName += "_" + instanceId apiBytesSentMetricName += "_" + instanceId apiBytesSentCounter = meter.create_counter(apiBytesSentMetricName, "API request load sent in bytes", "one", int) apiLatencyRecorder = meter.create_valuerecorder(latencyMetricName, "API latency time", "ms", int) # Start Metric Pipeline # Exporter to export metrics to the console exporter = OTLPMetricsExporter() # start_pipeline will notify the MeterProvider to begin collecting/exporting # metrics with the given meter, exporter and interval in seconds # TODO: Auto-Instrumentation will instantiate the MeterProvider before this # file has a chance to instantiate it. Once https://github.com/open-telemetry/opentelemetry-python/issues/1444 # is resolved, this try except block can be removed. try: metrics.get_meter_provider().start_pipeline(meter, exporter, 5) except: logger.warning("Metrics Pipeline was not started.") pass
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") @patch.dict( "os.environ", { OTEL_EXPORTER_OTLP_METRIC_ENDPOINT: "collector:4317", OTEL_EXPORTER_OTLP_METRIC_CERTIFICATE: THIS_DIR + "/fixtures/test.cert", OTEL_EXPORTER_OTLP_METRIC_HEADERS: "key1=value1,key2=value2", OTEL_EXPORTER_OTLP_METRIC_TIMEOUT: "10", }, ) @patch("opentelemetry.exporter.otlp.exporter.OTLPExporterMixin.__init__") def test_env_variables(self, mock_exporter_mixin): OTLPMetricsExporter() self.assertTrue(len(mock_exporter_mixin.call_args_list) == 1) _, kwargs = mock_exporter_mixin.call_args_list[0] self.assertEqual(kwargs["endpoint"], "collector:4317") self.assertEqual(kwargs["headers"], "key1=value1,key2=value2") self.assertEqual(kwargs["timeout"], 10) self.assertIsNotNone(kwargs["credentials"]) self.assertIsInstance(kwargs["credentials"], ChannelCredentials) @patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials") @patch("opentelemetry.exporter.otlp.exporter.secure_channel") @patch( "opentelemetry.exporter.otlp.metrics_exporter.OTLPMetricsExporter._stub" ) # pylint: disable=unused-argument def test_no_credentials_error(self, mock_ssl_channel, mock_secure, mock_stub): OTLPMetricsExporter(insecure=False) self.assertTrue(mock_ssl_channel.called) @patch.dict( "os.environ", {OTEL_EXPORTER_OTLP_METRIC_HEADERS: "key1=value1,key2=value2"}, ) @patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials") @patch("opentelemetry.exporter.otlp.exporter.secure_channel") # pylint: disable=unused-argument 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 = OTLPMetricsExporter(headers=(("key3", "value3"), ("key4", "value4"))) # pylint: disable=protected-access self.assertEqual( exporter._headers, (("key3", "value3"), ("key4", "value4")), ) @patch("opentelemetry.exporter.otlp.exporter.ssl_channel_credentials") @patch("opentelemetry.exporter.otlp.exporter.secure_channel") # pylint: disable=unused-argument def test_otlp_headers(self, mock_ssl_channel, mock_secure): exporter = OTLPMetricsExporter() # pylint: disable=protected-access self.assertIsNone(exporter._headers, None) @patch("opentelemetry.sdk.metrics.export.aggregate.time_ns") 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", ), ), [("g", "h")], SumAggregator(), self.resource, ) counter_export_record.aggregator.checkpoint = 1 counter_export_record.aggregator.initial_checkpoint_timestamp = 1 counter_export_record.aggregator.last_update_timestamp = 1 expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( name="name", version="version", ), metrics=[ OTLPMetric( name="c", description="d", unit="e", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="g", value="h") ], value=1, time_unix_nano=1, start_time_unix_nano=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_CUMULATIVE), is_monotonic=True, ), ) ], ) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([counter_export_record]) self.assertEqual(expected, actual) @patch("opentelemetry.sdk.metrics.export.aggregate.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", ), ), [("g", "h")], SumAggregator(), self.resource, ) counter_export_record.aggregator.checkpoint = 1 counter_export_record.aggregator.initial_checkpoint_timestamp = 1 counter_export_record.aggregator.last_update_timestamp = 1 expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( name="name", version="version", ), metrics=[ OTLPMetric( name="c", description="d", unit="e", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="g", value="h") ], value=1, time_unix_nano=1, start_time_unix_nano=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_CUMULATIVE), is_monotonic=True, ), ) ], ) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([counter_export_record]) self.assertEqual(expected, actual) @patch("opentelemetry.sdk.metrics.export.aggregate.time_ns") def test_translate_updowncounter_export_record(self, mock_time_ns): mock_time_ns.configure_mock(**{"return_value": 1}) counter_export_record = ExportRecord( UpDownCounter("c", "d", "e", int, self.meter), [("g", "h")], SumAggregator(), self.resource, ) counter_export_record.aggregator.checkpoint = 1 counter_export_record.aggregator.initial_checkpoint_timestamp = 1 counter_export_record.aggregator.last_update_timestamp = 1 expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( name="name", version="version", ), metrics=[ OTLPMetric( name="c", description="d", unit="e", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="g", value="h") ], value=1, time_unix_nano=1, start_time_unix_nano=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_CUMULATIVE), ), ) ], ) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([counter_export_record]) self.assertEqual(expected, actual) @patch("opentelemetry.sdk.metrics.export.aggregate.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", ), ), [("g", "h")], SumAggregator(), self.resource, ) counter_export_record.aggregator.checkpoint = 1 counter_export_record.aggregator.initial_checkpoint_timestamp = 1 counter_export_record.aggregator.last_update_timestamp = 1 expected = ExportMetricsServiceRequest(resource_metrics=[ ResourceMetrics( resource=OTLPResource(attributes=[ KeyValue(key="a", value=AnyValue(int_value=1)), KeyValue(key="b", value=AnyValue(bool_value=False)), ]), instrumentation_library_metrics=[ InstrumentationLibraryMetrics( instrumentation_library=InstrumentationLibrary( name="name", version="version", ), metrics=[ OTLPMetric( name="c", description="d", unit="e", int_sum=IntSum( data_points=[ IntDataPoint( labels=[ StringKeyValue(key="g", value="h") ], value=1, time_unix_nano=1, start_time_unix_nano=1, ) ], aggregation_temporality=( AggregationTemporality. AGGREGATION_TEMPORALITY_CUMULATIVE), ), ) ], ) ], ) ]) # pylint: disable=protected-access actual = self.exporter._translate_data([counter_export_record]) self.assertEqual(expected, actual)
def test_otlp_headers(self, mock_ssl_channel, mock_secure): exporter = OTLPMetricsExporter() # pylint: disable=protected-access self.assertIsNone(exporter._headers, None)