Skip to content

Commit 936dc37

Browse files
committed
include feedback
1 parent a8d5e16 commit 936dc37

File tree

7 files changed

+64
-75
lines changed

7 files changed

+64
-75
lines changed

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/__init__.py

+47-50
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def func():
9797
from opentelemetry.trace import get_tracer
9898
from opentelemetry.trace.status import Status, StatusCode
9999

100-
ASYNCIO_PREFIX = "asyncio."
100+
ASYNCIO_PREFIX = "asyncio"
101101

102102

103103
class AsyncioInstrumentor(BaseInstrumentor):
@@ -118,8 +118,8 @@ class AsyncioInstrumentor(BaseInstrumentor):
118118

119119
def __init__(self):
120120
super().__init__()
121-
self.process_duration_metric = None
122-
self.process_counts_metric = None
121+
self.process_duration_histogram = None
122+
self.process_counts_counter = None
123123

124124
self._tracer = None
125125
self._meter = None
@@ -131,8 +131,9 @@ def instrumentation_dependencies(self) -> Collection[str]:
131131
return _instruments
132132

133133
def _instrument(self, **kwargs):
134-
tracer_provider = kwargs.get("tracer_provider")
135-
self._tracer = get_tracer(__name__, __version__, tracer_provider)
134+
self._tracer = get_tracer(
135+
__name__, __version__, kwargs.get("tracer_provider")
136+
)
136137
self._meter = get_meter(
137138
__name__, __version__, kwargs.get("meter_provider")
138139
)
@@ -141,12 +142,12 @@ def _instrument(self, **kwargs):
141142
self._future_active_enabled = get_future_trace_enabled()
142143
self._to_thread_name_to_trace = get_to_thread_to_trace()
143144

