Content · Programming · Python

Python Structured Logging with JSON

Structured JSON logs put fields such as event, request ID and severity in predictable keys.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Structured JSON logs put fields such as event, request ID and severity in predictable keys.

Understanding the Concept


Structured JSON logs put fields such as event, request ID and severity in predictable keys. Machines can filter records reliably, unlike parsing a free-form sentence.

A JSON log line is a serialization format, not automatically a secure or validated audit record.

How this helps diagnose real applications


First decide what question you are trying to answer: whether a particular branch runs, why an operation failed, or what contextual event should be recorded. Logging, interactive debugging, traceback inspection and controlled timing complement each other but produce different kinds of evidence.

Diagnostic output should preserve enough context to reproduce the problem without recording passwords, tokens, full personal records or untrusted payloads. Keep instrumentation focused so it does not hide the original behavior.

Worked Example


Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.

import json
import logging
class JSONFormatter(logging.Formatter):
    def format(self, record):
        return json.dumps({"level": record.levelname, "message": record.getMessage(), "logger": record.name})
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logger = logging.getLogger("json-demo")
logger.addHandler(handler)
logger.warning("Queue reached capacity")
logger.removeHandler(handler)

Walkthrough: What Each Part Does


  • The imports make json, logging available. These are standard-library building blocks unless the example explicitly names an external tool.
  • The definition JSONFormatter creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
  • Observe which message or diagnostic field appears and which condition caused it. Modify the input deliberately to test the failure path.

This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.

The example completed in the local test environment. Its output is not fixed enough to publish as a universal expected result; inspect the result on your own computer.

Important Behavior and Edge Cases


Logging raw credentials, authorization headers or personal data just because JSON makes them easy to query.

A JSON log line is a serialization format, not automatically a secure or validated audit record.

Practice Exercise


Add a safe request identifier field; check that the output is valid JSON.

Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.

Further reading: official documentation and API reference.

Common Beginner Mistakes


  • Logging raw credentials, authorization headers or personal data just because JSON makes them easy to query.
  • Removing the diagnostic message after seeing it once instead of reproducing the failure and checking the underlying cause.

Key Takeaways


  • Structured JSON logs put fields such as event, request ID and severity in predictable keys.
  • A JSON log line is a serialization format, not automatically a secure or validated audit record.
  • Practice: Add a safe request identifier field; check that the output is valid JSON.
Share this resourceSend this page to someone who may find it useful.