Back to Home 9 lessons Pyodide ready

Python Logging
Like a Pro

Replace print() with levels, handlers, formatters, and rotating files. Nine interactive lessons that teach production-ready logging β€” by @PoeticGlenn.

What you will learn

The five standard log levels, how to configure the root logger and named loggers, attach console and file handlers, control message format, rotate log files, and follow practices that keep logs useful in real applications.

Why Logging Exists

print() is fine while you are exploring. In anything that runs longer than a few minutes β€” a web service, a scheduled job, a data pipeline β€” you need messages that can be filtered by importance, written to files, timestamped, and left running without flooding the terminal. That is what the standard library logging module is for.

Logging gives you five severity levels, multiple destinations (console, files, network), structured message formats, and the ability to turn verbosity up or down without changing source code. Once you learn the core ideas β€” Logger, Handler, Formatter, Level β€” the rest of the module falls into place.

πŸ€” print() vs logging

Why production code almost never relies on print for diagnostics

❌ The print() Habit

Print statements are always on, have no severity, and disappear when stdout is not captured. They also mix freely with real program output.

python
def process_order(order_id):
    print("Starting order", order_id)          # always visible
    # ... work ...
    print("Order done")                        # no severity
    print("WARNING: low stock")                # still just a string

process_order(42)

βœ… The logging Approach

Same idea with levels, so you can silence debug noise in production while still recording warnings and errors.

python
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

def process_order(order_id):
    logging.info("Starting order %s", order_id)
    # ... work ...
    logging.info("Order done")
    logging.warning("Low stock for order %s", order_id)

process_order(42)
logging.debug("This will not appear β€” level is INFO")
πŸ’‘ Notice the %s style: the message is only formatted if the level is enabled. That avoids expensive string work for disabled debug messages.

πŸ“Š The Five Standard Levels

DEBUG β†’ INFO β†’ WARNING β†’ ERROR β†’ CRITICAL

πŸ“ 1.1 Level Hierarchy

Each level has a numeric severity. A logger (or handler) only emits records at or above its configured level.

python
import logging

print("DEBUG   ", logging.DEBUG)
print("INFO    ", logging.INFO)
print("WARNING ", logging.WARNING)
print("ERROR   ", logging.ERROR)
print("CRITICAL", logging.CRITICAL)

# Show filtering
logging.basicConfig(level=logging.WARNING, format="%(levelname)-8s %(message)s", force=True)

logging.debug("detail for developers")
logging.info("normal progress")
logging.warning("something unexpected")
logging.error("a failure that was handled")
logging.critical("system is unusable")
πŸ’‘ force=True (Python 3.8+) reconfigures even if basicConfig was already called β€” useful in notebooks and interactive runners.

πŸ“ 1.2 When to Use Each Level

  • βœ“DEBUG β€” detailed diagnostic information, usually only interesting during development
  • βœ“INFO β€” confirmation that things are working as expected (startup, completed jobs)
  • βœ“WARNING β€” something unexpected happened, but the software is still working
  • βœ“ERROR β€” a serious problem; the software failed to perform a function
  • βœ“CRITICAL β€” a very serious error; the program itself may be unable to continue

▢️ Basic Usage

Getting useful output in under a minute

πŸ“ 2.1 basicConfig β€” The Quick Start

One call configures the root logger with a stream handler and a simple format.

python
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)-8s | %(message)s",
    datefmt="%H:%M:%S",
    force=True,
)

logging.debug("Connecting to database")
logging.info("User logged in: alice")
logging.warning("Disk space below 10%")
logging.error("Failed to send email")

πŸ“ 2.2 Named Loggers

Prefer logging.getLogger(__name__) so each module has its own logger and you can control verbosity per package.

python
import logging

logging.basicConfig(level=logging.DEBUG, format="%(name)s | %(levelname)s | %(message)s", force=True)

# Simulate two modules
log_auth = logging.getLogger("myapp.auth")
log_db   = logging.getLogger("myapp.db")

log_auth.info("Login attempt for user=bob")
log_db.debug("Executing query: SELECT * FROM users")
log_db.warning("Slow query (1.2s)")

# Silence one package
logging.getLogger("myapp.db").setLevel(logging.WARNING)
log_db.debug("This debug line is now suppressed")
log_db.warning("This warning still appears")
πŸ’‘ Logger names form a hierarchy. Setting the level on myapp.db does not affect myapp.auth. Setting it on myapp would affect both children.

βš™οΈ Configuration Styles

basicConfig, dictConfig, and programmatic setup

πŸ“ 3.1 Programmatic Handlers (explicit control)

Create a logger, attach a handler, and set a formatter yourself. This is the most flexible approach.

python
import logging
import sys

# Fresh logger for this example
logger = logging.getLogger("demo")
logger.setLevel(logging.DEBUG)
logger.handlers.clear()  # avoid duplicate handlers on re-run

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)

formatter = logging.Formatter(
    "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%H:%M:%S",
)
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.debug("Not shown β€” handler level is INFO")
logger.info("Application started")
logger.error("Something failed", exc_info=False)

πŸ“ 3.2 Useful Format Fields

Common placeholders you will use in format strings:

  • βœ“%(asctime)s β€” timestamp
  • βœ“%(levelname)s β€” DEBUG / INFO / WARNING / …
  • βœ“%(name)s β€” logger name
  • βœ“%(message)s β€” the log message
  • βœ“%(filename)s / %(lineno)d β€” source location
  • βœ“%(funcName)s β€” function that issued the log
  • βœ“%(process)d / %(threadName)s β€” process / thread info

πŸ“€ Handlers β€” Where Logs Go

Console, files, and rotating files

πŸ“ 4.1 StreamHandler (console)

