The Analogy: The Building Security Control Room
In the control room of a large building, one wall is a grid of CCTV monitors, a clerk keeps a bound incident logbook, and a small panel of buttons escalates a genuine emergency straight to the fire brigade. The cameras run continuously, recording far more than anyone will ever watch. The logbook is different: the clerk writes deliberate, dated entries -- "22:14, loading bay, delivery signed for by the night manager" -- each stamped with a time and a place so a later reader can reconstruct exactly what happened and where. The escalation panel is reserved for the rare event a human must act on right now. The camera feeds are your raw logs; the dated logbook entries are structured log records with context; the escalation panel is error tracking that pages a person.
The three tools are deliberately separate because they answer different questions. The cameras answer "what was happening everywhere, in general"; the logbook answers "what notable events occurred, in order, with enough detail to investigate"; the panel answers "what needs a human this instant." A control room that treated every camera frame as an incident would call the brigade over a cat in the car park; one that wrote nothing down would have footage but no searchable account of the night. Good observability is the same triad: high-volume telemetry you can sample, structured event records you can search and correlate, and a narrow, loud channel for the things that must wake someone.
What makes the logbook useful months later is that every entry carries the same anchors -- when, where, and what -- so an investigator can pull every line touching "loading bay" between two times and read the sequence as a story. A stack of notes that said only "something happened" would be worthless. The digital equivalent is attaching structured context to every log line: a timestamp, the component, and above all a correlation id that ties together every line produced while handling one request, so you can follow a single request through dozens of interleaved entries from other requests.
The failure that makes a control room useless is recording everything at one flat importance and keeping none of it long. The tapes overwrite every twenty-four hours and the clerk logs each uneventful patrol in the same ink as a break-in, so when a theft is discovered a week later the footage has rolled off and the one entry that mattered is buried among ten thousand identical "all quiet" lines with nothing to distinguish it. Nobody watched the wall, and the alarm panel was never wired to anything. The building had mountains of records and no way to find, rank, or act on the one event that counted -- which is exactly what a system logs when every line is INFO, nothing is retained or aggregated, and no error ever escalates.
Syntax or Core Structure
Python's standard logging module gives you everything the analogy describes: named loggers (which clerk is writing), levels (how important the entry is), handlers (where the ink goes), and formatters (the shape of each line). You almost never call print in a real service. You get a logger by name, set a threshold level, attach a handler with a formatter, and log at the level that matches the event. Anything below the logger's level is discarded before it is ever formatted -- the cheap, deliberate filtering that keeps the logbook readable.
The five standard levels, from least to most severe, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. Setting the level to INFO means "write down INFO and everything more serious; throw away DEBUG." Here we send output to an in-memory StringIO buffer instead of the screen so the result is deterministic and testable, but a real app would use a StreamHandler to stdout or a file.
import logging, io
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
log = logging.getLogger("shop")
log.handlers = [handler]
log.propagate = False # do not also bubble up to the root logger
log.setLevel(logging.INFO) # DEBUG is below this and is dropped
log.debug("cache warm start") # dropped: below the threshold
log.info("order received")
log.warning("stock low")
log.error("payment declined")
print(stream.getvalue(), end="")
Output:
INFO shop: order received
WARNING shop: stock low
ERROR shop: payment declined
The debug line produced nothing: it sat below the logger's INFO threshold and was dropped before formatting. The other three came through in order, each tagged with its level and the logger's name. Setting propagate = False stops these records from also travelling up to the root logger, which would otherwise print a duplicate line -- the single most common cause of "why is every log entry appearing twice?"
Technical Depth: Levels, Context, and Escalation
Choosing the right level
Levels are not decoration; they are the routing decision. A handler or an external aggregator filters on level, so the level you pick decides whether an event is retained, searched, or turned into a 3 a.m. page. The discipline is to reserve the loud levels for things a human should actually act on, and to keep routine traffic at INFO or below so the signal is not drowned.
| Level | Numeric value | When to use it | Should it reach alerting? |
|---|---|---|---|
| DEBUG | 10 | Detailed diagnostics; variable dumps; off in production | No |
| INFO | 20 | Routine expected events: request served, job finished | No |
| WARNING | 30 | Unexpected but handled: retry, slow query, deprecated route | Sometimes (trend) |
| ERROR | 40 | A request or job failed and needs attention | Yes |
| CRITICAL | 50 | The process cannot continue: dependency down, data at risk | Yes, page now |
The rule of thumb: if a healthy production system emits a given line thousands of times an hour, it is INFO or DEBUG. If a line means someone's afternoon is about to change, it is ERROR or CRITICAL. WARNING is for the middle ground you watch as a rate, not per-occurrence.
Structured logs and the correlation id
A flat message string is hard to search. The fix is to attach structured fields to each record and let the formatter render them. The most valuable field is a correlation id (also called a request id): a short token assigned once per incoming request and stamped onto every line that request produces, so you can filter a noisy log down to the story of one request. You pass extra fields through the extra= argument, and reference them by name in the format string.
import logging, io
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s req=%(request_id)s %(message)s"))
log = logging.getLogger("api")
log.handlers = [handler]
log.propagate = False
log.setLevel(logging.INFO)
log.info("login ok", extra={"request_id": "r-100"})
log.warning("slow query", extra={"request_id": "r-100"})
log.info("login ok", extra={"request_id": "r-205"})
print(stream.getvalue(), end="")
Output:
INFO req=r-100 login ok
WARNING req=r-100 slow query
INFO req=r-205 login ok
The two r-100 lines are the same request's story; the r-205 line belongs to a different request that happened to interleave. In a real Flask app you would assign the id in a before_request hook and read it back everywhere, rather than passing extra by hand -- the Real World example below does exactly that.
Logging exceptions without leaking a traceback
When you catch an exception, you want the failure recorded at ERROR with enough detail to debug, but you rarely want the raw multi-line traceback printed into a shared log where it becomes noise or, worse, leaks file paths and internal structure. logger.exception(...) logs at ERROR and attaches the active exception's information to the record; logger.error("...", exc_info=True) does the same at a level you choose. What you do with that attached information is up to your handler -- you can render a full traceback in development and record only the exception type in a shared stream.
import logging
captured = []
class Capture(logging.Handler):
def emit(self, record):
exc = record.exc_info[0].__name__ if record.exc_info else None
captured.append((record.levelname, record.getMessage(), exc))
log = logging.getLogger("worker")
log.handlers = [Capture()]
log.propagate = False
log.setLevel(logging.INFO)
try:
1 / 0
except ZeroDivisionError:
log.exception("charge failed") # logs at ERROR, exception attached
log.info("moving on")
print(captured)
Output:
[('ERROR', 'charge failed', 'ZeroDivisionError'), ('INFO', 'moving on', None)]
The exception call produced an ERROR record that carried the exception type (ZeroDivisionError) without us formatting a single line of traceback text into the message. The later info call has no exception attached, so its third field is None. This separation -- the message is human-readable, the exception rides along as structured data -- is what lets an aggregator group all ZeroDivisionError failures together while keeping the log stream clean.
Configuration and error tracking (illustrative)
Real apps configure logging once, at startup, rather than per module. logging.config.dictConfig takes a single dictionary describing formatters, handlers, and levels, so the whole policy lives in one place (and can differ between environments). The snippet below is illustrative -- it configures the root logger to write structured lines to stdout, which a platform like Docker or systemd then captures.
# logging_config.py -- configure logging once at startup (illustrative)
from logging.config import dictConfig
dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
},
"handlers": {
"stdout": {"class": "logging.StreamHandler", "formatter": "default"},
},
"root": {"level": "INFO", "handlers": ["stdout"]},
})
Logs answer "what happened," but they do not page anyone. Error tracking does: a service such as Sentry captures unhandled exceptions, groups identical failures into one issue, attaches the request context, and notifies a human. You initialise it once and it hooks into Flask automatically. The snippet below is illustrative and needs the sentry-sdk package and a real DSN to run.
# app.py -- Sentry error tracking (illustrative; needs sentry-sdk and a DSN)
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
integrations=[FlaskIntegration()],
traces_sample_rate=0.1,
)
# unhandled exceptions in any view are now captured, grouped, and alerted on
With logs for the searchable account and error tracking for the loud escalation channel, you have the control room's logbook and alarm panel. What remains is wiring them to the request lifecycle correctly -- which is where most teams get the level wrong.
Real World Example: A Request Access Log With Correlation Ids
A production Flask app wants one access-log line per request, each tagged with a correlation id so a support ticket can be traced to the exact request that produced it. We assign the id in a before_request hook and record the outcome in an after_request hook, which runs on the way out for the responses the app returns. To keep the demo deterministic we use an integer counter for the id and an in-memory buffer for the log stream.
import logging, io
from flask import Flask, g, request, jsonify
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s rid=%(rid)s %(message)s"))
access = logging.getLogger("access")
access.handlers = [handler]
access.propagate = False
access.setLevel(logging.INFO)
app = Flask(__name__)
_counter = {"n": 0}
@app.before_request
def assign_rid():
_counter["n"] += 1
g.rid = "r-" + str(_counter["n"])
@app.after_request
def log_access(resp):
access.info(request.method + " " + request.path + " -> " + str(resp.status_code),
extra={"rid": g.rid}) # logged at INFO no matter the status
return resp
@app.errorhandler(RuntimeError)
def on_error(e):
return jsonify(error="internal"), 500
@app.get("/ok")
def ok():
return jsonify(ok=True)
@app.get("/boom")
def boom():
raise RuntimeError("db down")
client = app.test_client()
client.get("/ok")
client.get("/boom") # 500, but after_request still logs INFO
for line in stream.getvalue().splitlines():
print(line)
Output:
INFO rid=r-1 GET /ok -> 200
INFO rid=r-2 GET /boom -> 500
Both requests produced exactly one access line, each carrying its own correlation id -- r-1 for the successful call, r-2 for the one that raised. The before_request hook stamps the id onto g; the after_request hook fires on the way out and records the method, path, and status. If a user reports "my request failed at 14:03," support can pull that request's id and read every line it produced as one story.
Assigning the id in one central place and reading it back through g means every log line in the request -- not just this access line -- can carry the same rid without threading it through every function call. A view that separately logged "validation failed" would show the same rid=r-2, so the access line and the detail lines align. This is the single most useful habit in production logging: one id per request, stamped everywhere.
The RuntimeError handler is not optional scaffolding here: it is what makes the 500 appear in the log at all. It converts the exception into an ordinary 500 response, and only because a response was produced does after_request run and record the line. Remove the handler and the boom request would raise straight out, after_request would be skipped, and the failure would leave no access-log line whatsoever -- a silent gap even before we consider severity.
The design flaw is the level. Look again at after_request: every response is logged at INFO, whatever the status. The 500 -- a real failure a human should see -- is written as INFO rid=r-2 GET /boom -> 500, indistinguishable to any level-based filter from the thousands of healthy 200s beside it. An alert keyed on ERROR never fires, and the traceback from the original RuntimeError was swallowed by the handler and never logged. The fix is to derive the level from the status code -- ERROR (with exc_info=True) for 5xx, WARNING for 4xx, INFO otherwise -- and to call logger.exception inside the error handler so the failure both escalates and keeps its traceback. As written, the control room films the break-in and files the tape under "all quiet."
Common Mistakes
- Logging everything at INFO. When routine 200s and genuine 500s share a level, no filter or alert can tell an expected event from a failure. Severity is the entire purpose of levels; assign it honestly per event.
- Using
printinstead of a logger.printhas no level, no timestamp, no handler routing, and cannot be silenced or redirected per module. Reach forloggingfrom the first line of a service, not as a later cleanup.
- Leaving
propagateon after adding your own handler. A record handled locally also bubbles up to the root logger, producing a duplicate line for every event. Setpropagate = Falseon loggers you configure directly.
- Adding handlers at import time or on every request. Re-running handler setup attaches a second and third handler to the same logger, multiplying every line. Configure logging once, at startup, with
dictConfig.
- Logging secrets or personal data. Passwords, tokens, full card numbers, and message bodies do not belong in a stream that many people and systems can read. Redact at the point of logging, never "later."
- Swallowing exceptions with a bare
except.except: pass, or catching and returning without logging, turns a failure into silence -- and the hardest bug to find is the one that left no trace. Log it, then decide whether to re-raise.
- Building the message even when it will be dropped.
log.debug("state=" + expensive())runsexpensive()regardless of level. Pass arguments for lazy formatting (log.debug("state=%s", value)) so the work happens only if the line is actually emitted.
- Shipping without a correlation id. With no per-request token, concurrent requests interleave into an unreadable stream and you cannot reconstruct one request's path. Assign an id in
before_requestand stamp it on every line.
- Treating error tracking as optional. Logs are searched after you already suspect a problem; error tracking is what tells you there is one. Rich logs with no alerting still depend on a human noticing -- the control room with no alarm panel.
Best Practices
- Configure logging once, at startup, with
dictConfig. One dictionary holds formatters, handlers, and levels and can differ per environment; every module then simply callsgetLogger(__name__).
- Log structured fields, not just prose. A correlation id, the component, and the outcome as separate fields let an aggregator search and group records; one opaque string cannot be queried.
- Derive severity from outcome. Map 5xx to
ERROR, 4xx toWARNING, and the rest toINFO, so an alert that keys on level actually distinguishes a failure from routine traffic.
- Log exceptions with
logger.exceptionorexc_info=True. Attach the traceback as structured data where you catch the error, rather than re-raising blindly or pasting the traceback into the message text.
- Send logs to stdout in production and let the platform capture them. Containers and process managers already collect, rotate, and ship stdout; hand-rolling log files fights the environment you deploy into.
- Sample high-volume telemetry, but never sample errors. Keep a fraction of chatty
INFO/DEBUGtraffic to control cost, and retain everyERROR-- the rare event is the one you must not drop.
- Wire an error tracker for escalation. Let a service like Sentry group identical failures, attach request context, and page a human, so noticing a break does not depend on someone watching the log wall.
- Set retention deliberately. Decide how long each stream stays searchable; evidence that rolls off before anyone looks is no better than no evidence -- the lesson the control room learns too late.
Practice Exercises
- Take the Real World access logger and fix its flaw: change
after_requestso the line is logged atERRORfor a status code >= 500,WARNINGfor >= 400, andINFOotherwise. Capture the stream and verify that/boomnow emits anERRORline while/okstaysINFO.
- Add
logger.exception("unhandled")inside theRuntimeErrorhandler and confirm, using theCapturehandler pattern from the tech-depth section, that the captured record's level isERRORand it carriesRuntimeErroras its exception type -- without any raw traceback appearing in the message.
- Write a
dictConfigthat defines two loggers,accessatINFOandsecurityatWARNING, both writing to one stdout handler whose format includes%(name)s. Emit a line from each and show that asecurity.info(...)call is dropped whilesecurity.warning(...)is kept.
- Simulate a correlation id across two requests: assign
ridfrom an integer counter, log three lines for the first request and two for the second, then filter the captured output down to just the firstrid-- proving you can reconstruct one request's story from an interleaved stream.