Skip to content

Debugging & Logging

Every developer writes bugs. A professional developer is distinguished by how quickly and systematically they can find and fix them. While print() is a common first step, it is inefficient for large systems.

In this chapter, we explore Logging for observing long-running systems and Debugging for pausing time to inspect reality.


The logging module is the industry standard for tracking events. Unlike print, logging can be turned on or off, filtered by importance, and sent to multiple locations (console, files, cloud).

  1. DEBUG: Detailed info for developers.
  2. INFO: Confirmation that things are working.
  3. WARNING: Something unexpected happened, but the app is still running.
  4. ERROR: A feature failed to run.
  5. CRITICAL: The entire app crashed.
logging_pro.py
import logging
# Configure once at the start of your app
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logging.info("System starting...")
logging.error("Failed to connect to database.")

Introduced in Python 3.7, the breakpoint() keyword is the easiest way to pause your code and enter an interactive shell inside your running program.

debug_logic.py
def calculate_complex_math(x, y):
result = x * 2
breakpoint() # The program pauses here!
return result / y
# Inside the prompt, you can:
# 'p result' -> Print the value of result
# 'n' -> Go to next line
# 'c' -> Continue execution

Professional IDEs allow you to set “Visual Breakpoints” (the red dots next to line numbers).

  1. Click to the left of a line number.
  2. Press F5.
  3. The program stops, and you can see all your variables in a side panel. This is much faster than manual text debugging.

When your program crashes, Python prints a Traceback.

  • Top: Where the error started (Global scope).
  • Bottom: Where the error finally exploded.

Always read from the bottom up! The last line tells you the type of error (ZeroDivisionError) and the specific line where it happened.


ToolWhen to use?Why?
print()Simple, one-off scripts.Fast but messy.
loggingProduction systems.Permanent, searchable record.
breakpoint()Hard-to-find logic bugs.Real-time inspection.
IDE DebuggerEvery day development.Visual and powerful.