Skip to content

RFC: Thread-local metrics object #8

Open
@jaredcnance

Description

@jaredcnance

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.

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.

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions