Skip to content

Commit 7d35dd6

Browse files
committed
Fix Tracing decorator
Signed-off-by: Federico Busetti <[email protected]>
1 parent cea0506 commit 7d35dd6

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

src/common/tracing.py

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,39 +18,46 @@ def trace_function(trace_attributes: bool = True, trace_result: bool = True):
1818

1919
def decorator(func):
2020
@wraps(func)
21-
def sync_or_async_wrapper(*args, **kwargs):
21+
async def async_wrapper(*args, **kwargs):
2222
with tracer.start_as_current_span(func.__name__) as span:
2323
try:
2424
# Set function arguments as attributes
2525
if trace_attributes:
2626
span.set_attribute("function.args", str(args))
2727
span.set_attribute("function.kwargs", str(kwargs))
2828

29-
async def async_handler():
30-
result = await func(*args, **kwargs)
31-
# Add result to span
32-
if trace_result:
33-
span.set_attribute("function.result", str(result))
34-
return result
35-
36-
def sync_handler():
37-
result = func(*args, **kwargs)
38-
# Add result to span
39-
if trace_result:
40-
span.set_attribute("function.result", str(result))
41-
return result
42-
43-
if asyncio.iscoroutinefunction(func):
44-
return async_handler()
45-
else:
46-
return sync_handler()
29+
result = await func(*args, **kwargs)
30+
# Add result to span
31+
if trace_result:
32+
span.set_attribute("function.result", str(result))
33+
return result
34+
except Exception as e:
35+
# Record the exception in the span
36+
span.record_exception(e)
37+
span.set_status(trace.status.Status(trace.status.StatusCode.ERROR))
38+
raise
39+
40+
@wraps(func)
41+
def sync_wrapper(*args, **kwargs):
42+
with tracer.start_as_current_span(func.__name__) as span:
43+
try:
44+
# Set function arguments as attributes
45+
if trace_attributes:
46+
span.set_attribute("function.args", str(args))
47+
span.set_attribute("function.kwargs", str(kwargs))
48+
49+
result = func(*args, **kwargs)
50+
# Add result to span
51+
if trace_result:
52+
span.set_attribute("function.result", str(result))
53+
return result
4754

4855
except Exception as e:
4956
# Record the exception in the span
5057
span.record_exception(e)
5158
span.set_status(trace.status.Status(trace.status.StatusCode.ERROR))
5259
raise
5360

54-
return sync_or_async_wrapper
61+
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
5562

5663
return decorator

0 commit comments

Comments
 (0)