Python provides several built-in tools to assist developers in debugging and logging during application development. Two commonly used tools are pdb
(Python Debugger) and the logging
module. These tools help track issues, log messages, and debug programs efficiently.
pdb
ModuleThe pdb
module is Python's built-in debugger, which allows you to pause execution and inspect the state of your program. You can use it to step through code, inspect variables, and identify bugs.
Here is an example of using pdb
:
import pdb def divide_numbers(a, b): pdb.set_trace() # Pause execution for debugging result = a / b return result divide_numbers(10, 2)
pdb.set_trace()
.n
(next), c
(continue), and q
(quit).l
: List the source code.n
: Execute the next line of code.c
: Continue execution until the next breakpoint.q
: Quit the debugger.p variable_name
: Print the value of a variable.logging
ModuleThe logging
module allows you to log messages at different severity levels. It is more robust and configurable than using print
statements for debugging or monitoring.
import logging # Configure logging logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s') def add_numbers(a, b): logging.debug(f"Adding {a} and {b}") return a + b result = add_numbers(5, 7) logging.info(f"Result is {result}")
DEBUG: Adding 5 and 7 INFO: Result is 12
DEBUG
: Detailed information for debugging purposes.INFO
: General information about program execution.WARNING
: Indicates something unexpected or a potential problem.ERROR
: An error occurred but the program can continue running.CRITICAL
: A severe error indicating the program may not continue running.You can save logs to a file for later analysis:
import logging logging.basicConfig(filename='app.log', level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s') logging.warning("This is a warning message") logging.error("This is an error message")
app.log
:2024-11-30 12:00:00,123 - WARNING - This is a warning message 2024-11-30 12:00:00,124 - ERROR - This is an error message
pdb
and logging
You can combine pdb
for interactive debugging and logging
for recording messages during development.
import pdb import logging logging.basicConfig(level=logging.INFO) def divide_numbers(a, b): pdb.set_trace() if b == 0: logging.error("Division by zero is not allowed!") return None return a / b result = divide_numbers(10, 0) logging.info(f"Result: {result}")
The pdb
module and logging
module are essential tools for Python developers. While pdb
is ideal for step-by-step debugging, logging
is better suited for tracking application behavior in production. By mastering these tools, you can debug and monitor your programs effectively.