Skip to main content

Pythonic Error Handling

Logging and Debugging

0:00
LearnStep 1/3

Effective Logging and Debugging

New Python developers often rely on print() statements to debug their code or track execution. While simple, this approach scales poorly. In production environments, you need a way to filter messages by severity, write to files or external services, and include timestamps without modifying your codebase. Python's built-in logging module provides this functionality.

Basic Configuration and Log Levels

The logging module defines standard levels indicating the severity of events: DEBUG, INFO, WARNING, ERROR, and CRITICAL. You can set up a basic configuration using logging.basicConfig().

python

Contextual Information

Logs are most useful when they contain context. Instead of just logging an error, include relevant variable states or identifiers.

python

Using exc_info=True (or logging.exception()) automatically includes the traceback, which is invaluable for debugging.

Interactive Debugging with breakpoint()

When you need to inspect the state of a running program, print isn't enough. Python 3.7+ introduced the built-in breakpoint() function, which drops you into the debugger (usually pdb) at that line.

python

Inside the debugger, you can type variable names to see their values, n to go to the next line, c to continue, or q to quit.