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])How it works
The working surface is the class JsonFormatter and the functions format and configure — everything else is wiring.
Iteration happens inside for key, value in record.__dict__.items() — everything outside it runs once.
Watch out for
- Plan for an install step:
loggingis a real dependency, resolved by the package manager.
Using it
The entry-point signature is def format(self, record: logging.LogRecord) -> str
format is what another module would consume; nothing else here is load-bearing for callers.
Key statements
def configure() -> None:
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler])
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- Does this require external packages?
- Yes — `logging`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.