144-
self.process_duration_metric = self._meter.create_histogram(
145+
self.process_duration_histogram = self._meter.create_histogram(
145146
name="asyncio.process.duration",
146147
description="Duration of asyncio process",
147148
unit="seconds",
148149
)
149-
self.process_counts_metric = self._meter.create_up_down_counter(
150+
self.process_counts_counter = self._meter.create_counter(
150151
name="asyncio.process.count",
151152
description="Number of asyncio process",
152153
unit="1",
@@ -166,7 +167,7 @@ def _uninstrument(self, **kwargs):
166167
uninstrument_to_thread()
167168
uninstrument_taskgroup_create_task()
168169

169-
def instrument_method_with_coroutine(self, method_name):
170+
def instrument_method_with_coroutine(self, method_name: str):
170171
"""
171172
Instruments specified asyncio method.
172173
"""
@@ -201,12 +202,12 @@ def wrap_coros_or_futures(method, instance, args, kwargs):
201202

202203
_wrap(asyncio, "gather", wrap_coros_or_futures)
203204

204-
def instrument_to_thread(self):
205+
def instrument_to_thread(self) -> None:
205206
# to_thread was added in Python 3.9
206207
if sys.version_info < (3, 9):
207208
return
208209

209-
def wrap_to_thread(method, instance, args, kwargs):
210+
def wrap_to_thread(method, instance, args, kwargs) -> None:
210211
if args:
211212
first_arg = args[0]
212213
# Wrap the first argument
@@ -218,12 +219,12 @@ def wrap_to_thread(method, instance, args, kwargs):
218219

219220
_wrap(asyncio, "to_thread", wrap_to_thread)
220221

221-
def instrument_taskgroup_create_task(self):
222+
def instrument_taskgroup_create_task(self) -> None:
222223
# TaskGroup.create_task was added in Python 3.11
223224
if sys.version_info < (3, 11):
224225
return
225226

226-
def wrap_taskgroup_create_task(method, instance, args, kwargs):
227+
def wrap_taskgroup_create_task(method, instance, args, kwargs) -> None:
227228
if args:
228229
coro = args[0]
229230
wrapped_coro = self.trace_coroutine(coro)
@@ -237,18 +238,17 @@ def wrap_taskgroup_create_task(method, instance, args, kwargs):
237238
wrap_taskgroup_create_task,
238239
)
239240

240-
def trace_to_thread(self, func):
241+
def trace_to_thread(self, func: callable):
241242
"""Trace a function."""
242243
start = default_timer()
243244
span = (
244245
self._tracer.start_span(
245-
f"{ASYNCIO_PREFIX}to_thread_func-" + func.__name__
246+
f"{ASYNCIO_PREFIX} to_thread-" + func.__name__
246247
)
247248
if func.__name__ in self._to_thread_name_to_trace
248249
else None
249250
)
250251
attr = {"type": "to_thread", "name": func.__name__}
251-
duration_attr = attr.copy()
252252
exception = None
253253
try:
254254
attr["state"] = "finished"
@@ -257,14 +257,7 @@ def trace_to_thread(self, func):
257257
attr["state"] = "exception"
258258
raise
259259
finally:
260-
duration = max(round((default_timer() - start) * 1000), 0)
261-
self.process_duration_metric.record(duration, duration_attr)
262-
self.process_counts_metric.add(1, attr)
263-
if span:
264-
if span.is_recording() and exception:
265-
span.set_status(Status(StatusCode.ERROR))
266-
span.record_exception(exception)
267-
span.end()
260+
self.record_process(start, attr, span, exception)
268261

269262
def trace_item(self, coro_or_future):
270263
"""Trace a coroutine or future item."""
@@ -283,9 +276,8 @@ async def trace_coroutine(self, coro):
283276
"type": "coroutine",
284277
"name": coro.__name__,
285278
}
286-
duration_attr = attr.copy()
287279
span = (
288-
self._tracer.start_span(f"{ASYNCIO_PREFIX}coro-" + coro.__name__)
280+
self._tracer.start_span(f"{ASYNCIO_PREFIX} coro-" + coro.__name__)
289281
if coro.__name__ in self._coros_name_to_trace
290282
else None
291283
)
@@ -304,46 +296,51 @@ async def trace_coroutine(self, coro):
304296
attr["state"] = state
305297
raise
306298
finally:
307-
duration = max(round(default_timer() - start), 0)
308-
self.process_duration_metric.record(duration, duration_attr)
309-
self.process_counts_metric.add(1, attr)
310-
311-
if span:
312-
if span.is_recording() and exception:
313-
span.set_status(Status(StatusCode.ERROR))
314-
span.record_exception(exception)
315-
span.end()
299+
self.record_process(start, attr, span, exception)
316300

317-
def trace_future(self, future):
301+
def trace_future(self, future) -> futures.Future:
318302
start = default_timer()
319303
span = (
320-
self._tracer.start_span(f"{ASYNCIO_PREFIX}future")
304+
self._tracer.start_span(f"{ASYNCIO_PREFIX} future")
321305
if self._future_active_enabled
322306
else None
323307
)
324308

325309
def callback(f):
326-
duration = max(round(default_timer() - start), 0)
327310
exception = f.exception()
328311
attr = {
329312
"type": "future",
330313
}
331-
duration_attr = attr.copy()
332314
state = determine_state(exception)
333315
attr["state"] = state
334-
self.process_counts_metric.add(1, attr)
335-
self.process_duration_metric.record(duration, duration_attr)
336-
if span:
337-
if span.is_recording() and exception:
338-
span.set_status(Status(StatusCode.ERROR))
339-
span.record_exception(exception)
340-
span.end()
316+
self.record_process(start, attr, span, exception)
341317

342318
future.add_done_callback(callback)
343319
return future
344320

321+
def record_process(
322+
self, start: float, attr: dict, span=None, exception=None
323+
) -> None:
324+
"""
325+
Record the processing time, update histogram and counter, and handle span.
326+
327+
:param start: Start time of the process.
328+
:param attr: Attributes for the histogram and counter.
329+
:param span: Optional span for tracing.
330+
:param exception: Optional exception occurred during the process.
331+
"""
332+
duration = max(default_timer() - start, 0)
333+
self.process_duration_histogram.record(duration, attr)
334+
self.process_counts_counter.add(1, attr)
335+
336+
if span:
337+
if span.is_recording() and exception:
338+
span.set_status(Status(StatusCode.ERROR))
339+
span.record_exception(exception)
340+
span.end()
341+
345342

346-
def determine_state(exception):
343+
def determine_state(exception: Exception) -> str:
347344
if isinstance(exception, asyncio.CancelledError):
348345
return "cancelled"
349346
if isinstance(exception, asyncio.TimeoutError):
@@ -353,25 +350,25 @@ def determine_state(exception):
353350
return "finished"
354351

355352

356-
def uninstrument_taskgroup_create_task():
353+
def uninstrument_taskgroup_create_task() -> None:
357354
# TaskGroup.create_task was added in Python 3.11
358355
if sys.version_info < (3, 11):
359356
return
360357
unwrap(asyncio.TaskGroup, "create_task") # pylint: disable=no-member
361358

362359

363-
def uninstrument_to_thread():
360+
def uninstrument_to_thread() -> None:
364361
# to_thread was added in Python 3.9
365362
if sys.version_info < (3, 9):
366363
return
367364
unwrap(asyncio, "to_thread")
368365

369366

370-
def uninstrument_gather():
367+
def uninstrument_gather() -> None:
371368
unwrap(asyncio, "gather")
372369

373370

374-
def uninstrument_method_with_coroutine(method_name):
371+
def uninstrument_method_with_coroutine(method_name: str) -> None:
375372
"""
376373
Uninstrument specified asyncio method.
377374
"""

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
)
2222