Writes to sys.stderr by default. You already used it via basicConfig.

python
import logging
import sys

logger = logging.getLogger("console_demo")
logger.handlers.clear()
logger.setLevel(logging.DEBUG)

sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(logging.Formatter("%(levelname)s β†’ %(message)s"))
logger.addHandler(sh)

logger.info("Visible on stdout")
logger.warning("Also visible")
⚠️ File handlers write to a real filesystem. In the browser runner they use a virtual FS that does not persist β€” the examples below demonstrate the API; run them locally for real files.

πŸ“ 4.2 FileHandler & RotatingFileHandler (concepts)

Typical production pattern: one rotating file for the application, console for interactive use.

python
import logging
from logging.handlers import RotatingFileHandler
import sys

logger = logging.getLogger("app")
logger.handlers.clear()
logger.setLevel(logging.DEBUG)

# Console β€” human readable
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)-8s %(message)s"))

# In a real script you would also add:
# file_handler = RotatingFileHandler("app.log", maxBytes=1_000_000, backupCount=3)
# file_handler.setLevel(logging.DEBUG)
# file_handler.setFormatter(...)
# logger.addHandler(file_handler)

logger.addHandler(console)
logger.debug("Only goes to file (if configured)")
logger.info("Goes to console and file")
logger.error("Goes to both")
πŸ’‘ RotatingFileHandler keeps the last backupCount files when the current file exceeds maxBytes. TimedRotatingFileHandler rotates on a schedule instead.

🎨 Formatters & Structured Messages

Make logs readable for humans and machines

πŸ“ 5.1 Custom Format Strings

python
import logging
import sys

logger = logging.getLogger("fmt")
logger.handlers.clear()
logger.setLevel(logging.DEBUG)

fmt = logging.Formatter(
    fmt="%(asctime)s | %(levelname)-8s | %(filename)s:%(lineno)d | %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
h = logging.StreamHandler(sys.stdout)
h.setFormatter(fmt)
logger.addHandler(h)

logger.info("Service ready")
logger.warning("Retry count exceeded")

πŸ“ 5.2 Extra Fields & exc_info

Pass structured context with the extra dict, and attach exception info with exc_info=True.

python
import logging
import sys

logger = logging.getLogger("ctx")
logger.handlers.clear()
logger.setLevel(logging.DEBUG)

fmt = logging.Formatter("%(levelname)s user=%(user)s | %(message)s")
h = logging.StreamHandler(sys.stdout)
h.setFormatter(fmt)
logger.addHandler(h)

logger.info("Login success", extra={"user": "alice"})
logger.warning("Rate limit near", extra={"user": "bob"})

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Division failed")  # includes traceback
πŸ’‘ logger.exception(...) is a convenience for logger.error(..., exc_info=True) inside an except block. It records the current exception automatically.

βœ… Best Practices

Habits that keep logs useful instead of noisy

πŸ“‹ Guidelines

  • βœ“Use logging.getLogger(__name__) in every module
  • βœ“Configure logging once at application startup (not in libraries)
  • βœ“Prefer %s / %d style over f-strings so disabled levels stay cheap
  • βœ“Log the exception with logger.exception or exc_info=True, not only the message
  • βœ“Keep DEBUG off in production; leave WARNING and above on
  • βœ“Never log secrets (passwords, tokens, full credit-card numbers)
  • βœ“Use rotating or timed handlers so log files cannot grow without bound
  • βœ“Libraries should only add handlers if the user has not configured logging (or document that they do)

πŸ“ 6.1 A Minimal Production-Ready Snippet

Pattern you can copy into a real script (file parts commented for the browser runner).

python
import logging
import sys

def setup_logging(level=logging.INFO):
    root = logging.getLogger()
    root.handlers.clear()
    root.setLevel(level)

    console = logging.StreamHandler(sys.stdout)
    console.setFormatter(logging.Formatter(
        "%(asctime)s %(levelname)-8s [%(name)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    ))
    root.addHandler(console)

    # Uncomment locally:
    # from logging.handlers import RotatingFileHandler
    # fh = RotatingFileHandler("app.log", maxBytes=2_000_000, backupCount=5)
    # fh.setFormatter(...)
    # root.addHandler(fh)

setup_logging(logging.DEBUG)
log = logging.getLogger(__name__)
log.info("Application starting")
log.debug("Config loaded")
log.warning("Using default credentials β€” change them")

❓ Frequently Asked Questions

Common questions about the logging module

Usually because a handler was added more than once (e.g. calling configuration code on every request) or because both a child logger and the root logger have handlers and propagate is still True. Clear handlers before re-configuring, or set logger.propagate = False.

No. Libraries should only create named loggers and emit messages. Configuration belongs to the application that uses the library. If a library needs a fallback, it can add a NullHandler so that β€œNo handlers could be found” warnings are avoided.

A record must pass the logger’s level first. If it does, it is offered to each handler, which applies its own level filter. Setting the logger to DEBUG and a console handler to INFO is a common way to send everything to a file while keeping the console quieter.

Inside an except block use logger.exception("message") or logger.error("message", exc_info=True). Both attach the current exception information to the log record.

Yes. The standard library logging module is designed to be used from multiple threads. Handlers take locks around the actual emit operation.

🏁 Next Steps

You now have a practical foundation for application logging

βœ… What You Covered

  • Why print() is not enough for anything that runs longer than a few minutes
  • The five standard levels and when each is appropriate
  • basicConfig and named loggers with getLogger(__name__)
  • Programmatic setup with Handler + Formatter
  • StreamHandler, FileHandler, and RotatingFileHandler patterns
  • Format fields, extra, and logger.exception
  • Production-oriented best practices

Related modules: Exception Handling, Modules & Packages, and the main Curriculum.