Structured JSON Logging Setup
Configure a JSON formatter so every log record carries consistent fields, making logs searchable and correlatable across services.
Code
import json
import logging
import sys
from datetime import datetime, timezone
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"level": record.levelname,
"message": record.getMessage(),
"logger": record.name,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload)
def configure_logging(level: str = "INFO") -> logging.Logger:
logger = logging.getLogger("app")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.setLevel(level)
return loggerHow the snippet works
Count the class JsonFormatter and the functions format and configure_logging as the entire surface area of Structured JSON Logging Setup.
datetime, timezone are the only symbols borrowed from logging — the coupling is explicit and narrow.
What to watch for
- Plan for an install step:
loggingis a real dependency, resolved by the package manager.
Applying it
The main signature reads def format(self, record: logging.LogRecord) -> str
format is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def configure_logging(level: str = "INFO") -> logging.Logger:
logger = logging.getLogger("app")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.setLevel(level)
return logger
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
- Do I need to install anything before running this?
- Yes: `logging` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.