Structured Log JSON Formatter
Format Python log records as single-line JSON with extra fields, making logs machine-parsable without losing context.
Code
import json
import logging
RESERVED = {'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename',
'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName',
'created', 'msecs', 'relativeCreated', 'thread', 'threadName',
'processName', 'process', 'taskName'}
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
'level': record.levelname,
'message': record.getMessage(),
'logger': record.name,
'time': self.formatTime(record, '%Y-%m-%dT%H:%M:%S'),
}
for key, value in record.__dict__.items():
if key not in RESERVED and not key.startswith('_'):
payload[key] = value
if record.exc_info:
payload['exception'] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False, default=str)
def configure() -> None:
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler])Report a problem with this exampleOpens a pre-filled issue on GitHub.