|
| 1 | +import functools |
| 2 | +import logging |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from typing import Any, Callable, Dict, Optional, Union |
| 5 | + |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +class MetricsProviderBase(ABC): |
| 10 | + """Class for metric provider template |
| 11 | +
|
| 12 | + Use this template to create your own metric provider. |
| 13 | +
|
| 14 | + """ |
| 15 | + |
| 16 | + # General add metric function. Should return combined metrics Dict |
| 17 | + @abstractmethod |
| 18 | + def add_metric(self, *args, **kwargs): |
| 19 | + pass |
| 20 | + |
| 21 | + # serialize and return dict for flushing |
| 22 | + @abstractmethod |
| 23 | + def serialize(self, *args, **kwargs): |
| 24 | + pass |
| 25 | + |
| 26 | + # flush serialized data to output, or send to API directly |
| 27 | + @abstractmethod |
| 28 | + def flush(self, *args, **kwargs): |
| 29 | + pass |
| 30 | + |
| 31 | + |
| 32 | +class MetricsBase(ABC): |
| 33 | + """Class for metric template |
| 34 | +
|
| 35 | + Use this template to create your own metric class. |
| 36 | +
|
| 37 | + """ |
| 38 | + |
| 39 | + @abstractmethod |
| 40 | + def add_metric(self, *args, **kwargs): |
| 41 | + pass |
| 42 | + |
| 43 | + @abstractmethod |
| 44 | + def flush_metrics(self, raise_on_empty_metrics: bool = False) -> None: |
| 45 | + pass |
| 46 | + |
| 47 | + def log_metrics( |
| 48 | + self, |
| 49 | + lambda_handler: Union[Callable[[Dict, Any], Any], Optional[Callable[[Dict, Any, Optional[Dict]], Any]]] = None, |
| 50 | + capture_cold_start_metric: bool = False, |
| 51 | + raise_on_empty_metrics: bool = False, |
| 52 | + ): |
| 53 | + """Decorator to serialize and publish metrics at the end of a function execution. |
| 54 | +
|
| 55 | + Be aware that the log_metrics **does call* the decorated function (e.g. lambda_handler). |
| 56 | +
|
| 57 | + Example |
| 58 | + ------- |
| 59 | + **Lambda function using tracer and metrics decorators** |
| 60 | +
|
| 61 | + from aws_lambda_powertools import Metrics, Tracer |
| 62 | +
|
| 63 | + metrics = Metrics(service="payment") |
| 64 | + tracer = Tracer(service="payment") |
| 65 | +
|
| 66 | + @tracer.capture_lambda_handler |
| 67 | + @metrics.log_metrics |
| 68 | + def handler(event, context): |
| 69 | + ... |
| 70 | +
|
| 71 | + Parameters |
| 72 | + ---------- |
| 73 | + lambda_handler : Callable[[Any, Any], Any], optional |
| 74 | + lambda function handler, by default None |
| 75 | + capture_cold_start_metric : bool, optional |
| 76 | + captures cold start metric, by default False |
| 77 | + raise_on_empty_metrics : bool, optional |
| 78 | + raise exception if no metrics are emitted, by default False |
| 79 | + default_dimensions: Dict[str, str], optional |
| 80 | + metric dimensions as key=value that will always be present |
| 81 | +
|
| 82 | + Raises |
| 83 | + ------ |
| 84 | + e |
| 85 | + Propagate error received |
| 86 | + """ |
| 87 | + |
| 88 | + # If handler is None we've been called with parameters |
| 89 | + # Return a partial function with args filled |
| 90 | + if lambda_handler is None: |
| 91 | + logger.debug("Decorator called with parameters") |
| 92 | + return functools.partial( |
| 93 | + self.log_metrics, |
| 94 | + capture_cold_start_metric=capture_cold_start_metric, |
| 95 | + raise_on_empty_metrics=raise_on_empty_metrics, |
| 96 | + ) |
| 97 | + |
| 98 | + @functools.wraps(lambda_handler) |
| 99 | + def decorate(event, context): |
| 100 | + try: |
| 101 | + response = lambda_handler(event, context) |
| 102 | + if capture_cold_start_metric: |
| 103 | + self._add_cold_start_metric(context=context) |
| 104 | + finally: |
| 105 | + self.flush_metrics(raise_on_empty_metrics=raise_on_empty_metrics) |
| 106 | + |
| 107 | + return response |
| 108 | + |
| 109 | + return decorate |
| 110 | + |
| 111 | + def _add_cold_start_metric(self, context: Any) -> None: |
| 112 | + """Add cold start metric and function_name dimension |
| 113 | +
|
| 114 | + Parameters |
| 115 | + ---------- |
| 116 | + context : Any |
| 117 | + Lambda context |
| 118 | + """ |
| 119 | + global is_cold_start |
| 120 | + if not is_cold_start: |
| 121 | + return |
| 122 | + |
| 123 | + logger.debug("Adding cold start metric and function_name dimension") |
| 124 | + self.add_metric(name="ColdStart", value=1) |
| 125 | + |
| 126 | + is_cold_start = False |
0 commit comments