9
9
from abc import ABCMeta , abstractmethod
10
10
from datetime import datetime , timezone
11
11
from functools import partial
12
- from typing import Any , Callable , Dict , Iterable , List , Optional , Tuple , Union
12
+ from typing import TYPE_CHECKING , Any , Callable , Iterable
13
13
14
- from aws_lambda_powertools .logging .types import LogRecord , LogStackTrace
15
14
from aws_lambda_powertools .shared import constants
16
15
from aws_lambda_powertools .shared .functions import powertools_dev_is_set
17
16
17
+ if TYPE_CHECKING :
18
+ from aws_lambda_powertools .logging .types import LogRecord , LogStackTrace
19
+
18
20
RESERVED_LOG_ATTRS = (
19
21
"name" ,
20
22
"msg" ,
@@ -48,7 +50,7 @@ class BasePowertoolsFormatter(logging.Formatter, metaclass=ABCMeta):
48
50
def append_keys (self , ** additional_keys ) -> None :
49
51
raise NotImplementedError ()
50
52
51
- def get_current_keys (self ) -> Dict [str , Any ]:
53
+ def get_current_keys (self ) -> dict [str , Any ]:
52
54
return {}
53
55
54
56
def remove_keys (self , keys : Iterable [str ]) -> None :
@@ -74,11 +76,11 @@ class LambdaPowertoolsFormatter(BasePowertoolsFormatter):
74
76
def __init__ (
75
77
self ,
76
78
json_serializer : Callable [[LogRecord ], str ] | None = None ,
77
- json_deserializer : Callable [[Dict | str | bool | int | float ], str ] | None = None ,
79
+ json_deserializer : Callable [[dict | str | bool | int | float ], str ] | None = None ,
78
80
json_default : Callable [[Any ], Any ] | None = None ,
79
81
datefmt : str | None = None ,
80
82
use_datetime_directive : bool = False ,
81
- log_record_order : List [str ] | None = None ,
83
+ log_record_order : list [str ] | None = None ,
82
84
utc : bool = False ,
83
85
use_rfc3339 : bool = False ,
84
86
serialize_stacktrace : bool = True ,
@@ -182,7 +184,7 @@ def format(self, record: logging.LogRecord) -> str: # noqa: A003
182
184
183
185
return self .serialize (log = formatted_log )
184
186
185
- def formatTime (self , record : logging .LogRecord , datefmt : Optional [ str ] = None ) -> str :
187
+ def formatTime (self , record : logging .LogRecord , datefmt : str | None = None ) -> str :
186
188
# As of Py3.7, we can infer milliseconds directly from any datetime
187
189
# saving processing time as we can shortcircuit early
188
190
# Maintenance: In V3, we (and Java) should move to this format by default
@@ -234,7 +236,7 @@ def formatTime(self, record: logging.LogRecord, datefmt: Optional[str] = None) -
234
236
def append_keys (self , ** additional_keys ) -> None :
235
237
self .log_format .update (additional_keys )
236
238
237
- def get_current_keys (self ) -> Dict [str , Any ]:
239
+ def get_current_keys (self ) -> dict [str , Any ]:
238
240
return self .log_format
239
241
240
242
def remove_keys (self , keys : Iterable [str ]) -> None :
@@ -246,14 +248,14 @@ def clear_state(self) -> None:
246
248
self .log_format .update (** self .keys_combined )
247
249
248
250
@staticmethod
249
- def _build_default_keys () -> Dict [str , str ]:
251
+ def _build_default_keys () -> dict [str , str ]:
250
252
return {
251
253
"level" : "%(levelname)s" ,
252
254
"location" : "%(funcName)s:%(lineno)d" ,
253
255
"timestamp" : "%(asctime)s" ,
254
256
}
255
257
256
- def _get_latest_trace_id (self ) -> Optional [ str ] :
258
+ def _get_latest_trace_id (self ) -> str | None :
257
259
xray_trace_id_key = self .log_format .get ("xray_trace_id" , "" )
258
260
if xray_trace_id_key is None :
259
261
# key is explicitly disabled; ignore it. e.g., Logger(xray_trace_id=None)
@@ -262,7 +264,7 @@ def _get_latest_trace_id(self) -> Optional[str]:
262
264
xray_trace_id = os .getenv (constants .XRAY_TRACE_ID_ENV )
263
265
return xray_trace_id .split (";" )[0 ].replace ("Root=" , "" ) if xray_trace_id else None
264
266
265
- def _extract_log_message (self , log_record : logging .LogRecord ) -> Union [ Dict [ str , Any ], str , bool , Iterable ] :
267
+ def _extract_log_message (self , log_record : logging .LogRecord ) -> dict [ str , Any ] | str | bool | Iterable :
266
268
"""Extract message from log record and attempt to JSON decode it if str
267
269
268
270
Parameters
@@ -272,7 +274,7 @@ def _extract_log_message(self, log_record: logging.LogRecord) -> Union[Dict[str,
272
274
273
275
Returns
274
276
-------
275
- message: Union[Dict, str, bool, Iterable]
277
+ message: dict[str, Any] | str | bool | Iterable
276
278
Extracted message
277
279
"""
278
280
message = log_record .msg
@@ -308,7 +310,7 @@ def _serialize_stacktrace(self, log_record: logging.LogRecord) -> LogStackTrace
308
310
309
311
return None
310
312
311
- def _extract_log_exception (self , log_record : logging .LogRecord ) -> Union [ Tuple [ str , str ], Tuple [None , None ] ]:
313
+ def _extract_log_exception (self , log_record : logging .LogRecord ) -> tuple [ str , str ] | tuple [None , None ]:
312
314
"""Format traceback information, if available
313
315
314
316
Parameters
@@ -318,15 +320,15 @@ def _extract_log_exception(self, log_record: logging.LogRecord) -> Union[Tuple[s
318
320
319
321
Returns
320
322
-------
321
- log_record: Optional[Tuple[ str, str]]
323
+ log_record: tuple[ str, str] | tuple[None, None ]
322
324
Log record with constant traceback info and exception name
323
325
"""
324
326
if log_record .exc_info :
325
327
return self .formatException (log_record .exc_info ), log_record .exc_info [0 ].__name__ # type: ignore
326
328
327
329
return None , None
328
330
329
- def _extract_log_keys (self , log_record : logging .LogRecord ) -> Dict [str , Any ]:
331
+ def _extract_log_keys (self , log_record : logging .LogRecord ) -> dict [str , Any ]:
330
332
"""Extract and parse custom and reserved log keys
331
333
332
334
Parameters
@@ -336,7 +338,7 @@ def _extract_log_keys(self, log_record: logging.LogRecord) -> Dict[str, Any]:
336
338
337
339
Returns
338
340
-------
339
- formatted_log: Dict
341
+ formatted_log: dict[str, Any]
340
342
Structured log as dictionary
341
343
"""
342
344
record_dict = log_record .__dict__ .copy ()
@@ -358,7 +360,7 @@ def _extract_log_keys(self, log_record: logging.LogRecord) -> Dict[str, Any]:
358
360
return formatted_log
359
361
360
362
@staticmethod
361
- def _strip_none_records (records : Dict [str , Any ]) -> Dict [str , Any ]:
363
+ def _strip_none_records (records : dict [str , Any ]) -> dict [str , Any ]:
362
364
"""Remove any key with None as value"""
363
365
return {k : v for k , v in records .items () if v is not None }
364
366
@@ -367,4 +369,4 @@ def _strip_none_records(records: Dict[str, Any]) -> Dict[str, Any]:
367
369
368
370
369
371
# Fetch current and future parameters from PowertoolsFormatter that should be reserved
370
- RESERVED_FORMATTER_CUSTOM_KEYS : List [str ] = inspect .getfullargspec (LambdaPowertoolsFormatter ).args [1 :]
372
+ RESERVED_FORMATTER_CUSTOM_KEYS : list [str ] = inspect .getfullargspec (LambdaPowertoolsFormatter ).args [1 :]
0 commit comments