Structured Logging
Emit JSON-formatted logs for machine-readable output.
Structured Logging is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Structured Logging?
Structured logging emits log records as machine-readable data (JSON) instead of free-form text, making them easy to index, search, and alert on.
import logging, json
def log_json(level, msg, **kw):
record = {"level": level, "msg": msg, **kw}
print(json.dumps(record))
log_json("INFO", "Request received", path="/api/users", method="GET")Custom JSON Formatter
Subclass logging.Formatter to emit JSON instead of plain text.
import logging, json
class JSONFormatter(logging.Formatter):
def format(self, record):
return json.dumps({
"time": self.formatTime(record),
"level": record.levelname,
"name": record.name,
"msg": record.getMessage(),
})
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logging.getLogger().addHandler(handler)python-json-logger
The python-json-logger package provides a ready-made JSON formatter with standard and extra fields.
# pip install python-json-logger
import logging
from pythonjsonlogger import jsonlogger
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setFormatter(jsonlogger.JsonFormatter())
logger.addHandler(handler)
logger.info("User created", extra={"user_id": 42})structlog
structlog is a popular third-party library that separates context accumulation from formatting and supports processors pipelines.
# pip install structlog
import structlog
log = structlog.get_logger()
log = log.bind(request_id="abc123")
log.info("payment_processed", amount=49.99, currency="USD")Binding Context with structlog
structlog lets you bind key-value pairs to a logger that carry through all subsequent calls.
import structlog
log = structlog.get_logger().bind(
service="auth",
env="prod"
)
log.warning("login_failed", user="alice", reason="bad_password")
# {service:auth, env:prod, user:alice, reason:bad_password}Adding Timestamps and Caller Info
Processors can enrich records automatically. Add TimeStamper and CallsiteParameterAdder to every log record.
import structlog
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.CallsiteParameterAdder([structlog.processors.CallsiteParameter.FILENAME]),
structlog.processors.JSONRenderer(),
]
)Logging Request IDs in Web Apps
In a web framework, bind a request ID at the start of each request so every log line during that request includes it.
import structlog
def middleware(request, call_next):
req_id = request.headers.get("X-Request-Id", generate_id())
log = structlog.get_logger().bind(request_id=req_id)
log.info("request_started", path=request.url.path)
response = call_next(request)
log.info("request_finished", status=response.status_code)
return responseECS Log Format
Elastic Common Schema (ECS) is a standard JSON log format used by the Elastic Stack. Use ecs-logging for Python.
# pip install ecs-logging
import logging
import ecs_logging
logger = logging.getLogger("app")
handler = logging.StreamHandler()
handler.setFormatter(ecs_logging.StdlibFormatter())
logger.addHandler(handler)
logger.info("Event logged in ECS format")Log Aggregation Systems
Structured JSON logs flow naturally into aggregation tools: Elasticsearch/Kibana (ELK), Grafana Loki, Datadog, AWS CloudWatch Logs Insights.
# Loki query example:
# {app="myservice"} | json | level="ERROR"
# CloudWatch Insights:
# fields @timestamp, level, msg
# | filter level = "ERROR"
# | sort @timestamp descAvoiding PII in Logs
Scrub personally identifiable information before logging. Use a custom processor or filter to mask emails, tokens, and passwords.
import re
def mask_pii(_, __, event_dict):
msg = event_dict.get("event", "")
event_dict["event"] = re.sub(
r"[\w.+-]+@[\w-]+\.[\w.]+", "***@***.***", msg
)
return event_dictStructured vs Unstructured Trade-offs
Structured logs are searchable and alertable but verbose. Combine structured logging in production with human-readable formatting in development using environment-based configuration.
import structlog, os
if os.getenv("ENV") == "production":
renderer = structlog.processors.JSONRenderer()
else:
renderer = structlog.dev.ConsoleRenderer()
structlog.configure(processors=[renderer])Quick Check
What is the main advantage of JSON-structured logs over plain-text logs?
Recap
Structured logging emits key-value JSON records. Use a JSONFormatter, python-json-logger, or structlog. Bind context (request ID, user) at the start of an operation so every log line during that operation carries the context.
Frequently asked questions
Is the “Structured Logging” lesson free?
Yes — the full text of “Structured Logging” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Structured Logging”?
Emit JSON-formatted logs for machine-readable output. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Structured Logging” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.