Skip to content

Commit ac56d0e

Browse files
authored
sdk: Adding suppress_instrumentation in Metrics (#529)
Suppressing instrumentation in metrics to ensure no infinite loops of emitting telemetry.
1 parent 8894805 commit ac56d0e

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

Diff for: opentelemetry-sdk/src/opentelemetry/sdk/metrics/export/controller.py

+4
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
import atexit
1616
import threading
1717

18+
from opentelemetry.context import attach, detach, set_value
19+
1820

1921
class PushController(threading.Thread):
2022
"""A push based controller, used for exporting.
@@ -50,7 +52,9 @@ def shutdown(self):
5052
def tick(self):
5153
# Collect all of the meter's metrics to be exported
5254
self.meter.collect()
55+
token = attach(set_value("suppress_instrumentation", True))
5356
# Export the given metrics in the batcher
5457
self.exporter.export(self.meter.batcher.checkpoint_set())
58+
detach(token)
5559
# Perform post-exporting logic based on batcher configuration
5660
self.meter.batcher.finished_collection()

Diff for: opentelemetry-sdk/tests/metrics/export/test_export.py

+16
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import unittest
1818
from unittest import mock
1919

20+
from opentelemetry.context import get_value
2021
from opentelemetry.sdk import metrics
2122
from opentelemetry.sdk.metrics.export import (
2223
ConsoleMetricsExporter,
@@ -511,3 +512,18 @@ def test_push_controller(self):
511512
controller.shutdown()
512513
self.assertTrue(controller.finished.isSet())
513514
exporter.shutdown.assert_any_call()
515+
516+
def test_push_controller_suppress_instrumentation(self):
517+
meter = mock.Mock()
518+
exporter = mock.Mock()
519+
exporter.export = lambda x: self.assertIsNotNone(
520+
get_value("suppress_instrumentation")
521+
)
522+
with mock.patch(
523+
"opentelemetry.context._RUNTIME_CONTEXT"
524+
) as context_patch:
525+
controller = PushController(meter, exporter, 30.0)
526+
controller.tick()
527+
self.assertEqual(context_patch.attach.called, True)
528+
self.assertEqual(context_patch.detach.called, True)
529+
self.assertEqual(get_value("suppress_instrumentation"), None)

0 commit comments

Comments
 (0)