Python Logging & Debugging

Python Logging & Debugging – Best Practices for Maintaining Code

Writing code is only part of programming maintaining it is equally important. Bugs happen, programs crash, and without proper monitoring, identifying issues can be frustrating.

Logging and debugging are essential skills for every Python developer. They help you:

✔ Track application behavior
✔ Identify and fix bugs quickly
✔ Maintain production-ready code

In this guide, you’ll learn Python’s logging and debugging techniques, best practices, and real-world applications.

Part 1: Python Logging Basics

Python provides a built-in logging module that allows you to record messages at different severity levels.

Logging Levels

Level  Description
DEBUG                    Detailed information for debugging
INFO                    General information about program execution
WARNING                    Indication of potential issues
ERROR                    Serious problems, exceptions
CRITICAL                    Very severe issues causing program failure


1️⃣ Basic Logging Example

import logging

logging.basicConfig(level=logging.INFO)
logging.debug("This is a debug message")
logging.info("Program started")
logging.warning("This is a warning")
logging.error("An error occurred")
logging.critical("Critical issue!")

Output:

INFO:root:Program started
WARNING:root:This is a warning
ERROR:root:An error occurred
CRITICAL:root:Critical issue!


2️⃣ Logging to a File

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

logging.info("Program started")
logging.error("Something went wrong")

This will save all logs to app.log with timestamps.

3️⃣ Advanced Logging Configuration

logger = logging.getLogger("PyCraftLogger")
logger.setLevel(logging.DEBUG)

# File handler
fh = logging.FileHandler("app.log")
fh.setLevel(logging.WARNING)

# Console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

# Formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# Add handlers to logger
logger.addHandler(fh)
logger.addHandler(ch)


Part 2: Python Debugging Techniques

Debugging is the process of identifying and fixing errors in your code.

Python provides multiple ways:

1️⃣ Using print() Statements

The simplest debugging method:

x = 10
y = 0
print("x:", x, "y:", y)
z = x / y # Will raise ZeroDivisionError

Limitations: Print statements can clutter code and are not scalable for larger projects.

logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")


2️⃣ Using Python Debugger (pdb)

Python’s built-in debugger allows step-by-step execution:

import pdb
x = 10
y = 0
pdb.set_trace() # Start debugging
z = x / y
  • Commands inside pdb:

    • n → Next line

    • c → Continue execution

    • p variable → Print value

    • q → Quit debugger

3️⃣ Using IDE Debuggers

Modern IDEs like PyCharm, VS Code, and Jupyter Notebooks have built-in debuggers with:

  • Breakpoints

  • Step-over / Step-into

  • Variable inspection

  • Call stack visualization

 Part 3: Best Practices for Logging & Debugging

  1. Use logging instead of print statements for production code.

  2. Set appropriate logging levels (DEBUG for dev, INFO/WARNING for prod).

  3. Log to files for long-running applications.

  4. Avoid logging sensitive data like passwords.

  5. Use try-except blocks with logging for error handling:

try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("Division by zero: %s", e)
  1. Use debugging tools to step through complex code.

  2. Maintain clean logs — rotate logs using logging.handlers.RotatingFileHandler.

  3. Document error codes or messages for future maintenance.

Real-World Use Cases

  • Monitoring web applications in production

  • Tracking API request failures

  • Debugging data processing pipelines

  • Maintaining large-scale Python applications

  • Automating error reporting

Proper logging and debugging are essential for building maintainable, scalable, and production-ready Python applications.

  • Logging helps you track program behavior.

  • Debugging helps you find and fix issues efficiently.

  • Best practices ensure your code is clean, secure, and easy to maintain.

Master these skills to write professional Python applications that are reliable and easier to troubleshoot.

Comments