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