Existing answers answered the indentation part well. But the new format
implementation did not handle other fields (e.g. exec_info
, stack_info
) properly compared to the original logging.Formatter
.
The below implementation is based on simonzack's answer and reuses the original formatter to minimize the side effects.
[edit 2021-11] it also handles formatted values correctly by post-processing the formatted message instead of pre-processing it
class MultiLineFormatter(logging.Formatter):
"""Multi-line formatter."""
def get_header_length(self, record):
"""Get the header length of a given record."""
return len(super().format(logging.LogRecord(
name=record.name,
level=record.levelno,
pathname=record.pathname,
lineno=record.lineno,
msg='', args=(), exc_info=None
)))
def format(self, record):
"""Format a record with added indentation."""
indent = ' ' * self.get_header_length(record)
head, *trailing = super().format(record).splitlines(True)
return head + ''.join(indent + line for line in trailing)
\r\n
so all the desired aligned elements are left-aligned. Not exactly the requested functionality, but maybe accomplishes the goal very simply. – Wrath