Logging in Python


What is Logging in Python?

Logging allows you to record messages that describe events or errors in your software. Unlike print(), logs can be saved to files, filtered by severity level, and formatted for clarity.

Python Logging Module

Python provides a built-in logging module for flexible and powerful logging.

import logging

Python Logging Levels

Each log message has a severity level. Python has 5 standard logging levels:

Level Method Description
DEBUG logging.debug() Detailed info, for diagnosing problems
INFO logging.info() Confirmation that things are working
WARNING logging.warning() An indication of potential problems
ERROR logging.error() A serious problem, program may not work
CRITICAL logging.critical() Very serious error, may crash the app

Basic Logging Example

import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message.")
logging.info("This is an info message.")
logging.warning("This is a warning message.")
logging.error("This is an error message.")
logging.critical("This is a critical message.")

Output:

DEBUG:root:This is a debug message.
INFO:root:This is an info message.
WARNING:root:This is a warning message.
ERROR:root:This is an error message.
CRITICAL:root:This is a critical message.

Logging to a File

import logging

logging.basicConfig(filename='app.log', level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

logging.info("Program started")
logging.warning("Low memory warning")

Formatting Log Messages

logging.basicConfig(format='%(levelname)s:%(message)s')

Common format codes:

  • %(asctime)s - Time of the log
  • %(levelname)s - Logging level
  • %(message)s - Log message
  • %(filename)s - Filename
  • %(lineno)d - Line number

Example: Logging Inside a Function

def divide(x, y):
    try:
        result = x / y
        logging.info("Division successful")
        return result
    except ZeroDivisionError:
        logging.error("Attempted division by zero")

divide(10, 0)

Python Logging Best Practices

  • Use different log levels for different message types
  • Avoid using print() in production code
  • Log exceptions using logging.exception()
  • Use rotating logs for large applications
  • Configure logger names using logging.getLogger(__name__)

Advanced: Rotating Logs with RotatingFileHandler

from logging.handlers import RotatingFileHandler

logger = logging.getLogger("AppLogger")
logger.setLevel(logging.INFO)

handler = RotatingFileHandler("app.log", maxBytes=2000, backupCount=3)
logger.addHandler(handler)

logger.info("This message goes to a rotating log file.")

Logging Exceptions

try:
    1 / 0
except ZeroDivisionError:
    logging.exception("Exception occurred")

Output:

ERROR:root:Exception occurred
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero

Summary

  • logging is more flexible and powerful than print()
  • Use appropriate levels like INFO, ERROR, DEBUG
  • Log to files for persistence and analysis
  • Format logs for better readability
  • Integrate logs into larger systems using handlers