2323

24-
def separate_coro_names_by_comma(coro_names) -> set:
24+
def separate_coro_names_by_comma(coro_names: str) -> set:
2525
"""
2626
Function to separate the coroutines to be traced by comma
2727
"""

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/tests/common_test_func.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ async def async_func():
1919
await asyncio.sleep(0.1)
2020

2121

22-
async def factorial(number):
22+
async def factorial(number: int):
2323
factorial_value = 1
2424
for value in range(2, number + 1):
2525
await asyncio.sleep(0)

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_cancellation.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ def test_cancel(self):
5151
self.assertEqual(spans[0].context.trace_id, spans[1].context.trace_id)
5252
self.assertEqual(spans[2].context.trace_id, spans[1].context.trace_id)
5353

54-
self.assertEqual(spans[0].name, "asyncio.coro-cancellable_coroutine")
55-
self.assertEqual(spans[1].name, "asyncio.coro-cancellation_coro")
54+
self.assertEqual(spans[0].name, "asyncio coro-cancellable_coroutine")
55+
self.assertEqual(spans[1].name, "asyncio coro-cancellation_coro")
5656
for metric in (
5757
self.memory_metrics_reader.get_metrics_data()
5858
.resource_metrics[0]

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_create_task.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,4 @@ async def async_func():
4949
spans = self.memory_exporter.get_finished_spans()
5050

5151
self.assertEqual(len(spans), 1)
52-
self.assertEqual(spans[0].name, "asyncio.coro-sleep")
52+
self.assertEqual(spans[0].name, "asyncio coro-sleep")

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_gather.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,6 @@ async def gather_factorial():
4848
asyncio.run(gather_factorial())
4949
spans = self.memory_exporter.get_finished_spans()
5050
self.assertEqual(len(spans), 3)
51-
self.assertEqual(spans[0].name, "asyncio.coro-factorial")
52-
self.assertEqual(spans[1].name, "asyncio.coro-factorial")
53-
self.assertEqual(spans[2].name, "asyncio.coro-factorial")
51+
self.assertEqual(spans[0].name, "asyncio coro-factorial")
52+
self.assertEqual(spans[1].name, "asyncio coro-factorial")
53+
self.assertEqual(spans[2].name, "asyncio coro-factorial")

Diff for: instrumentation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_to_thread.py

+9-17
Original file line numberDiff line numberDiff line change
@@ -56,26 +56,18 @@ async def to_thread():
5656
spans = self.memory_exporter.get_finished_spans()
5757

5858
self.assertEqual(len(spans), 2)
59-
assert spans[0].name == "asyncio.to_thread_func-multiply"
59+
assert spans[0].name == "asyncio to_thread-multiply"
6060
for metric in (
6161
self.memory_metrics_reader.get_metrics_data()
6262
.resource_metrics[0]
6363
.scope_metrics[0]
6464
.metrics
6565
):
66-
if metric.name == "asyncio.to_thread.duration":
67-
self.assertEqual(metric.data.data_points[0].count, 1)
68-
elif metric.name == "asyncio.to_thread.active":
69-
self.assertEqual(metric.data.data_points[0].value, 0)
70-
elif metric.name == "asyncio.to_thread.created":
71-
self.assertEqual(metric.data.data_points[0].value, 1)
72-
elif metric.name == "asyncio.to_thread.finished":
73-
self.assertEqual(metric.data.data_points[0].value, 1)
74-
elif metric.name == "asyncio.to_thread.exceptions":
75-
self.assertEqual(metric.data.data_points[0].value, 0)
76-
elif metric.name == "asyncio.to_thread.cancelled":
77-
self.assertEqual(metric.data.data_points[0].value, 0)
78-
elif metric.name == "asyncio.to_thread.name":
79-
self.assertEqual(
80-
metric.data.data_points[0].value, "multiply"
81-
)
66+
if metric.name == "asyncio.process.duration":
67+
for point in metric.data.data_points:
68+
self.assertEqual(point.attributes["type"], "to_thread")
69+
self.assertEqual(point.attributes["name"], "multiply")
70+
if metric.name == "asyncio.process.count":
71+
for point in metric.data.data_points:
72+
self.assertEqual(point.attributes["type"], "to_thread")
73+
self.assertEqual(point.attributes["name"], "multiply")

0 commit comments

Comments
 (0)