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.
1. Professional Logging
Section titled “1. Professional Logging”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).
The Hierarchy of Severity
Section titled “The Hierarchy of Severity”DEBUG: Detailed info for developers.INFO: Confirmation that things are working.WARNING: Something unexpected happened, but the app is still running.ERROR: A feature failed to run.CRITICAL: The entire app crashed.
import logging
# Configure once at the start of your applogging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logging.info("System starting...")logging.error("Failed to connect to database.")2. The Modern Debugger: breakpoint()
Section titled “2. The Modern Debugger: breakpoint()”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.
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 execution3. Remote Debugging in VS Code
Section titled “3. Remote Debugging in VS Code”Professional IDEs allow you to set “Visual Breakpoints” (the red dots next to line numbers).
- Click to the left of a line number.
- Press
F5. - The program stops, and you can see all your variables in a side panel. This is much faster than manual text debugging.
4. Under the Hood: The Traceback
Section titled “4. Under the Hood: The Traceback”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.
5. Summary Table
Section titled “5. Summary Table”| Tool | When to use? | Why? |
|---|---|---|
print() | Simple, one-off scripts. | Fast but messy. |
logging | Production systems. | Permanent, searchable record. |
breakpoint() | Hard-to-find logic bugs. | Real-time inspection. |
| IDE Debugger | Every day development. | Visual and powerful. |