How do you produce structured (JSON) logs for a container?
IntermediateConceptExceptions, context managers, files & logging
Answer
Write one JSON object per line to stdout so Fluent Bit, CloudWatch or Loki can parse fields without regex. Use a library like python-json-logger or structlog, or a small formatter:
class JsonFormatter(logging.Formatter):
def format(self, r):
return json.dumps({"ts": self.formatTime(r), "level": r.levelname,
"logger": r.name, "msg": r.getMessage(),
**getattr(r, "ctx", {})})
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level="INFO", handlers=[handler])
log.info("snapshot deleted", extra={"ctx": {"snapshot_id": sid, "region": region}})
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?Beginner