-
Notifications
You must be signed in to change notification settings - Fork 4
Implement tracing decorator #218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c99fbad
Rename bootstrap package in common
febus982 55b9ce4
Create helper class decorator
febus982 695a961
Implement tracing decorator and add it to example service
febus982 0fadae5
Lint and typing
febus982 2d4d670
Attempt to reduce cognitive complexity
febus982 d3ae2c7
Attempt 2 to reduce cognitive complexity
febus982 5522bc3
Merge branch 'main' into tracing-decorator
febus982 b995b09
Revert "Attempt 2 to reduce cognitive complexity"
febus982 49732be
Revert "Attempt to reduce cognitive complexity"
febus982 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import asyncio | ||
from functools import wraps | ||
|
||
from opentelemetry import trace | ||
|
||
# Get the _tracer instance (You can set your own _tracer name) | ||
tracer = trace.get_tracer(__name__) | ||
|
||
|
||
def trace_function(trace_attributes: bool = True, trace_result: bool = True): | ||
febus982 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Decorator to trace callables using OpenTelemetry spans. | ||
|
||
Parameters: | ||
- trace_attributes (bool): If False, disables adding function arguments to the span. | ||
- trace_result (bool): If False, disables adding the function's result to the span. | ||
""" | ||
|
||
def decorator(func): | ||
@wraps(func) | ||
def sync_or_async_wrapper(*args, **kwargs): | ||
with tracer.start_as_current_span(func.__name__) as span: | ||
try: | ||
# Set function arguments as attributes | ||
if trace_attributes: | ||
span.set_attribute("function.args", str(args)) | ||
span.set_attribute("function.kwargs", str(kwargs)) | ||
|
||
async def async_handler(): | ||
result = await func(*args, **kwargs) | ||
# Add result to span | ||
if trace_result: | ||
span.set_attribute("function.result", str(result)) | ||
return result | ||
|
||
def sync_handler(): | ||
result = func(*args, **kwargs) | ||
# Add result to span | ||
if trace_result: | ||
span.set_attribute("function.result", str(result)) | ||
return result | ||
|
||
if asyncio.iscoroutinefunction(func): | ||
return async_handler() | ||
else: | ||
return sync_handler() | ||
|
||
except Exception as e: | ||
# Record the exception in the span | ||
span.record_exception(e) | ||
span.set_status(trace.status.Status(trace.status.StatusCode.ERROR)) | ||
raise | ||
|
||
return sync_or_async_wrapper | ||
|
||
return decorator |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
def apply_decorator_to_methods( | ||
febus982 marked this conversation as resolved.
Show resolved
Hide resolved
febus982 marked this conversation as resolved.
Show resolved
Hide resolved
febus982 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
decorator, protected_methods: bool = False, private_methods: bool = False | ||
): | ||
""" | ||
Class decorator to apply a given function or coroutine decorator | ||
to all functions and coroutines within a class. | ||
""" | ||
|
||
def class_decorator(cls): | ||
for attr_name, attr_value in cls.__dict__.items(): | ||
# Check if the attribute is a callable (method or coroutine) | ||
if not callable(attr_value): | ||
continue | ||
|
||
if attr_name.startswith(f"_{cls.__name__}__"): | ||
if not private_methods: | ||
continue | ||
|
||
elif attr_name.startswith("_") and not protected_methods: | ||
continue | ||
|
||
# Replace the original callable with the decorated version | ||
setattr(cls, attr_name, decorator(attr_value)) | ||
return cls | ||
|
||
return class_decorator |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
import asyncio | ||
from unittest.mock import MagicMock, call, patch | ||
|
||
import pytest | ||
|
||
from common.tracing import trace_function | ||
|
||
|
||
@pytest.fixture | ||
def mock_tracer(): | ||
""" | ||
Fixture to mock the OpenTelemetry tracer and span. | ||
""" | ||
mock_tracer = MagicMock() | ||
mock_span = MagicMock() | ||
mock_tracer.start_as_current_span.return_value.__enter__.return_value = mock_span | ||
|
||
with ( | ||
patch("opentelemetry.trace.get_tracer", return_value=mock_tracer), | ||
patch("common.tracing.tracer", mock_tracer), | ||
): | ||
yield mock_tracer, mock_span | ||
|
||
|
||
def test_sync_function_default_params(mock_tracer): | ||
""" | ||
Test a synchronous function with default decorator parameters. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define a sync function to wrap with the decorator | ||
@trace_function() | ||
def add_nums(a, b): | ||
return a + b | ||
|
||
# Call the function | ||
result = add_nums(2, 3) | ||
|
||
# Assertions | ||
assert result == 5 | ||
mock_tracer.start_as_current_span.assert_called_once_with("add_nums") | ||
mock_span.set_attribute.assert_any_call("function.args", "(2, 3)") | ||
mock_span.set_attribute.assert_any_call("function.result", "5") | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_async_function_default_params(mock_tracer): | ||
""" | ||
Test an asynchronous function with default decorator parameters. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define an async function to wrap with the decorator | ||
@trace_function() | ||
async def async_func(a, b): | ||
await asyncio.sleep(0.1) | ||
return a * b | ||
|
||
# Run the async function | ||
result = await async_func(4, 5) | ||
|
||
# Assertions | ||
assert result == 20 | ||
mock_tracer.start_as_current_span.assert_called_once_with("async_func") | ||
mock_span.set_attribute.assert_any_call("function.args", "(4, 5)") | ||
mock_span.set_attribute.assert_any_call("function.result", "20") | ||
|
||
|
||
def test_disable_function_attributes(mock_tracer): | ||
""" | ||
Test a synchronous function with `add_function_attributes` set to False. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define a sync function with attributes disabled | ||
@trace_function(trace_attributes=False) | ||
def sync_func(a, b): | ||
return a - b | ||
|
||
# Call the function | ||
result = sync_func(10, 6) | ||
|
||
# Assertions | ||
assert result == 4 | ||
mock_tracer.start_as_current_span.assert_called_once_with("sync_func") | ||
mock_span.set_attribute.assert_any_call("function.result", "4") | ||
assert ( | ||
call("function.args", "(10, 6)") not in mock_span.set_attribute.call_args_list | ||
) | ||
|
||
|
||
def test_disable_result_in_span_sync(mock_tracer): | ||
""" | ||
Test an asynchronous function with `add_result_to_span` set to False. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define an async function with result disabled | ||
@trace_function(trace_result=False) | ||
def sync_func(a, b): | ||
return a / b | ||
|
||
# Run the async function | ||
result = sync_func(10, 2) | ||
|
||
# Assertions | ||
assert result == 5.0 | ||
mock_tracer.start_as_current_span.assert_called_once_with("sync_func") | ||
mock_span.set_attribute.assert_any_call("function.args", "(10, 2)") | ||
assert call("function.result") not in mock_span.set_attribute.call_args_list | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_disable_result_in_span(mock_tracer): | ||
""" | ||
Test an asynchronous function with `add_result_to_span` set to False. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define an async function with result disabled | ||
@trace_function(trace_result=False) | ||
async def async_func(a, b): | ||
await asyncio.sleep(0.1) | ||
return a / b | ||
|
||
# Run the async function | ||
result = await async_func(10, 2) | ||
|
||
# Assertions | ||
assert result == 5.0 | ||
mock_tracer.start_as_current_span.assert_called_once_with("async_func") | ||
mock_span.set_attribute.assert_any_call("function.args", "(10, 2)") | ||
assert call("function.result") not in mock_span.set_attribute.call_args_list | ||
|
||
|
||
def test_exception_in_function(mock_tracer): | ||
""" | ||
Test behavior when the function raises an exception. | ||
""" | ||
mock_tracer, mock_span = mock_tracer | ||
|
||
# Define a failing function | ||
@trace_function() | ||
def failing_func(a, b): | ||
if b == 0: | ||
raise ValueError("Division by zero!") | ||
return a / b | ||
|
||
# Use pytest to assert the exception is raised | ||
with pytest.raises(ValueError, match="Division by zero!"): | ||
failing_func(10, 0) | ||
|
||
# Assertions | ||
mock_tracer.start_as_current_span.assert_called_once_with("failing_func") | ||
mock_span.record_exception.assert_called_once() | ||
mock_span.set_status.assert_called_once() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.