Format the log record nicely. This formats the log record so that it: - starts with the level (colorized, and padded to 5 chars so that it is nicely aligned) - then has the actual log message, if it's multiline then it's nicely indented - then has the str
(self, record: logging.LogRecord)
| 122 | return extra_fields |
| 123 | |
| 124 | def format(self, record: logging.LogRecord) -> str: |
| 125 | """Format the log record nicely. |
| 126 | |
| 127 | This formats the log record so that it: |
| 128 | - starts with the level (colorized, and padded to 5 chars so that it is nicely aligned) |
| 129 | - then has the actual log message, if it's multiline then it's nicely indented |
| 130 | - then has the stringified extra log fields |
| 131 | - then, if an exception is a part of the log record, prints the formatted exception. |
| 132 | """ |
| 133 | logger_name_string = f'{_LOG_NAME_COLOR}[{record.name}]{Style.RESET_ALL} ' |
| 134 | |
| 135 | # Colorize the log level, and shorten it to 6 chars tops |
| 136 | level_color_code = _LOG_LEVEL_COLOR.get(record.levelno, '') |
| 137 | level_short_alias = _LOG_LEVEL_SHORT_ALIAS.get(record.levelno, record.levelname) |
| 138 | level_string = f'{level_color_code}{level_short_alias}{Style.RESET_ALL} ' |
| 139 | |
| 140 | # Format the extra log record fields, if there were some |
| 141 | # Just stringify them to JSON and color them gray |
| 142 | extra_string = '' |
| 143 | extra = self._get_extra_fields(record) |
| 144 | if extra: |
| 145 | extra_string = ( |
| 146 | f' {Fore.LIGHTBLACK_EX}({json.dumps(extra, ensure_ascii=False, default=str)}){Style.RESET_ALL}' |
| 147 | ) |
| 148 | |
| 149 | # Call the parent method so that it populates missing fields in the record |
| 150 | super().format(record) |
| 151 | |
| 152 | # Format the actual log message |
| 153 | log_string = self.formatMessage(record) |
| 154 | |
| 155 | # Format the exception, if there is some |
| 156 | # Basically just print the traceback and indent it a bit |
| 157 | exception_string = '' |
| 158 | if record.exc_text: |
| 159 | exception_string = '\n' + textwrap.indent(record.exc_text.rstrip(), _LOG_MESSAGE_INDENT) |
| 160 | else: |
| 161 | exception_string = '' |
| 162 | |
| 163 | if self.include_logger_name: |
| 164 | # Include logger name at the beginning of the log line |
| 165 | return f'{logger_name_string}{level_string}{log_string}{extra_string}{exception_string}' |
| 166 | |
| 167 | return f'{level_string}{log_string}{extra_string}{exception_string}' |