Concept Explanation
print() is fine until the code is running on a server you cannot see. Then you need logging: levels so you can filter, structure so you can search, and context so you can follow one request through a system.
print() vs logging
print() | logging | |
|---|---|---|
| Severity levels | No | Yes, filterable |
| Destination | stdout only | Files, syslog, stderr, HTTP, anything |
| Timestamps, module, line | Manual | Automatic |
| Enable/disable per module | No | Yes |
| Structured output | Manual | Via a formatter |
The Five Levels
logger.debug("cache key computed: %s", key) # development detail
logger.info("order created", extra={"id": 42}) # normal, notable events
logger.warning("retrying after timeout") # recoverable, worth noticing
logger.error("payment failed", exc_info=True) # this request failed
logger.critical("database unreachable") # the service is down
The discipline: INFO is for things you would want in a timeline of what happened. ERROR means a user was affected. If everything is INFO, the level carries no information.
One Logger Per Module
import logging
logger = logging.getLogger(__name__) # always __name__, never the root
__name__ gives you a hierarchy — myapp.api.orders is a child of myapp.api — so you can raise the level for one noisy subsystem without touching the rest. Configure handlers once, in your entry point; libraries should only ever get a logger and log to it.
Lazy Formatting
logger.debug("processing %s items for %s", count, user) # correct
logger.debug(f"processing {count} items for {user}") # formats even when disabled
With %s placeholders, the string is only built if the message will actually be emitted. With an f-string it is built every time, including the millions of debug calls you have switched off.
Structured Logging
A human reads "Order 42 failed for user 7". A log aggregator cannot search it. Emit JSON instead:
{"level": "error", "event": "order_failed", "order_id": 42, "user_id": 7, "request_id": "a3f9"}
Now order_id:42 is a query. This is the single biggest upgrade to debugging a distributed system, and structlog or a JSON formatter gets you there in about ten lines.
Correlation IDs
One user action touches several services. Without a shared id, their log lines are unrelated. Generate a request_id at the edge, put it in a ContextVar, attach it to every log record, and pass it downstream as a header. Then one query returns the whole story.
ContextVar rather than a global or thread-local: it works correctly with asyncio, where many requests share one thread.
The Three Pillars
| Pillar | Question it answers | Tool |
|---|---|---|
| Logs | What happened, in detail? | structlog, CloudWatch, Loki |
| Metrics | How much, how often, how fast? | Prometheus, StatsD |
| Traces | Where did the time go across services? | OpenTelemetry, Jaeger |
Metrics are cheap and aggregate — count every request. Logs are expensive per event but detailed. Traces show you which of six services caused the slow request.
The Four Metrics Worth Having First
Rate, errors, duration, and saturation. Requests per second, error percentage, p95 latency, and how full your resources are. Those four catch most incidents.
Track percentiles, not averages. A 200 ms mean hides that 5% of users wait four seconds.
Never Log Secrets or PII
Passwords, tokens, card numbers, full addresses. Logs get shipped to third parties, retained for years, and read by people with no need to know. Redact at the formatter so it cannot be forgotten at a call site.
Code Example #1 (Basic)
Levels, per-module loggers, and the mistakes that make logs useless.
import logging
import sys
# Configure ONCE, in the entry point. Libraries never call basicConfig.
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s:%(lineno)d - %(message)s",
datefmt="%H:%M:%S",
stream=sys.stdout,
)
logger = logging.getLogger(__name__)
def process_order(order_id: int, amount: float) -> bool:
logger.debug("validating order %s", order_id) # filtered out at INFO
if amount <= 0:
logger.warning("rejecting order %s: amount %.2f is not positive",
order_id, amount)
return False
logger.info("order %s accepted for %.2f", order_id, amount)
return True
print("=== Levels in action ===")
process_order(101, 49.99)
process_order(102, -5.00)
# --- Exceptions: log the traceback, do not swallow it ---
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
# exc_info=True attaches the full traceback
logger.error("division failed for %s/%s", a, b, exc_info=True)
return None
print("\n=== Exception logging ===")
divide(10, 0)
# --- logger.exception() is shorthand inside an except block ---
def load_config(path):
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
logger.exception("config file missing: %s", path) # implies exc_info=True
return None
print("\n=== logger.exception ===")
load_config("/nonexistent/config.toml")
# --- The hierarchy: quiet one noisy subsystem, keep the rest ---
print("\n=== Per-module levels ===")
noisy = logging.getLogger("myapp.thirdparty.pollers")
app = logging.getLogger("myapp.api")
noisy.setLevel(logging.ERROR) # only errors from this subtree
noisy.info("polling tick") # suppressed
noisy.error("poller crashed") # shown
app.info("handling GET /orders") # shown -- unaffected
# --- Lazy formatting matters ---
print("\n=== Lazy vs eager formatting ===")
logger.setLevel(logging.INFO)
expensive_calls = 0
def expensive_repr():
global expensive_calls
expensive_calls += 1
return "a-costly-string"
logger.debug("eager: %s", f"value={expensive_repr()}") # f-string ran anyway
before = expensive_calls
logger.debug("lazy: %s", expensive_repr) # not called at DEBUG-off
print(f" eager f-string called the helper: {before} time(s)")
print(f" passing the callable did not: still {expensive_calls}")
print(" Use %s placeholders so disabled log calls cost nothing.")
Note the difference between logger.error(..., exc_info=True) and logger.exception(...) — the second is the idiomatic form inside an except block, and both give you the traceback that a bare logger.error("failed") throws away.
Code Example #2 (Intermediate)
Structured JSON logs, correlation ids across async requests, redaction, and metrics.
import asyncio
import json
import logging
import random
import sys
import time
import uuid
from collections import defaultdict
from contextvars import ContextVar
# ==================== Correlation id, async-safe ====================
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")
user_id_var: ContextVar[str] = ContextVar("user_id", default="-")
class ContextFilter(logging.Filter):
"""Attach the current request's context to every record."""
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = request_id_var.get()
record.user_id = user_id_var.get()
return True
# ==================== JSON formatter with redaction ====================
SENSITIVE_KEYS = {"password", "token", "secret", "api_key", "card_number",
"authorization", "ssn"}
def redact(value):
"""Recursively mask anything that looks sensitive."""
if isinstance(value, dict):
return {k: ("***" if k.lower() in SENSITIVE_KEYS else redact(v))
for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [redact(v) for v in value]
return value
RESERVED = set(vars(logging.LogRecord("", 0, "", 0, "", (), None)).keys()) | {
"message", "asctime", "taskName"}
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname.lower(),
"logger": record.name,
"event": record.getMessage(),
"request_id": getattr(record, "request_id", "-"),
"user_id": getattr(record, "user_id", "-"),
}
# Anything passed via extra={...} becomes a searchable field
for key, value in record.__dict__.items():
if key not in RESERVED and key not in payload:
payload[key] = value
if record.exc_info:
payload["error"] = self.formatException(record.exc_info).splitlines()[-1]
return json.dumps(redact(payload))
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
handler.addFilter(ContextFilter())
root = logging.getLogger("shop")
root.handlers.clear()
root.addHandler(handler)
root.setLevel(logging.INFO)
root.propagate = False
logger = logging.getLogger("shop.orders")
# ==================== A tiny metrics registry ====================
class Metrics:
"""The four that matter: rate, errors, duration, saturation."""
def __init__(self):
self.counters = defaultdict(int)
self.durations = defaultdict(list)
def increment(self, name: str, **labels):
self.counters[self._key(name, labels)] += 1
def observe(self, name: str, seconds: float, **labels):
self.durations[self._key(name, labels)].append(seconds)
@staticmethod
def _key(name, labels):
return name + ("{" + ",".join(f"{k}={v}" for k, v in sorted(labels.items())) + "}"
if labels else "")
def percentile(self, name: str, p: float, **labels) -> float:
values = sorted(self.durations.get(self._key(name, labels), []))
if not values:
return 0.0
idx = min(int(len(values) * p), len(values) - 1)
return values[idx]
def report(self):
print("\n=== Metrics ===")
for key, count in sorted(self.counters.items()):
print(f" {key:<44} {count:>5}")
for key in sorted(self.durations):
values = sorted(self.durations[key])
mean = sum(values) / len(values)
p50 = values[len(values) // 2]
p95 = values[min(int(len(values) * 0.95), len(values) - 1)]
print(f" {key:<44} n={len(values):<4} "
f"mean={mean * 1000:>6.1f}ms p50={p50 * 1000:>6.1f}ms "
f"p95={p95 * 1000:>6.1f}ms")
print(" Note how p95 exceeds the mean -- averages hide the slow tail.")
metrics = Metrics()
# ==================== A request, instrumented ====================
async def charge_card(order_id: int, card_number: str, amount: float) -> dict:
# The card number is passed but never reaches the log in the clear
logger.info("charging card", extra={
"order_id": order_id, "amount": amount, "card_number": card_number,
})
await asyncio.sleep(random.uniform(0.01, 0.08))
if random.random() < 0.2:
raise RuntimeError("gateway declined")
return {"status": "captured", "amount": amount}
async def handle_request(order_id: int) -> str:
# One id per request, propagated automatically to every log line
token_r = request_id_var.set(uuid.uuid4().hex[:8])
token_u = user_id_var.set(f"user-{order_id % 5}")
started = time.perf_counter()
metrics.increment("http_requests_total", route="/checkout")
try:
logger.info("checkout started", extra={"order_id": order_id})
result = await charge_card(order_id, card_number="4111111111111111",
amount=round(random.uniform(10, 300), 2))
logger.info("checkout complete", extra={
"order_id": order_id, "status": result["status"],
})
return "ok"
except RuntimeError:
metrics.increment("http_errors_total", route="/checkout")
logger.error("checkout failed", extra={"order_id": order_id}, exc_info=True)
return "error"
finally:
elapsed = time.perf_counter() - started
metrics.observe("http_request_duration_seconds", elapsed, route="/checkout")
request_id_var.reset(token_r)
user_id_var.reset(token_u)
async def main():
random.seed(11)
print("=== Structured logs (one JSON object per line) ===")
results = await asyncio.gather(*[handle_request(i) for i in range(6)])
print(f"\n {results.count('ok')} succeeded, {results.count('error')} failed")
print(" Every line carries request_id and user_id, so grepping one id")
print(" reconstructs a single request even though six ran concurrently.")
print(" card_number appears as *** -- redaction happens in the formatter,")
print(" so no call site can forget it.")
metrics.report()
print(f"\n p95 checkout latency: "
f"{metrics.percentile('http_request_duration_seconds', 0.95, route='/checkout') * 1000:.1f} ms")
asyncio.run(main())
Two design choices here are the ones to carry into real code. Redaction lives in the formatter, not at the call sites, so it cannot be forgotten. And the correlation id lives in a ContextVar, which is why six concurrent async requests on one thread each keep their own id — a thread-local would not.
Common Mistakes
- Using
print()in production code: no levels, no timestamps, no way to route or filter it. logging.getLogger()with no name: configures the root logger and floods your output with every library's debug messages.- f-strings in log calls: the message is built even when the level is disabled.
logger.error("failed")insideexcept: throws away the traceback. Uselogger.exceptionorexc_info=True.basicConfigin a library: hijacks the application's logging configuration. Libraries get a logger and nothing else.- Everything at
INFO: the level stops carrying information and nobody can filter. - Logging inside a tight loop: a million lines per second costs money and hides the signal.
- Logging secrets or PII: passwords, tokens, card numbers. Redact in the formatter.
- Unstructured messages:
"Order 42 failed"cannot be queried;{"event": "order_failed", "order_id": 42}can. - No correlation id: with concurrent requests, interleaved log lines are unreadable.
- Thread-locals in async code: many requests share one thread. Use
ContextVar. - Averages instead of percentiles: a healthy mean hides a badly broken p99.
- Swallowing exceptions after logging: log and re-raise unless you have genuinely handled it.
- No log rotation: an unrotated file fills the disk and takes the service down.
Best Practices
logger = logging.getLogger(__name__)at the top of every module, and configure handlers only in the entry point.- Use
%splaceholders, never f-strings, in log calls. logger.exception()insideexceptblocks so you keep the traceback.- Log structured JSON in production — one object per line, with fields you can query.
- Attach a correlation id via
ContextVarand propagate it downstream as a header. - Redact in the formatter, driven by a key list, so no call site can leak a secret.
- Mean levels something:
ERRORfor user-affecting failures,WARNINGfor recoverable oddities,INFOfor the timeline. - Log to stdout in containers and let the platform handle shipping and rotation.
- Track rate, errors, duration, and saturation before adding anything more exotic.
- Report percentiles (p50, p95, p99), not averages.
- Include enough context to act: ids, not just "something went wrong".
- Set up rotation (
RotatingFileHandlerorTimedRotatingFileHandler) when you do write files. - Sample high-volume debug logs rather than disabling them entirely.
- Alert on symptoms users feel — error rate and latency — not on every individual log line.
Practice Exercises
- The Traceback: Write a function that raises inside a
try, and log it three ways:logger.error("failed"),logger.error("failed", exc_info=True), andlogger.exception("failed"). Compare the output and say which you would want at 3am. - The JSON Formatter: Write a
logging.Formattersubclass that emits JSON withts,level,logger,event, and every field passed viaextra=. Add a redaction pass that masks any key containing "password" or "token", and prove a logged password comes out as***. - The Correlation ID: Use a
ContextVarand alogging.Filterto stamp a per-request id onto every record. Run five requests concurrently withasyncio.gather, then show that filtering the output by one id reconstructs exactly that request's lines.