1
1
import copy
2
2
import functools
3
- import itertools
4
3
import json
5
4
import logging
6
5
import os
7
6
import random
8
7
import sys
9
- import warnings
10
8
from distutils .util import strtobool
11
9
from typing import Any , Callable , Dict , Union
12
10
13
- from ..helper .models import MetricUnit , build_lambda_context_model , build_metric_unit_from_str
11
+ from ..helper .models import build_lambda_context_model
14
12
from .exceptions import InvalidLoggerSamplingRateError
15
13
16
14
logger = logging .getLogger (__name__ )
@@ -114,44 +112,6 @@ def format(self, record): # noqa: A003
114
112
return json_record
115
113
116
114
117
- def logger_setup (
118
- service : str = None , level : str = None , sampling_rate : float = 0.0 , legacy : bool = False , ** kwargs
119
- ) -> DeprecationWarning :
120
- """DEPRECATED
121
-
122
- This will be removed when GA - Use `aws_lambda_powertools.logging.logger.Logger` instead
123
-
124
- Example
125
- -------
126
- **Logger class - Same UX**
127
-
128
- from aws_lambda_powertools import Logger
129
- logger = Logger(service="payment") # same env var still applies
130
-
131
- """
132
- raise DeprecationWarning ("Use Logger instead - This method will be removed when GA" )
133
-
134
-
135
- def logger_inject_lambda_context (
136
- lambda_handler : Callable [[Dict , Any ], Any ] = None , log_event : bool = False
137
- ) -> DeprecationWarning :
138
- """DEPRECATED
139
-
140
- This will be removed when GA - Use `aws_lambda_powertools.logging.logger.Logger` instead
141
-
142
- Example
143
- -------
144
- **Logger class - Same UX**
145
-
146
- from aws_lambda_powertools import Logger
147
- logger = Logger(service="payment") # same env var still applies
148
- @logger.inject_lambda_context
149
- def handler(evt, ctx):
150
- pass
151
- """
152
- raise DeprecationWarning ("Use Logger instead - This method will be removed when GA" )
153
-
154
-
155
115
def _is_cold_start () -> bool :
156
116
"""Verifies whether is cold start
157
117
@@ -170,113 +130,6 @@ def _is_cold_start() -> bool:
170
130
return cold_start
171
131
172
132
173
- def log_metric (
174
- name : str , namespace : str , unit : MetricUnit , value : float = 0 , service : str = "service_undefined" , ** dimensions ,
175
- ):
176
- """Logs a custom metric in a statsD-esque format to stdout.
177
-
178
- **This will be removed when GA - Use `aws_lambda_powertools.metrics.metrics.Metrics` instead**
179
-
180
- Creating Custom Metrics synchronously impact on performance/execution time.
181
- Instead, log_metric prints a metric to CloudWatch Logs.
182
- That allows us to pick them up asynchronously via another Lambda function and create them as a metric.
183
-
184
- NOTE: It takes up to 9 dimensions by default, and Metric units are conveniently available via MetricUnit Enum.
185
- If service is not passed as arg or via env var, "service_undefined" will be used as dimension instead.
186
-
187
- **Output in CloudWatch Logs**: `MONITORING|<metric_value>|<metric_unit>|<metric_name>|<namespace>|<dimensions>`
188
-
189
- Serverless Application Repository App that creates custom metric from this log output:
190
- https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:374852340823:applications~async-custom-metrics
191
-
192
- Environment variables
193
- ---------------------
194
- POWERTOOLS_SERVICE_NAME: str
195
- service name
196
-
197
- Parameters
198
- ----------
199
- name : str
200
- metric name, by default None
201
- namespace : str
202
- metric namespace (e.g. application name), by default None
203
- unit : MetricUnit, by default MetricUnit.Count
204
- metric unit enum value (e.g. MetricUnit.Seconds), by default None\n
205
- API Info: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
206
- value : float, optional
207
- metric value, by default 0
208
- service : str, optional
209
- service name used as dimension, by default "service_undefined"
210
- dimensions: dict, optional
211
- keyword arguments as additional dimensions (e.g. `customer=customerId`)
212
-
213
- Example
214
- -------
215
- **Log metric to count number of successful payments; define service via env var**
216
-
217
- $ export POWERTOOLS_SERVICE_NAME="payment"
218
- from aws_lambda_powertools.logging import MetricUnit, log_metric
219
- log_metric(
220
- name="SuccessfulPayments",
221
- unit=MetricUnit.Count,
222
- value=1,
223
- namespace="DemoApp"
224
- )
225
-
226
- **Log metric to count number of successful payments per campaign & customer**
227
-
228
- from aws_lambda_powertools.logging import MetricUnit, log_metric
229
- log_metric(
230
- name="SuccessfulPayments",
231
- service="payment",
232
- unit=MetricUnit.Count,
233
- value=1,
234
- namespace="DemoApp",
235
- campaign=campaign_id,
236
- customer=customer_id
237
- )
238
- """
239
-
240
- warnings .warn (message = "This method will be removed in GA; use Metrics instead" , category = DeprecationWarning )
241
- logger .debug (f"Building new custom metric. Name: { name } , Unit: { unit } , Value: { value } , Dimensions: { dimensions } " )
242
- service = os .getenv ("POWERTOOLS_SERVICE_NAME" ) or service
243
- dimensions = __build_dimensions (** dimensions )
244
- unit = build_metric_unit_from_str (unit )
245
-
246
- metric = f"MONITORING|{ value } |{ unit .name } |{ name } |{ namespace } |service={ service } "
247
- if dimensions :
248
- metric = f"MONITORING|{ value } |{ unit .name } |{ name } |{ namespace } |service={ service } ,{ dimensions } "
249
-
250
- print (metric )
251
-
252
-
253
- def __build_dimensions (** dimensions ) -> str :
254
- """Builds correct format for custom metric dimensions from kwargs
255
-
256
- Parameters
257
- ----------
258
- dimensions: dict, optional
259
- additional dimensions
260
-
261
- Returns
262
- -------
263
- str
264
- Dimensions in the form of "key=value,key2=value2"
265
- """
266
- MAX_DIMENSIONS = 10
267
- dimension = ""
268
-
269
- # CloudWatch accepts a max of 10 dimensions per metric
270
- # We include service name as a dimension
271
- # so we take up to 9 values as additional dimensions
272
- # before we convert everything to a string of key=value
273
- dimensions_partition = dict (itertools .islice (dimensions .items (), MAX_DIMENSIONS ))
274
- dimensions_list = [dimension + "=" + value for dimension , value in dimensions_partition .items () if value ]
275
- dimension = "," .join (dimensions_list )
276
-
277
- return dimension
278
-
279
-
280
133
class Logger (logging .Logger ):
281
134
"""Creates and setups a logger to format statements in JSON.
282
135
0 commit comments