How to Debug in Python Using print() and logging With Examples

 


 

What Is Debugging?

Debugging is the process of identifying and fixing errors (bugs) in your code. Two common ways to debug in Python are:

  1. Using print() statements
  2. Using the logging module

1. Debugging with print()

Simple and Quick

print() is the fastest way to inspect variables and flow.

Example:

def greet(name):
    print("greet() function was called")  # Debug message
    print("Received name:", name)
    return f"Hello, {name}!"

print(greet("Alice"))

Pros:

  • Easy to use
  • No setup needed

Cons:

  • Not flexible (e.g., no log levels)
  • Messy for large projects
  • Hard to disable in production

2. Debugging with logging

The logging module is more powerful and professional, suitable for larger applications.

Example:

import logging

# Configure logging
logging.basicConfig(level=logging.DEBUG)

def greet(name):
    logging.debug("greet() function was called")
    logging.info(f"Received name: {name}")
    return f"Hello, {name}!"

print(greet("Alice"))

Output:

DEBUG:root:greet() function was called
INFO:root:Received name: Alice
Hello, Alice!

Logging Levels:

Level Use Case
DEBUG Detailed information for devs
INFO General info about execution
WARNING Something unexpected happened
ERROR Serious problem in the program
CRITICAL Very serious error

Custom Log Format Example:

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

Output Example:

2025-06-14 17:12:30,123 - DEBUG - greet() function was called

When to Use print() vs logging

Situation Use
Small scripts or quick tests print()
Larger apps or production code logging
Need log levels or file output logging
One-time debugging print()

Pro Tips

  • Use logging.debug() instead of print() for better control.
  • To disable debug logs in production, just change the log level:
    logging.basicConfig(level=logging.WARNING)

0 Comments:

Post a Comment