|
1 | 1 | import json
|
2 | 2 | import logging
|
| 3 | +import os |
3 | 4 |
|
4 | 5 |
|
5 | 6 | class JsonFormatter(logging.Formatter):
|
@@ -29,14 +30,27 @@ def __init__(self, **kwargs):
|
29 | 30 | # Set the default unserializable function, by default values will be cast as str.
|
30 | 31 | self.default_json_formatter = kwargs.pop("json_default", str)
|
31 | 32 | # Set the insertion order for the log messages
|
32 |
| - self.format_dict = dict.fromkeys(kwargs.pop("log_record_order", ["level", "location", "message", "timestamp"])) |
| 33 | + self.format_dict = dict.fromkeys( |
| 34 | + kwargs.pop("log_record_order", ["level", "location", "message", "xray_trace_id", "timestamp"]) |
| 35 | + ) |
| 36 | + self.reserved_keys = ["timestamp", "level", "location"] |
33 | 37 | # Set the date format used by `asctime`
|
34 | 38 | super(JsonFormatter, self).__init__(datefmt=kwargs.pop("datefmt", None))
|
35 | 39 |
|
36 |
| - self.reserved_keys = ["timestamp", "level", "location"] |
37 |
| - self.format_dict.update( |
38 |
| - {"level": "%(levelname)s", "location": "%(funcName)s:%(lineno)d", "timestamp": "%(asctime)s", **kwargs} |
39 |
| - ) |
| 40 | + self.format_dict.update(self._build_root_keys(**kwargs)) |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def _build_root_keys(**kwargs): |
| 44 | + xray_trace_id = os.getenv("_X_AMZN_TRACE_ID") |
| 45 | + trace_id = xray_trace_id.split(";")[0].replace("Root=", "") if xray_trace_id else None |
| 46 | + |
| 47 | + return { |
| 48 | + "level": "%(levelname)s", |
| 49 | + "location": "%(funcName)s:%(lineno)d", |
| 50 | + "xray_trace_id": trace_id, |
| 51 | + "timestamp": "%(asctime)s", |
| 52 | + **kwargs, |
| 53 | + } |
40 | 54 |
|
41 | 55 | def update_formatter(self, **kwargs):
|
42 | 56 | self.format_dict.update(kwargs)
|
|
0 commit comments