|
3 | 3 | import os
|
4 | 4 | from typing import Dict, Iterable, Optional, Union
|
5 | 5 |
|
| 6 | +STD_LOGGING_KEYS = ( |
| 7 | + "name", |
| 8 | + "msg", |
| 9 | + "args", |
| 10 | + "levelname", |
| 11 | + "levelno", |
| 12 | + "pathname", |
| 13 | + "filename", |
| 14 | + "module", |
| 15 | + "exc_info", |
| 16 | + "exc_text", |
| 17 | + "stack_info", |
| 18 | + "lineno", |
| 19 | + "funcName", |
| 20 | + "created", |
| 21 | + "msecs", |
| 22 | + "relativeCreated", |
| 23 | + "thread", |
| 24 | + "threadName", |
| 25 | + "processName", |
| 26 | + "process", |
| 27 | + "asctime", |
| 28 | +) |
| 29 | + |
6 | 30 |
|
7 | 31 | class JsonFormatter(logging.Formatter):
|
8 | 32 | """AWS Lambda Logging formatter.
|
@@ -120,15 +144,21 @@ def _extract_log_keys(self, log_record: logging.LogRecord) -> Dict:
|
120 | 144 |
|
121 | 145 | formatted_log = {}
|
122 | 146 |
|
123 |
| - # Iterate over new or existing log structure |
124 |
| - # replace reserved logging expression e.g. '%(level)s' to 'INFO' |
125 |
| - # lastly, add or replace non-reserved keys |
| 147 | + # We have to iterate over a default or existing log structure |
| 148 | + # then replace any logging expression for reserved keys e.g. '%(level)s' to 'INFO' |
| 149 | + # and lastly add or replace incoming keys (those added within the constructor or .structure_logs method) |
126 | 150 | for key, value in self.log_format.items():
|
127 | 151 | if value and key in self.reserved_keys:
|
128 | 152 | formatted_log[key] = value % record_dict
|
129 | 153 | else:
|
130 | 154 | formatted_log[key] = value
|
131 | 155 |
|
| 156 | + # pick up extra keys when logging a new message e.g. log.info("my message", extra={"additional_key": "value"} |
| 157 | + # these messages will be added to the root of the final structure not within `message` key |
| 158 | + for key, value in record_dict.items(): |
| 159 | + if key not in STD_LOGGING_KEYS: |
| 160 | + formatted_log[key] = value |
| 161 | + |
132 | 162 | return formatted_log
|
133 | 163 |
|
134 | 164 | def format(self, record): # noqa: A003
|
|
0 commit comments