Part 02 / Topic 3 of 6
Logging
When your tool runs at 2am in the customer's scheduler, its logs are the only interview you get. Two rules shape everything:
Log in a structure their platform can search. Enterprise log systems (Splunk, Datadog, CloudWatch) filter and aggregate by field. One JSON object per line beats free text:
# examples/02_structured_json_logs_that_a_customer.py
import json, logging, sys
class JsonFormatter(logging.Formatter):
def format(self, record):
entry = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}
entry.update(getattr(record, "fields", {}))
return json.dumps(entry)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("acme-sync")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("page fetched", extra={"fields": {"page": 2, "records": 3, "duration_ms": 182}})
log.warning("rate limited", extra={"fields": {"retry_after_s": 0, "attempt": 1}})
# {"level": "INFO", "logger": "acme-sync", "msg": "page fetched", "page": 2, "records": 3, "duration_ms": 182}
# {"level": "WARNING", "logger": "acme-sync", "msg": "rate limited", "retry_after_s": 0, "attempt": 1}
Now "all warnings with attempt > 1" is a query, not an afternoon of grep.
Know what never to log. Tokens, passwords, and personal data (names, emails, addresses) do not belong in logs — logs are copied, shipped to third-party platforms, and kept for years. Part 12 builds the redaction tooling; the habit starts here.
Use levels with intent: INFO for the normal heartbeat of a run, WARNING for handled trouble (a retry, a quarantined row), ERROR for failures a human must look at.
🧪 Quick quiz
- Why log in JSON instead of free text in a customer deployment?
Show the answer
Log platforms can filter and aggregate by field — e.g. all warnings with attempt > 1. The example emits one JSON object per line with fields such as page, records and duration_ms. (verified against the example output above)
Done here? The practice set for Part 2 — 4 exercises with solutions — is on the part page.