Skip to content

Commit

Permalink
sdk: Adding suppress_instrumentation in Metrics (#529)
Browse files Browse the repository at this point in the history
Suppressing instrumentation in metrics to ensure no infinite loops of emitting telemetry.
  • Loading branch information
hectorhdzg authored Apr 1, 2020
1 parent 8894805 commit ac56d0e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import atexit
import threading

from opentelemetry.context import attach, detach, set_value


class PushController(threading.Thread):
"""A push based controller, used for exporting.
Expand Down Expand Up @@ -50,7 +52,9 @@ def shutdown(self):
def tick(self):
# Collect all of the meter's metrics to be exported
self.meter.collect()
token = attach(set_value("suppress_instrumentation", True))
# Export the given metrics in the batcher
self.exporter.export(self.meter.batcher.checkpoint_set())
detach(token)
# Perform post-exporting logic based on batcher configuration
self.meter.batcher.finished_collection()
16 changes: 16 additions & 0 deletions opentelemetry-sdk/tests/metrics/export/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import unittest
from unittest import mock

from opentelemetry.context import get_value
from opentelemetry.sdk import metrics
from opentelemetry.sdk.metrics.export import (
ConsoleMetricsExporter,
Expand Down Expand Up @@ -511,3 +512,18 @@ def test_push_controller(self):
controller.shutdown()
self.assertTrue(controller.finished.isSet())
exporter.shutdown.assert_any_call()

def test_push_controller_suppress_instrumentation(self):
meter = mock.Mock()
exporter = mock.Mock()
exporter.export = lambda x: self.assertIsNotNone(
get_value("suppress_instrumentation")
)
with mock.patch(
"opentelemetry.context._RUNTIME_CONTEXT"
) as context_patch:
controller = PushController(meter, exporter, 30.0)
controller.tick()
self.assertEqual(context_patch.attach.called, True)
self.assertEqual(context_patch.detach.called, True)
self.assertEqual(get_value("suppress_instrumentation"), None)

0 comments on commit ac56d0e

Please sign in to comment.