awslabs / awslabs/aws-embedded-metrics-python
RFC: Thread-local metrics object
- Dominant language
- Python
- Stars
- 231
- Forks
- 44
- PR merge metrics
- No merged PRs in 30d
Description
**Purpose**
It would be nice to create the metric context and logger at the beginning of the function execution and use that instance in multiple classes/methods without having to pass it as a parameter throughout.
**Proposal Summary**
Add an interface for accessing a thread-local metric logger.
**Option A**
Introduce a decorator that will provide access to the thread-local instance. The first time it gets called, it will initialize itself and close upon completion of the top-level method.
```py
from aws_embedded_metrics import metric_scope
@metric_scope(local_scope=True)
def my_function(..):
my_method()
# metrics get closed when my_function exits
@metric_scope(local_scope=True)
def my_method(metrics):
metrics.put_metric("Name", value)
```
**Option B**
Introduce a static accessor with decorator that initializes and closes the scope.
```py
from aws_embedded_metrics import local_metric_scope, local_metrics
@local_metric_scope
def my_function(..):
my_method()
# metrics get closed when my_function exits
def my_method():
local_metrics.put_metric("Name", value)
```
**Option C**
Explicit initialization of local metrics
```py
from aws_embedded_metrics import local_metrics
def my_function(..):
with local_metrics.init() as metrics:
my_method()
# metrics get closed when with statement completes
def my_method():
local_metrics.put_metric("Name", value)
```
**Considerations**
- Metrics still need to be explicitly initialized and closed.
- Need to provide advice on unit testing code that consumes the thread-local metrics object.
- Currently, the flush for TCP is not async. If we make this async we can't rely on thread local and may need to use something like [contextvars](https://docs.python.org/3/library/contextvars.html#module-contextvars)
Contributor guide
Assessment
This issue has not been assessed yet.