Predict the output
What line does the logger print?
import json
import logging
import sys
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
doc = {"level": record.levelname, "msg": record.getMessage()}
doc.update(getattr(record, "ctx", {}))
return json.dumps(doc, sort_keys=True)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("orders")
log.addHandler(handler)
log.setLevel(logging.INFO)
ctx = {"order_id": 42, "request_id": "r-9"}
log.info("payment captured", extra={"ctx": ctx})Hint 1 of 1
Which formatter is attached?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A {"level": "INFO", "msg": "payment captured", "order_id": 42, "request_id": "r-9"}
Correct. The formatter merges the context into one JSON object with sorted keys.
The custom formatter builds one dict from the level, message and the ctx passed via extra, and json.dumps with sort_keys writes the keys alphabetically. One JSON object per line is easy for log tools to query.
Why not the others?
- B
INFO:orders:payment captured. That's the default text format; this handler uses JsonFormatter. - C
{"msg": "payment captured"}. Level and context are added too. - D Nothing. The logger level is INFO, so info lines go out.