Commit 7f31567463290273a48ad11066c78264c91a72f4
1 parent
28c0449c
log_helper: Format text in JsonFormatter
Use a standard logging.Formatter to do %-formatting and other stuff (i.e. the regular formatter job) before converting to Json.
Showing
1 changed file
with
14 additions
and
7 deletions
oletools/common/log_helper/_json_formatter.py
| ... | ... | @@ -5,12 +5,17 @@ import json |
| 5 | 5 | class JsonFormatter(logging.Formatter): |
| 6 | 6 | """ |
| 7 | 7 | Format every message to be logged as a JSON object |
| 8 | + | |
| 9 | + Uses the standard :py:class:`logging.Formatter` with standard arguments | |
| 10 | + to do the actual formatting, could save and use a user-supplied formatter | |
| 11 | + instead. | |
| 8 | 12 | """ |
| 9 | 13 | _is_first_line = True |
| 10 | 14 | |
| 11 | 15 | def __init__(self, other_logger_has_first_line=False): |
| 12 | 16 | if other_logger_has_first_line: |
| 13 | 17 | self._is_first_line = False |
| 18 | + self.msg_formatter = logging.Formatter() # could adjust this | |
| 14 | 19 | |
| 15 | 20 | def format(self, record): |
| 16 | 21 | """ |
| ... | ... | @@ -18,15 +23,17 @@ class JsonFormatter(logging.Formatter): |
| 18 | 23 | the output JSON-compatible. The only exception is when printing the first line, |
| 19 | 24 | so we need to keep track of it. |
| 20 | 25 | |
| 21 | - The resulting text is just a json dump of the :py:class:`logging.LogRecord` | |
| 22 | - object that is received as input, so no %-formatting or similar is done. Raw | |
| 23 | - unformatted message and formatting arguments are contained in fields `msg` and | |
| 24 | - `args` of the output. | |
| 26 | + The actual conversion from :py:class:`logging.LogRecord` to a text message | |
| 27 | + (i.e. %-formatting, adding exception information, etc.) is delegated to the | |
| 28 | + standard :py:class:`logging.Formatter. | |
| 25 | 29 | |
| 26 | - Arg `record` has a `type` field when created by `OletoolLoggerAdapter`. If not | |
| 27 | - (e.g. captured warnings or output from third-party libraries), we add one. | |
| 30 | + The dumped json structure contains fields `msg` with the formatted message, | |
| 31 | + `level` with the log-level of the message and `type`, which is created by | |
| 32 | + :py:class:`oletools.common.log_helper.OletoolsLoggerAdapter` or added here | |
| 33 | + (for input from e.g. captured warnings, third-party libraries) | |
| 28 | 34 | """ |
| 29 | - json_dict = dict(msg=record.msg.replace('\n', ' '), level=record.levelname) | |
| 35 | + msg = self.msg_formatter.format(record) | |
| 36 | + json_dict = dict(msg=msg.replace('\n', ' '), level=record.levelname) | |
| 30 | 37 | try: |
| 31 | 38 | json_dict['type'] = record.type |
| 32 | 39 | except AttributeError: | ... | ... |