Every Python script starts with print(). "Starting import..." "Done." "Error!!!" It works fine while you're watching the terminal.
Then the script runs at 2 a.m. from Task Scheduler, or as a service on a server, and something fails. The prints went nowhere. There's no timestamp, no record of which customer was being processed, and no traceback. You're left guessing.
Python's built-in logging module solves all of that, and with a small setup function it's no harder to use than print().
What logging gives you that print() doesn't
- Timestamps on every message
- Levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), so you can show more or less detail without changing code
- Destinations: console, files, rotating files, syslog, the Windows Event Log, log services
- Tracebacks for exceptions, captured automatically
- Context: which module wrote the message, plus extra fields like an order ID
- Configuration in one place, instead of print() calls scattered through the code
The five levels
- DEBUG — Use it for: Detailed information for diagnosing problems: values, branches taken
- INFO — Use it for: Normal events: job started, file processed, 250 rows imported
- WARNING — Use it for: Something unexpected but handled: retrying, slow response, missing optional value
- ERROR — Use it for: An operation failed: an order couldn't be charged, a file couldn't be read
- CRITICAL — Use it for: The program can't continue: database unreachable, configuration missing
In production you'd usually log INFO and above. When investigating a problem, switch to DEBUG with an environment variable, without touching code.
A complete, reusable setup
And writes structured JSON lines to logs/app.log:
{"time": "2026-11-18T19:00:09", "level": "INFO", "logger": "billing", "message": "Charging order", "order_id": "1042"}
{"time": "2026-11-18T19:00:09", "level": "ERROR", "logger": "billing", "message": "Charge failed", "order_id": "1043", "exception": "Traceback (most recent call last): ..."}
We ran this exact script; the output above is from that run, with the traceback shortened.
Create a logger per module
log = logging.getLogger("billing")
In real projects, use logging.getLogger(__name__) at the top of each module. The logger's name then matches the module path (myapp.billing, myapp.db), so you can see where every message came from, and turn up or down the detail for specific parts of the app.
Configure once, at the entry point
setup_logging() is called only in if __name__ == "__main__":, the place where your program starts. Library code and modules should only create loggers and log, never configure handlers. Otherwise you get duplicated or missing messages when modules are imported elsewhere.
Handlers decide where messages go
We attach two handlers to the root logger:
- a StreamHandler for the console, with a short human-friendly format
- a TimedRotatingFileHandler that starts a new file at midnight and keeps 14 days of history
Rotation matters. A log file that grows forever eventually fills the disk, usually on a weekend. For size-based rotation, use RotatingFileHandler(maxBytes=..., backupCount=...) instead.
Use lazy formatting
log.warning("Retry queue has %d items", 3)
Pass values as arguments rather than building an f-string. The message is only formatted if it will actually be logged, which saves work for DEBUG messages that are switched off. It also lets log tools group messages with the same template.
Log exceptions with tracebacks
except ValueError:
log.exception("Charge failed", extra={"order_id": "1043"})
log.exception() logs at ERROR level and includes the full traceback. Use it inside except blocks. A message like "Something failed" without a traceback is one of the most frustrating things to find in a log.
Add context with extra fields
log.info("Charging order", extra={"order_id": order_id})
Fields passed with extra become attributes on the log record. Our JsonFormatter writes them as separate JSON keys, so you can later search "all log lines for order 1043". In larger applications, a LoggerAdapter or contextvars can attach a request ID to every message automatically.
Structured (JSON) logs
Plain text is great for humans reading a terminal. JSON lines are better for machines: log tools like Grafana Loki, Elasticsearch, Azure Monitor, CloudWatch and Datadog can filter by level, logger or order_id instantly. Libraries such as structlog and python-json-logger provide richer structured logging if you outgrow the simple formatter.
Common mistakes
Calling logging.basicConfig() in several modules. Only the first call takes effect. Configure once at the entry point.
Using the root logger everywhere (logging.info(...)). It works, but you lose the module name and the ability to control levels per module.
Swallowing exceptions:
try:
import_file(path)
except Exception:
pass # the error vanishes forever
At minimum, log.exception("Import failed for %s", path).
Logging secrets and personal data. Never log passwords, tokens, API keys, full card numbers or Aadhaar numbers. Be careful with request bodies and headers, and mask sensitive values. Logs are often kept longer, and copied more widely, than the data itself.
Logging too much. If every loop iteration writes INFO lines, real problems drown. Keep INFO for meaningful events and use DEBUG for detail.
Noisy libraries. Libraries like urllib3, botocore or asyncio can be chatty. Raise their level, as the example does for urllib3.
Logging in scheduled jobs and services
For scripts run by Task Scheduler or cron:
- log to a file with an absolute path (or set LOG_DIR), since the working directory may not be what you expect
- log a clear start and finish line with counts ("Imported 250 rows, 3 skipped")
- return a non-zero exit code on failure, so the scheduler records it
- consider sending ERROR-level messages by email or chat alert, using logging.handlers.SMTPHandler or your monitoring tool
For web apps under Gunicorn or Uvicorn, log to the console (stdout) and let the platform or container runtime collect the logs. That's the standard approach for containers.
Configuration from a file
For larger apps, describe logging in a dictionary or YAML file and load it with logging.config.dictConfig(). That way operations staff can change levels and destinations without editing code.
Key takeaways
Replacing print() with logging costs a few lines of setup and pays for itself the first time something fails while nobody is watching. Create a logger per module, configure handlers once at startup, rotate log files, log exceptions with tracebacks, add context like order IDs, and keep secrets out of your logs.
Copy the setup_logging() function into your next script. The next 2 a.m. failure will come with timestamps, context and a traceback, instead of a mystery.
Leave a Comment