Skip to content

Commit 69d5fda

Browse files
authored
chore: remove deprecated code before GA (#78)
* chore: remove Logger deprecated code * chore: remove Metrics deprecated code * chore: remove models from deprecated code * chore: move logger formatter to its own file
1 parent 57d2905 commit 69d5fda

File tree

12 files changed

+234
-624
lines changed

12 files changed

+234
-624
lines changed

Diff for: aws_lambda_powertools/helper/__init__.py

-2
This file was deleted.

Diff for: aws_lambda_powertools/helper/models.py

-132
This file was deleted.

Diff for: aws_lambda_powertools/logging/__init__.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Logging utility
22
"""
3-
from ..helper.models import MetricUnit
4-
from .logger import Logger, log_metric, logger_inject_lambda_context, logger_setup
3+
from .logger import Logger
54

6-
__all__ = ["logger_setup", "logger_inject_lambda_context", "log_metric", "MetricUnit", "Logger"]
5+
__all__ = ["Logger"]

Diff for: aws_lambda_powertools/logging/formatter.py

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import json
2+
import logging
3+
from typing import Any
4+
5+
6+
def json_formatter(unserialized_value: Any):
7+
"""JSON custom serializer to cast unserialisable values to strings.
8+
9+
Example
10+
-------
11+
12+
**Serialize unserialisable value to string**
13+
14+
class X: pass
15+
value = {"x": X()}
16+
17+
json.dumps(value, default=json_formatter)
18+
19+
Parameters
20+
----------
21+
unserialized_value: Any
22+
Python object unserializable by JSON
23+
"""
24+
return str(unserialized_value)
25+
26+
27+
class JsonFormatter(logging.Formatter):
28+
"""AWS Lambda Logging formatter.
29+
30+
Formats the log message as a JSON encoded string. If the message is a
31+
dict it will be used directly. If the message can be parsed as JSON, then
32+
the parse d value is used in the output record.
33+
34+
Originally taken from https://gitlab.com/hadrien/aws_lambda_logging/
35+
36+
"""
37+
38+
def __init__(self, **kwargs):
39+
"""Return a JsonFormatter instance.
40+
41+
The `json_default` kwarg is used to specify a formatter for otherwise
42+
unserialisable values. It must not throw. Defaults to a function that
43+
coerces the value to a string.
44+
45+
Other kwargs are used to specify log field format strings.
46+
"""
47+
datefmt = kwargs.pop("datefmt", None)
48+
49+
super(JsonFormatter, self).__init__(datefmt=datefmt)
50+
self.reserved_keys = ["timestamp", "level", "location"]
51+
self.format_dict = {
52+
"timestamp": "%(asctime)s",
53+
"level": "%(levelname)s",
54+
"location": "%(funcName)s:%(lineno)d",
55+
}
56+
self.format_dict.update(kwargs)
57+
self.default_json_formatter = kwargs.pop("json_default", json_formatter)
58+
59+
def format(self, record): # noqa: A003
60+
record_dict = record.__dict__.copy()
61+
record_dict["asctime"] = self.formatTime(record, self.datefmt)
62+
63+
log_dict = {}
64+
for key, value in self.format_dict.items():
65+
if value and key in self.reserved_keys:
66+
# converts default logging expr to its record value
67+
# e.g. '%(asctime)s' to '2020-04-24 09:35:40,698'
68+
log_dict[key] = value % record_dict
69+
else:
70+
log_dict[key] = value
71+
72+
if isinstance(record_dict["msg"], dict):
73+
log_dict["message"] = record_dict["msg"]
74+
else:
75+
log_dict["message"] = record.getMessage()
76+
77+
# Attempt to decode the message as JSON, if so, merge it with the
78+
# overall message for clarity.
79+
try:
80+
log_dict["message"] = json.loads(log_dict["message"])
81+
except (json.decoder.JSONDecodeError, TypeError, ValueError):
82+
pass
83+
84+
if record.exc_info:
85+
# Cache the traceback text to avoid converting it multiple times
86+
# (it's constant anyway)
87+
# from logging.Formatter:format
88+
if not record.exc_text:
89+
record.exc_text = self.formatException(record.exc_info)
90+
91+
if record.exc_text:
92+
log_dict["exception"] = record.exc_text
93+
94+
json_record = json.dumps(log_dict, default=self.default_json_formatter)
95+
96+
if hasattr(json_record, "decode"): # pragma: no cover
97+
json_record = json_record.decode("utf-8")
98+
99+
return json_record

Diff for: aws_lambda_powertools/logging/lambda_context.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class LambdaContextModel:
2+
"""A handful of Lambda Runtime Context fields
3+
4+
Full Lambda Context object: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
5+
6+
Parameters
7+
----------
8+
function_name: str
9+
Lambda function name, by default "UNDEFINED"
10+
e.g. "test"
11+
function_memory_size: int
12+
Lambda function memory in MB, by default 128
13+
function_arn: str
14+
Lambda function ARN, by default "UNDEFINED"
15+
e.g. "arn:aws:lambda:eu-west-1:809313241:function:test"
16+
function_request_id: str
17+
Lambda function unique request id, by default "UNDEFINED"
18+
e.g. "52fdfc07-2182-154f-163f-5f0f9a621d72"
19+
"""
20+
21+
def __init__(
22+
self,
23+
function_name: str = "UNDEFINED",
24+
function_memory_size: int = 128,
25+
function_arn: str = "UNDEFINED",
26+
function_request_id: str = "UNDEFINED",
27+
):
28+
self.function_name = function_name
29+
self.function_memory_size = function_memory_size
30+
self.function_arn = function_arn
31+
self.function_request_id = function_request_id
32+
33+
34+
def build_lambda_context_model(context: object) -> LambdaContextModel:
35+
"""Captures Lambda function runtime info to be used across all log statements
36+
37+
Parameters
38+
----------
39+
context : object
40+
Lambda context object
41+
42+
Returns
43+
-------
44+
LambdaContextModel
45+
Lambda context only with select fields
46+
"""
47+
48+
context = {
49+
"function_name": context.function_name,
50+
"function_memory_size": context.memory_limit_in_mb,
51+
"function_arn": context.invoked_function_arn,
52+
"function_request_id": context.aws_request_id,
53+
}
54+
55+
return LambdaContextModel(**context)

0 commit comments

Comments
 (0)