Sub topic 13
Structured JSON logging with a custom formatter
Plain-text log lines are easy to read but hard for a program to parse. A log shipper, a search index, or a jq command has to guess where the timestamp ends and the message begins. Structured logging writes each record as one JSON object per line, so every field has a name and a type.
This chapter assumes you know how loggers, handlers, and formatters connect, and how extra= and filters add attributes to a record. It builds a JSON formatter step by step and covers the edge cases that break naive versions.
What a formatter receives
A handler calls formatter.format(record) and writes the returned string. record is a LogRecord. Its attributes include name, levelname, created, msg, args, exc_info, and stack_info. Calling record.getMessage() applies msg % args and gives the final message text.
To produce JSON, override format(). Build a dictionary from the record and return json.dumps(...) of it.
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:34:01,602", "level": "INFO", "logger": "myapp", "message": "User alice logged in"}Three choices in this code matter:
getMessage()applies the lazy%sformatting. Do not readrecord.msgdirectly, because it still holds the unformatted template.formatException()turns theexc_infotuple into a traceback string. The traceback lives inside a JSON string, so its newlines are escaped as\nand the record stays on one line.- The formatter does not call
super().format(). The base class would buildrecord.messageandrecord.asctimeand cacherecord.exc_text, but you don't need any of that when you construct the output yourself.
Choosing field names and time format
formatTime(record) uses the local time zone and the format 2026-11-26 11:34:01,602. That format is ambiguous across machines and awkward to parse. Most log pipelines expect an ISO 8601 timestamp in UTC. Compute it from record.created, which is a Unix timestamp:
from datetime import datetime, timezone
def iso_utc(record):
return datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat()Pick field names once and keep them stable. Downstream dashboards and alerts depend on them. The table lists common mappings.
| JSON field | Source on the record |
|---|---|
| `time` | `record.created`, converted to UTC |
| `level` | `record.levelname` |
| `logger` | `record.name` |
| `message` | `record.getMessage()` |
| `module`, `line` | `record.module`, `record.lineno` |
| `exception` | `self.formatException(record.exc_info)` |
| `stack` | `self.formatStack(record.stack_info)` |
Including extra fields
The main reason to log JSON is to attach data as fields instead of embedding it in the message text. The extra= argument copies each key onto the record as an attribute. A formatter can then find those keys by comparing the record's attributes with the standard set.
import json
import logging
from datetime import datetime, timezone
# Every attribute a bare LogRecord has, plus two the base Formatter adds.
RESERVED = set(vars(logging.LogRecord("", 0, "", 0, "", (), None)))
RESERVED |= {"message", "asctime"}
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {
"time": datetime.fromtimestamp(
record.created, tz=timezone.utc
).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
for key, value in record.__dict__.items():
if key not in RESERVED:
payload[key] = value
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
if record.stack_info:
payload["stack"] = self.formatStack(record.stack_info)
return json.dumps(payload, default=str, ensure_ascii=False)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Order placed", extra={"order_id": 1042, "total": 19.99})
try:
int("not a number")
except ValueError:
logger.exception("Bad input", extra={"field": "quantity"})The first call prints a line like this:
{"time": "2026-11-26T11:34:01.602000+00:00", "level": "INFO", "logger": "myapp", "message": "Order placed", "order_id": 1042, "total": 19.99}The second call prints a line with "level": "ERROR", a "field": "quantity" entry, and an "exception" string that contains the traceback.
Building RESERVED from a real LogRecord keeps the list correct across Python versions. For example, Python 3.12 added taskName. A hard-coded list would drift.
This formatter also picks up attributes added by a filter, such as the request_id filter from the filters chapter. The formatter does not care whether a field arrived through extra= or a filter.
Edge cases that break JSON output
Values that are not serializable
json.dumps raises TypeError for objects such as datetime, Decimal, set, or arbitrary class instances. An exception inside a formatter is caught by the handler's handleError. By default that prints a traceback to stderr and drops the record. Passing default=str makes unknown types fall back to their string form. That is a good default for logs, where losing a record is worse than an imprecise value.
Non-ASCII text
json.dumps escapes non-ASCII characters as \uXXXX by default. ensure_ascii=False keeps them readable. If you set it, make sure the destination encodes as UTF-8. For a file handler, pass encoding="utf-8".
Multi-line messages
JSON escapes newlines inside strings, so a message or traceback with line breaks still produces exactly one line. This is the reason line-oriented collectors work well with JSON logs.
Failures inside `format`
If your formatter raises an exception, the record is lost. Keep format simple. Do not call code that can fail or block, such as a database lookup or a network call.
Large or sensitive values
Do not dump whole request bodies into extra fields. Records can become huge, and secrets such as tokens and passwords end up in log storage. Decide which fields are allowed and leave out the rest.
Using the formatter with dictConfig
In dictConfig, the "()" key names a factory for the formatter. It can be an import path string or the class itself.
import logging
import logging.config
# JsonFormatter defined as in the previous section
config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"json": {"()": JsonFormatter}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "json",
"level": "INFO",
}
},
"root": {"level": "INFO", "handlers": ["console"]},
}
logging.config.dictConfig(config)
logging.getLogger("myapp").info("Ready", extra={"port": 8080})In a real project, put JsonFormatter in a module and give the dotted path as a string, for example "()": "myapp.logfmt.JsonFormatter". Any other keys you add beside "()" are passed to the factory as keyword arguments, so you can make field names configurable.
When not to write your own
A 20-line formatter covers most needs. Libraries such as python-json-logger and structlog add features like renaming fields, processor chains, and context binding. Write your own when you need a small, dependency-free formatter whose output you fully control. Use a library when you need those extras, but check that it handles extra= and exceptions in the way your pipeline expects.
Exercise
A teammate's JSON formatter calls json.dumps(payload) and reads record.msg for the message. A call logger.info("Took %d ms", 87, extra={"started": datetime.now()}) produces a missing record and a traceback on stderr, and the one record that does appear shows "message": "Took %d ms". Name the two bugs and the fix for each.
Show answer
First, record.msg is the unformatted template, so the formatter should use record.getMessage(), which applies the %d argument. Second, datetime is not JSON serializable, so json.dumps raises TypeError inside format. The handler reports the error on stderr and drops the record. Pass default=str to json.dumps, or convert the value with .isoformat() before logging it.
Exercise
Why does a traceback stored in an "exception" field not break a tool that reads one JSON object per line?
Show answer
json.dumps escapes the newlines in the traceback string as \n. The whole record therefore stays on a single physical line, and the reader recovers the original line breaks when it parses the JSON.