Sub topic 13
Structured JSON logging with a custom formatter
This chapter assumes you know how loggers, handlers, and formatters fit together, and that you can subclass a class in Python.
Why structure the output
A text line such as 2026-11-26 11:44:55 INFO myapp: User alice logged in is easy for a person to read. A log tool has to parse it with regular expressions before it can filter by user or level. If each record is one JSON object per line, the tool reads the fields directly.
The logging module already separates what is logged from how it looks. A custom Formatter is the only part you replace.
A minimal JSON formatter
Subclass logging.Formatter and override format. It receives a LogRecord and must return a string.
import json
import logging
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {
"time": self.formatTime(record),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("User %s logged in", "alice")The output is one line:
{"time": "2026-11-26 11:44:55,307", "level": "INFO", "logger": "myapp", "message": "User alice logged in"}Three details matter here:
record.getMessage()applies the%sarguments to the message. Use it instead ofrecord.msg, which is the unformatted template.formatExceptionturns the exception info into a traceback string.json.dumpsescapes newlines, so a multi-line traceback stays inside one JSON line.
Including extra fields
The extra argument to a logging call copies its keys onto the record as attributes. To include them in the JSON, collect every attribute that is not part of a standard record.
import json
import logging
_STANDARD = set(vars(logging.makeLogRecord({})))
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {
"time": self.formatTime(record),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
for key, value in vars(record).items():
if key not in _STANDARD:
payload[key] = value
return json.dumps(payload, default=str)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Order placed", extra={"user_id": 42, "total": 19.99})logging.makeLogRecord({}) builds an empty record, so _STANDARD holds the names of the built-in attributes. Anything else on a real record came from extra (or from a filter, as in the earlier filters chapter).
Common mistakes
- Putting
JsonFormatteron only one handler. Each handler has its own formatter, so a file handler still writes plain text unless you set the formatter on it too. - Calling
json.dumpsonrecord.__dict__. It containsexc_infoand other objects that are not serializable. - Using
record.msginstead ofrecord.getMessage(), which leaves%splaceholders unfilled.
Exercise
Why does the JSON formatter call record.getMessage() instead of reading record.msg, and why does a multi-line traceback not break the one-line-per-record format?
Show answer
record.msg is the template before arguments are applied, so "User %s logged in" would keep its placeholder. getMessage() merges the arguments into it. A traceback stays on one line because json.dumps escapes each newline in the string as \n.