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().
Contextual Information
Logs are most useful when they contain context. Instead of just logging an error, include relevant variable states or identifiers.
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.
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.