Skip to content
IT Vizag
← Production Python

Logging instead of print

Lesson 3 of 10 · 2 min read

Logs you can actually use when something breaks.

🎬 Video version coming soon — read it now

print is fine while learning. In a program running on a server at 3 am, you need logs: messages with timestamps and severity levels, which you can filter and send to files or monitoring systems.

The basics

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger(__name__)

log.debug("Detailed info for debugging")        # hidden at INFO level
log.info("Processed 120 feedback items")
log.warning("Slow response from model: 8.2s")
log.error("Could not save report.csv")

Output:

2026-12-06 16:42:10,512 INFO feedback_api.service: Processed 120 feedback items

The levels

  • DEBUG: details useful only while debugging
  • INFO: normal events: started, finished, processed N items
  • WARNING: something unexpected, but the program carries on
  • ERROR: an operation failed
  • CRITICAL: the whole program can't continue

Set the level to DEBUG while developing and INFO or WARNING in production. No code changes, just configuration.

One logger per module

log = logging.getLogger(__name__)

__name__ is the module's name, so every line shows where it came from. Configure logging once, at the program's entry point, not in every module.

Logging exceptions

try:
    save_report(rows)
except OSError:
    log.exception("Saving the report failed")

log.exception logs at ERROR level and includes the full traceback. That's exactly what you need to fix the bug later.

Use lazy formatting

log.info("Processed %d items in %.1fs", count, elapsed)

The message is only built if the level is enabled, which saves work for DEBUG messages that are switched off.

Never log secrets or personal data

  • No API keys, passwords or tokens
  • Be careful with customer names, phone numbers, Aadhaar numbers and full message text. Log an ID instead.

Logs are often stored for months and read by many people.

Logs to a file

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()],
)

On hosting platforms, logging to the console (standard output) is usually best: the platform collects it and shows it in its dashboard.

Tip: When something goes wrong in production, logs are often your only evidence. Log the start and end of important operations, with counts and durations.

In one line

Use logging with levels and one logger per module, log exceptions with tracebacks, and never log secrets or personal data.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend