Skip to content

chore: remove deprecated code before GA #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions aws_lambda_powertools/helper/__init__.py

This file was deleted.

132 changes: 0 additions & 132 deletions aws_lambda_powertools/helper/models.py

This file was deleted.

5 changes: 2 additions & 3 deletions aws_lambda_powertools/logging/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Logging utility
"""
from ..helper.models import MetricUnit
from .logger import Logger, log_metric, logger_inject_lambda_context, logger_setup
from .logger import Logger

__all__ = ["logger_setup", "logger_inject_lambda_context", "log_metric", "MetricUnit", "Logger"]
__all__ = ["Logger"]
99 changes: 99 additions & 0 deletions aws_lambda_powertools/logging/formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import json
import logging
from typing import Any


def json_formatter(unserialized_value: Any):
"""JSON custom serializer to cast unserialisable values to strings.

Example
-------

**Serialize unserialisable value to string**

class X: pass
value = {"x": X()}

json.dumps(value, default=json_formatter)

Parameters
----------
unserialized_value: Any
Python object unserializable by JSON
"""
return str(unserialized_value)


class JsonFormatter(logging.Formatter):
"""AWS Lambda Logging formatter.

Formats the log message as a JSON encoded string. If the message is a
dict it will be used directly. If the message can be parsed as JSON, then
the parse d value is used in the output record.

Originally taken from https://gitlab.com/hadrien/aws_lambda_logging/

"""

def __init__(self, **kwargs):
"""Return a JsonFormatter instance.

The `json_default` kwarg is used to specify a formatter for otherwise
unserialisable values. It must not throw. Defaults to a function that
coerces the value to a string.

Other kwargs are used to specify log field format strings.
"""
datefmt = kwargs.pop("datefmt", None)

super(JsonFormatter, self).__init__(datefmt=datefmt)
self.reserved_keys = ["timestamp", "level", "location"]
self.format_dict = {
"timestamp": "%(asctime)s",
"level": "%(levelname)s",
"location": "%(funcName)s:%(lineno)d",
}
self.format_dict.update(kwargs)
self.default_json_formatter = kwargs.pop("json_default", json_formatter)

def format(self, record): # noqa: A003
record_dict = record.__dict__.copy()
record_dict["asctime"] = self.formatTime(record, self.datefmt)

log_dict = {}
for key, value in self.format_dict.items():
if value and key in self.reserved_keys:
# converts default logging expr to its record value
# e.g. '%(asctime)s' to '2020-04-24 09:35:40,698'
log_dict[key] = value % record_dict
else:
log_dict[key] = value

if isinstance(record_dict["msg"], dict):
log_dict["message"] = record_dict["msg"]
else:
log_dict["message"] = record.getMessage()

# Attempt to decode the message as JSON, if so, merge it with the
# overall message for clarity.
try:
log_dict["message"] = json.loads(log_dict["message"])
except (json.decoder.JSONDecodeError, TypeError, ValueError):
pass

if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
# from logging.Formatter:format
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)

if record.exc_text:
log_dict["exception"] = record.exc_text

json_record = json.dumps(log_dict, default=self.default_json_formatter)

if hasattr(json_record, "decode"): # pragma: no cover
json_record = json_record.decode("utf-8")

return json_record
55 changes: 55 additions & 0 deletions aws_lambda_powertools/logging/lambda_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class LambdaContextModel:
"""A handful of Lambda Runtime Context fields

Full Lambda Context object: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

Parameters
----------
function_name: str
Lambda function name, by default "UNDEFINED"
e.g. "test"
function_memory_size: int
Lambda function memory in MB, by default 128
function_arn: str
Lambda function ARN, by default "UNDEFINED"
e.g. "arn:aws:lambda:eu-west-1:809313241:function:test"
function_request_id: str
Lambda function unique request id, by default "UNDEFINED"
e.g. "52fdfc07-2182-154f-163f-5f0f9a621d72"
"""

def __init__(
self,
function_name: str = "UNDEFINED",
function_memory_size: int = 128,
function_arn: str = "UNDEFINED",
function_request_id: str = "UNDEFINED",
):
self.function_name = function_name
self.function_memory_size = function_memory_size
self.function_arn = function_arn
self.function_request_id = function_request_id


def build_lambda_context_model(context: object) -> LambdaContextModel:
"""Captures Lambda function runtime info to be used across all log statements

Parameters
----------
context : object
Lambda context object

Returns
-------
LambdaContextModel
Lambda context only with select fields
"""

context = {
"function_name": context.function_name,
"function_memory_size": context.memory_limit_in_mb,
"function_arn": context.invoked_function_arn,
"function_request_id": context.aws_request_id,
}

return LambdaContextModel(**context)
Loading