Skip to content

Commit

Permalink
Handle duplicate meters (#2373)
Browse files Browse the repository at this point in the history
  • Loading branch information
lzchen authored Jan 15, 2022
1 parent 8ff97ea commit fb1063c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
14 changes: 10 additions & 4 deletions opentelemetry-sdk/src/opentelemetry/sdk/_metrics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,15 @@ def __init__(
shutdown_on_exit: bool = True,
):
self._lock = Lock()
self._meter_lock = Lock()
self._atexit_handler = None

self._measurement_consumer = SynchronousMeasurementConsumer()

if shutdown_on_exit:
self._atexit_handler = register(self.shutdown)

self._meters = {}
self._metric_readers = metric_readers

for metric_reader in self._metric_readers:
Expand Down Expand Up @@ -221,7 +223,11 @@ def get_meter(
)
return _DefaultMeter(name, version=version, schema_url=schema_url)

return Meter(
InstrumentationInfo(name, version, schema_url),
self._measurement_consumer,
)
info = InstrumentationInfo(name, version, schema_url)
with self._meter_lock:
if not self._meters.get(info):
self._meters[info] = Meter(
info,
self._measurement_consumer,
)
return self._meters[info]
24 changes: 24 additions & 0 deletions opentelemetry-sdk/tests/metrics/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,30 @@ def test_get_meter(self):
self.assertEqual(meter._instrumentation_info.version, "version")
self.assertEqual(meter._instrumentation_info.schema_url, "schema_url")

def test_get_meter_duplicate(self):
"""
Subsequent calls to `MeterProvider.get_meter` with the same arguments
should return the same `Meter` instance.
"""
mp = MeterProvider()
meter1 = mp.get_meter(
"name",
version="version",
schema_url="schema_url",
)
meter2 = mp.get_meter(
"name",
version="version",
schema_url="schema_url",
)
meter3 = mp.get_meter(
"name2",
version="version",
schema_url="schema_url",
)
self.assertIs(meter1, meter2)
self.assertIsNot(meter1, meter3)

def test_shutdown_subsequent_calls(self):
"""
No subsequent attempts to get a `Meter` are allowed after calling
Expand Down

0 comments on commit fb1063c

Please sign in to comment.