Lesson 24: Logging and Debugging in Python

🎯 Lesson Objective

To understand how to find and fix errors efficiently using debugging tools and how to track program execution using Python’s logging module.


🧩 1. What Is Debugging?

Debugging is the process of identifying and fixing bugs (errors) in your code.

Common debugging techniques:

  • Using print() statements
  • Using Python’s built-in pdb (Python Debugger)
  • Using IDEs like VS Code or PyCharm with breakpoints
  • Using the logging module for professional tracking

⚙️ 2. Common Types of Errors

Error TypeDescriptionExample
SyntaxErrorInvalid Python syntaxprint("Hello"
NameErrorVariable not definedprint(x)
TypeErrorInvalid type operation"5" + 2
ValueErrorWrong type of valueint("abc")
ZeroDivisionErrorDivision by zero10 / 0

🧠 3. Simple Debugging Using print()

def divide(a, b):
    print(f"Dividing {a} by {b}")
    return a / b

print(divide(10, 2))
print(divide(10, 0))  # Error: division by zero

Problem: Works for quick checks but not for large or production programs.
Solution: Use the logging module.


🧾 4. Introduction to Logging

Logging records events that happen during program execution, making it easier to:

  • Diagnose issues
  • Record user activity
  • Track performance and errors
import logging

🧱 5. Basic Logging Example

import logging

logging.basicConfig(level=logging.INFO)
logging.info("Program started successfully")
logging.warning("Low disk space")
logging.error("File not found!")

Output:

INFO:root:Program started successfully
WARNING:root:Low disk space
ERROR:root:File not found!

🧰 6. Logging Levels

LevelDescriptionUsage
DEBUGDetailed information (for developers)Code tracing
INFOConfirmation that things are workingStatus updates
WARNINGSomething unexpected happenedPotential problems
ERRORSerious issue, program may continueError handling
CRITICALVery serious errorProgram crash alerts

Example:

logging.debug("This is a debug message")
logging.info("Program is running fine")
logging.warning("Low memory")
logging.error("An error occurred")
logging.critical("System failure!")

🪶 7. Writing Logs to a File

import logging

logging.basicConfig(filename="app.log",
                    level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")

logging.info("Application started")
logging.warning("Disk usage high")
logging.error("Error while processing data")

Creates a file: app.log
Example log:

2025-10-25 10:15:23,123 - INFO - Application started
2025-10-25 10:15:23,456 - WARNING - Disk usage high
2025-10-25 10:15:23,789 - ERROR - Error while processing data

🧮 8. Logging in Try–Except Blocks

import logging

logging.basicConfig(level=logging.ERROR,
                    format="%(asctime)s - %(levelname)s - %(message)s")

try:
    result = 10 / 0
except ZeroDivisionError as e:
    logging.error("Division by zero error: %s", e)

Output:

2025-10-25 12:34:56,789 - ERROR - Division by zero error: division by zero

🐞 9. Debugging with pdb (Python Debugger)

You can use the Python debugger to pause execution and inspect variables step-by-step.

import pdb

def add_numbers(a, b):
    pdb.set_trace()  # Debug breakpoint
    return a + b

print(add_numbers(5, 10))

🔹 Commands inside pdb:

CommandMeaning
nNext line
cContinue execution
p variablePrint variable value
qQuit debugging

💡 10. Example – Logging in a Real Program

import logging

logging.basicConfig(filename="bank.log", level=logging.INFO,
                    format="%(asctime)s - %(levelname)s - %(message)s")

class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        logging.info(f"Account created for {self.name} with balance {self.balance}")

    def deposit(self, amount):
        self.balance += amount
        logging.info(f"{self.name} deposited {amount}. New balance: {self.balance}")

    def withdraw(self, amount):
        if amount > self.balance:
            logging.warning(f"{self.name} tried to withdraw {amount} but insufficient funds.")
        else:
            self.balance -= amount
            logging.info(f"{self.name} withdrew {amount}. Remaining: {self.balance}")

acc = BankAccount("Sameer", 1000)
acc.deposit(500)
acc.withdraw(2000)

Log File (bank.log):

2025-10-25 12:40:05,123 - INFO - Account created for Sameer with balance 1000
2025-10-25 12:40:05,456 - INFO - Sameer deposited 500. New balance: 1500
2025-10-25 12:40:05,789 - WARNING - Sameer tried to withdraw 2000 but insufficient funds.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *