Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Using Built-In Tools (pdb, logging) in Python


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.

Using the pdb Module

The 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.

Basic Example

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)
        

How It Works:

Interactive Debugging Commands

Using the logging Module

The 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.

Basic Example

    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}")
        

Output:

    DEBUG: Adding 5 and 7
    INFO: Result is 12
        

Logging Levels

Saving Logs to a File

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")
        

Content of 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
        

Combining 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}")
        

Conclusion

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.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java