Commit cdede5b167671e8116d45ce85ddd8aafcb8374c1
1 parent
ca0ee46c
log_helper: allow integration with other json-printers
Make log_helper compatible with olevba which has its own print_json function and does not (yet?) use logging to create json.
Showing
2 changed files
with
10 additions
and
2 deletions
oletools/common/log_helper/_json_formatter.py
| ... | ... | @@ -8,6 +8,10 @@ class JsonFormatter(logging.Formatter): |
| 8 | 8 | """ |
| 9 | 9 | _is_first_line = True |
| 10 | 10 | |
| 11 | + def __init__(self, other_logger_has_first_line=False): | |
| 12 | + if other_logger_has_first_line: | |
| 13 | + self._is_first_line = False | |
| 14 | + | |
| 11 | 15 | def format(self, record): |
| 12 | 16 | """ |
| 13 | 17 | Since we don't buffer messages, we always prepend messages with a comma to make | ... | ... |
oletools/common/log_helper/log_helper.py
| ... | ... | @@ -82,7 +82,8 @@ class LogHelper: |
| 82 | 82 | """ |
| 83 | 83 | return self._get_or_create_logger(name, level, logging.NullHandler()) |
| 84 | 84 | |
| 85 | - def enable_logging(self, use_json=False, level='warning', log_format=DEFAULT_MESSAGE_FORMAT, stream=None): | |
| 85 | + def enable_logging(self, use_json=False, level='warning', log_format=DEFAULT_MESSAGE_FORMAT, stream=None, | |
| 86 | + other_logger_has_first_line=False): | |
| 86 | 87 | """ |
| 87 | 88 | This function initializes the root logger and enables logging. |
| 88 | 89 | We set the level of the root logger to the one passed by calling logging.basicConfig. |
| ... | ... | @@ -93,6 +94,9 @@ class LogHelper: |
| 93 | 94 | which in turn will log to the stream set in this function. |
| 94 | 95 | Since the root logger is the one doing the work, when using JSON we set its formatter |
| 95 | 96 | so that every message logged is JSON-compatible. |
| 97 | + | |
| 98 | + If other code also creates json output, that other code should output the | |
| 99 | + first logging line and tell us via `other_logger_has_first_line`. | |
| 96 | 100 | """ |
| 97 | 101 | if self._is_enabled: |
| 98 | 102 | raise ValueError('re-enabling logging. Not sure whether that is ok...') |
| ... | ... | @@ -115,7 +119,7 @@ class LogHelper: |
| 115 | 119 | |
| 116 | 120 | # add a JSON formatter to the root logger, which will be used by every logger |
| 117 | 121 | if self._use_json: |
| 118 | - _root_logger_wrapper.set_formatter(JsonFormatter()) | |
| 122 | + _root_logger_wrapper.set_formatter(JsonFormatter(other_logger_has_first_line)) | |
| 119 | 123 | print('[') |
| 120 | 124 | |
| 121 | 125 | def end_logging(self): | ... | ... |