One-Sentence Definition
Logging records runtime events by severity level along with timestamps, module origins, and correlation fields to reconstruct program execution—working alongside metrics and traces to diagnose production failures.
Why It Matters
- There is no interactive debugger attached in production: When a remote server misbehaves, engineers rely on logs, metrics, distributed traces, and process telemetry to reconstruct what happened.
- Why logging beats raw
printstatements: Severity levels can be toggled per environment, timestamps and module names are attached automatically, records can fan out to multiple destinations simultaneously (console, rotating files, log aggregators), and JSON fields can be indexed and queried. - One of the three pillars of observability: Logs, Metrics, and Traces. See OpenTelemetry's overview of observability signals: https://opentelemetry.io/docs/concepts/signals/
Practical Boundaries
Lazy percent-formatting in Python's logger only defers string interpolation: calling logger.debug("x=%s", expensive()) still evaluates expensive() before checking the log level. Guard expensive argument computations with logger.isEnabledFor(logging.DEBUG), and ensure secret redaction covers log messages, extra fields, and exception tracebacks alike.
How It Works / Diagram
Core architecture of Python's standard library logging module:
| Level | Numeric Value | Intended Use |
|---|---|---|
| DEBUG | 10 | Fine-grained diagnostic details (payload byte sizes, intermediate state) |
| INFO | 20 | Normal lifecycle milestones (service startup, model invocation completed) |
| WARNING | 30 | Unexpected condition that does not halt execution (approaching rate limit, falling back to default) |
| ERROR | 40 | A specific operation or request failed |
| CRITICAL | 50 | Fatal failure where the process itself may not be able to continue |
Official Python logging HOWTO and Cookbook: https://docs.python.org/3/howto/logging.html , https://docs.python.org/3/howto/logging-cookbook.html
Runnable Example
Configuring two handlers side by side—a human-readable console handler (`INFO` and above) and a machine-parseable JSON buffer handler (`DEBUG` and above)—demonstrating extra correlation IDs, logger.exception, and API key masking (verified on Python 3.15.0 with a dummy key):
# File: examples/17_logging.py
# Logging: severity levels, structured JSON, contextual fields, and secret masking
import logging, json, io, sys
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}
if hasattr(record, "request_id"):
payload["request_id"] = record.request_id
if record.exc_info:
payload["exc"] = self.formatException(record.exc_info).splitlines()[-1]
return json.dumps(payload, ensure_ascii=False)
logger = logging.getLogger("app.llm")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler(sys.stdout) # For humans: plain text, INFO and above
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)-7s %(name)s: %(message)s"))
buffer = io.StringIO()
machine = logging.StreamHandler(buffer) # For machines: JSON, DEBUG and above
machine.setFormatter(JsonFormatter())
logger.addHandler(console); logger.addHandler(machine)
logger.debug("Request payload size=%d tokens", 1234) # Routed only to JSON buffer
logger.info("Invoking model", extra={"request_id": "req-7"})
logger.warning("Approaching rate limit: %d calls remaining", 3)
try:
1 / 0
except ZeroDivisionError:
logger.exception("Computation failed", extra={"request_id": "req-8"})
print("---- JSON Logs (indexable by ELK / Loki / Datadog) ----")
print(buffer.getvalue().strip())
# Security rule: never log raw API keys
api_key = "sk-abcdef1234567890"
logger.info("Using key=%s", api_key[:5] + "***")
Captured output:
INFO app.llm: Invoking model
WARNING app.llm: Approaching rate limit: 3 calls remaining
ERROR app.llm: Computation failed
Traceback (most recent call last):
File "17_logging.py", line 28, in <module>
1 / 0
~~^~~
ZeroDivisionError: division by zero
---- JSON Logs (indexable by ELK / Loki / Datadog) ----
{"level": "DEBUG", "logger": "app.llm", "msg": "Request payload size=1234 tokens"}
{"level": "INFO", "logger": "app.llm", "msg": "Invoking model", "request_id": "req-7"}
{"level": "WARNING", "logger": "app.llm", "msg": "Approaching rate limit: 3 calls remaining"}
{"level": "ERROR", "logger": "app.llm", "msg": "Computation failed", "request_id": "req-8", "exc": "ZeroDivisionError: division by zero"}
INFO app.llm: Using key=sk-ab***
Key observations:
- The
DEBUGrecord appears in the JSON sink but not on the console—a single log call can be filtered differently per destination handler. logger.exceptionautomatically captures and attaches the active exception traceback.- Attaching
request_idviaextralets you correlate every log line belonging to the same user request across concurrent workers.
Common Pitfalls
- Formatting log messages eagerly with f-strings: Writing
logger.debug(f"x={big()}")evaluatesbig()and builds the string even whenDEBUGis disabled. Prefer lazy percent-formattinglogger.debug("x=%s", x), and guard expensive argument calls withif logger.isEnabledFor(logging.DEBUG):. https://docs.python.org/3/howto/logging.html#optimization - Calling
logging.basicConfig()inside a reusable library: Handler and formatter configuration belongs to the top-level application entry point; libraries should only calllogging.getLogger(__name__). See "Configuring Logging for a Library": https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library - Logging raw API keys, passwords, or unredacted user PII: Log files typically have long retention windows and broad read access inside an organization, making them a frequent source of credential leaks.
- Logging everything indiscriminately: Excessive noise buries real signals and drives up log ingestion and storage bills.
- Shipping
print()to production instead of structured logging.
Connection to AI Development
- What every production LLM service should log: Model name and checkpoint version, prompt template version, input/output/reasoning token counts, end-to-end latency, request correlation ID, tool-call arguments and results, and retry counts. Without these fields, diagnosing why a workflow suddenly degraded is guesswork.
- Privacy and compliance: User prompts regularly contain sensitive personal or corporate data; scrub PII or hash/sample payloads before writing logs to persistent storage.
- LLM observability platforms: Tools like Langfuse, LangSmith, Arize Phoenix, and OpenTelemetry's GenAI Semantic Conventions unify logs, nested agent traces, and token cost attribution. See OpenTelemetry GenAI Semantic Conventions: https://github.com/open-telemetry/semantic-conventions-genai
- Model training telemetry: Per-step loss curves, gradient norms, and learning-rate schedules belong in purpose-built experiment trackers (TensorBoard, Weights & Biases, MLflow) rather than unstructured text logs.
Further Reading
- Python Logging HOWTO: https://docs.python.org/3/howto/logging.html
- Python Logging Cookbook: https://docs.python.org/3/howto/logging-cookbook.html
structlog(structured logging library for Python): https://www.structlog.org/- OpenTelemetry Observability Signals: https://opentelemetry.io/docs/concepts/signals/
Concept Check
When the DEBUG level is disabled on a logger, does an expensive function passed as an argument inside logger.debug("val=%s", compute_heavy()) still execute?
Reference answer: Yes. Python evaluates all function arguments before invoking logger.debug; only the string interpolation step is deferred unless you guard the call with logger.isEnabledFor(logging.DEBUG).
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 17_logging.py.
Companion Code & Verification Materials