Reading history

Python Logging Tutorial: Levels, Handlers and Formatters

6 min read 1 views

Use Python's logging module: log levels, basicConfig, named loggers, formatting, logging exceptions, and handlers that write to the console and a file.

While you are learning, print() is the natural way to see what a program is doing. In real applications, especially ones that run on a server with nobody watching, you need more: messages graded by importance, timestamps, the ability to turn detail on or off without editing code, and output saved to a file. Python’s built-in logging module does all of that. This lesson shows how to log messages, choose levels, format output and send logs to several places at once.

In this lesson you will learn

  • The five log levels: DEBUG, INFO, WARNING, ERROR and CRITICAL
  • Quick setup with logging.basicConfig
  • Named loggers with getLogger(__name__)
  • Formatting messages and recording exceptions
  • Handlers that send logs to the console and a file with different levels

You should know functions, exception handling and modules.

Levels and basicConfig

import logging
import sys

# Basic setup: level, message format, and where to write (stdout here so you can see it)
logging.basicConfig(
    level=logging.INFO,
    format="%(levelname)-8s %(name)s: %(message)s",
    stream=sys.stdout,
)

log = logging.getLogger("shop")

log.debug("cart contents: %s", ["pen"])       # below INFO: not shown
log.info("order %d placed by %s", 1001, "Karim")
log.warning("stock low for %s (%d left)", "notebook", 3)
log.error("payment failed for order %d", 1002)

try:
    1 / 0
except ZeroDivisionError as e:
    log.error("could not calculate discount: %s", e)  # log.exception(...) would add the traceback

print("--- raising the level to WARNING ---")
log.setLevel(logging.WARNING)
log.info("this info message is now hidden")
log.warning("warnings still appear")

Output

INFO     shop: order 1001 placed by Karim
WARNING  shop: stock low for notebook (3 left)
ERROR    shop: payment failed for order 1002
ERROR    shop: could not calculate discount: division by zero
--- raising the level to WARNING ---
WARNING  shop: warnings still appear
  • basicConfig sets up logging once, at the start of the program: the minimum level to show, the message format, and the output stream. By default logs go to standard error; this example uses standard output so you can see them next to the prints.
  • Each level has a method: debug, info, warning, error and critical. With the level set to INFO, the DEBUG message was dropped.
  • Pass values as extra arguments, as in log.info("order %d placed by %s", 1001, "Karim"). The message is only built if it will actually be shown, which is faster than an f-string for hidden levels.
  • In an except block, log.exception("...") logs at ERROR level and adds the full traceback, which is exactly what you need when investigating a crash later. The example uses log.error to keep the output short.
  • setLevel(logging.WARNING) silenced the info message without touching the call. In a real app the level usually comes from a setting or environment variable.

Loggers, Handlers and Formatters

import logging
import os
import sys
import tempfile

folder = tempfile.mkdtemp()
log_path = os.path.join(folder, "app.log")

logger = logging.getLogger("payments")
logger.setLevel(logging.DEBUG)
logger.propagate = False                       # do not also send to the root logger

# Handler 1: everything (DEBUG and up) to a file, with time and function name
file_handler = logging.FileHandler(log_path, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
    "%(asctime)s | %(levelname)s | %(funcName)s | %(message)s", datefmt="%H:%M:%S"))

# Handler 2: only WARNING and up to the console, short format
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.WARNING)
console.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))

logger.addHandler(file_handler)
logger.addHandler(console)


def charge(amount):
    logger.debug("charging %d taka", amount)
    if amount > 5000:
        logger.warning("large payment: %d taka needs review", amount)
    logger.info("charged %d taka", amount)


charge(1200)
charge(8000)

file_handler.close()
with open(log_path, encoding="utf-8") as f:
    lines = f.read().splitlines()
print(f"log file has {len(lines)} lines:")
for line in lines:
    print("  " + line.split(" | ", 1)[1])        # hide the time so the output is repeatable

Output

[WARNING] large payment: 8000 taka needs review
log file has 5 lines:
  DEBUG | charge | charging 1200 taka
  INFO | charge | charged 1200 taka
  DEBUG | charge | charging 8000 taka
  WARNING | charge | large payment: 8000 taka needs review
  INFO | charge | charged 8000 taka
  • A logger creates messages; handlers decide where they go; formatters decide how they look. One logger can have several handlers.
  • The file handler accepts DEBUG and above, so the file kept all five messages. The console handler accepts WARNING and above, so only the large-payment warning appeared on screen.
  • %(asctime)s adds the time, %(levelname)s the level and %(funcName)s the function that logged. The example hides the time when printing the file so the output stays the same on every run.
  • propagate = False stops messages also travelling up to the root logger, which would print them a second time if the root logger had its own handler.
  • In a larger project, each module uses logging.getLogger(__name__), so log lines show which module they came from, and settings can be changed per module.

Log Levels

LevelValueUse for
DEBUG10Detailed information for diagnosing problems
INFO20Normal events: started, finished, order placed
WARNING30Something unexpected that the program handled (the default level)
ERROR40An operation failed
CRITICAL50The program itself may not be able to continue

For files that grow forever, use logging.handlers.RotatingFileHandler, which starts a new file when the current one reaches a size limit and keeps a fixed number of old files.

Common Mistakes

  1. Calling basicConfig after logging has already started. It does nothing if the root logger already has handlers; call it once, early.
  2. Building messages with f-strings for debug logs that are usually hidden, which wastes time formatting text nobody sees.
  3. Logging passwords, card numbers or personal data. Logs are often stored for a long time and read by many people.
  4. Adding handlers every time a function runs, which makes each message appear several times. Configure handlers once.

Practice Exercises

Exercise 1. Configure logging so that messages include the time, level and message, and only WARNING and above are shown.

Show answer
import logging
logging.basicConfig(level=logging.WARNING,
                    format="%(asctime)s %(levelname)s %(message)s")
logging.info("hidden")
logging.warning("disk space below 10%")

The message is formatted with % only when extra arguments are passed, so a single percent sign is fine here. In a message with arguments, write a literal percent sign as %%.

Exercise 2. Write a function divide(a, b) that logs the traceback if b is zero and returns None.

Show answer
import logging
log = logging.getLogger(__name__)

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        log.exception("cannot divide %s by zero", a)
        return None

Frequently Asked Questions

Should I remove print statements and use logging instead?

Use print for output that is the purpose of a program, such as a report on screen. Use logging for messages about what the program is doing, so they can be filtered, timestamped and saved.

Can logs be written as JSON?

Yes. You can write a custom Formatter that returns JSON, or use a library such as python-json-logger. JSON logs are easy for monitoring tools to search.

Summary

  • Logging grades messages by level and can switch detail on or off.
  • basicConfig is enough for small programs; handlers and formatters give full control.
  • Use getLogger(__name__) in each module and log.exception inside except blocks.
  • Never log secrets or personal data.

Next: Python argparse: Command-Line Arguments.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *