{"id":94,"date":"2025-10-25T06:53:29","date_gmt":"2025-10-25T06:53:29","guid":{"rendered":"https:\/\/codetypingpro.com\/?p=94"},"modified":"2025-12-17T07:49:19","modified_gmt":"2025-12-17T07:49:19","slug":"lesson-24-logging-and-debugging-in-python","status":"publish","type":"post","link":"https:\/\/codetypingpro.com\/?p=94","title":{"rendered":"Lesson 24: Logging and Debugging in Python"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\"><\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\ud83c\udfaf <strong>Lesson Objective<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To understand how to <strong>find and fix errors efficiently<\/strong> using debugging tools and how to <strong>track program execution<\/strong> using Python\u2019s <code>logging<\/code> module.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde9 <strong>1. What Is Debugging?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Debugging<\/strong> is the process of identifying and fixing bugs (errors) in your code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Common debugging techniques:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Using <code>print()<\/code> statements<\/li>\n\n\n\n<li>Using Python\u2019s built-in <strong><code>pdb<\/code><\/strong> (Python Debugger)<\/li>\n\n\n\n<li>Using IDEs like VS Code or PyCharm with <strong>breakpoints<\/strong><\/li>\n\n\n\n<li>Using the <strong><code>logging<\/code><\/strong> module for professional tracking<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\u2699\ufe0f <strong>2. Common Types of Errors<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Error Type<\/th><th>Description<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td><strong>SyntaxError<\/strong><\/td><td>Invalid Python syntax<\/td><td><code>print(\"Hello\"<\/code><\/td><\/tr><tr><td><strong>NameError<\/strong><\/td><td>Variable not defined<\/td><td><code>print(x)<\/code><\/td><\/tr><tr><td><strong>TypeError<\/strong><\/td><td>Invalid type operation<\/td><td><code>\"5\" + 2<\/code><\/td><\/tr><tr><td><strong>ValueError<\/strong><\/td><td>Wrong type of value<\/td><td><code>int(\"abc\")<\/code><\/td><\/tr><tr><td><strong>ZeroDivisionError<\/strong><\/td><td>Division by zero<\/td><td><code>10 \/ 0<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde0 <strong>3. Simple Debugging Using <code>print()<\/code><\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>def divide(a, b):\n    print(f\"Dividing {a} by {b}\")\n    return a \/ b\n\nprint(divide(10, 2))\nprint(divide(10, 0))  # Error: division by zero\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Problem:<\/strong> Works for quick checks but not for large or production programs.<br>\u2705 <strong>Solution:<\/strong> Use the <strong><code>logging<\/code><\/strong> module.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddfe <strong>4. Introduction to Logging<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Logging records <strong>events that happen during program execution<\/strong>, making it easier to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Diagnose issues<\/li>\n\n\n\n<li>Record user activity<\/li>\n\n\n\n<li>Track performance and errors<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>import logging\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf1 <strong>5. Basic Logging Example<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import logging\n\nlogging.basicConfig(level=logging.INFO)\nlogging.info(\"Program started successfully\")\nlogging.warning(\"Low disk space\")\nlogging.error(\"File not found!\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>INFO:root:Program started successfully\nWARNING:root:Low disk space\nERROR:root:File not found!\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf0 <strong>6. Logging Levels<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Level<\/th><th>Description<\/th><th>Usage<\/th><\/tr><\/thead><tbody><tr><td><code>DEBUG<\/code><\/td><td>Detailed information (for developers)<\/td><td>Code tracing<\/td><\/tr><tr><td><code>INFO<\/code><\/td><td>Confirmation that things are working<\/td><td>Status updates<\/td><\/tr><tr><td><code>WARNING<\/code><\/td><td>Something unexpected happened<\/td><td>Potential problems<\/td><\/tr><tr><td><code>ERROR<\/code><\/td><td>Serious issue, program may continue<\/td><td>Error handling<\/td><\/tr><tr><td><code>CRITICAL<\/code><\/td><td>Very serious error<\/td><td>Program crash alerts<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>logging.debug(\"This is a debug message\")\nlogging.info(\"Program is running fine\")\nlogging.warning(\"Low memory\")\nlogging.error(\"An error occurred\")\nlogging.critical(\"System failure!\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udeb6 <strong>7. Writing Logs to a File<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import logging\n\nlogging.basicConfig(filename=\"app.log\",\n                    level=logging.DEBUG,\n                    format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\nlogging.info(\"Application started\")\nlogging.warning(\"Disk usage high\")\nlogging.error(\"Error while processing data\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Creates a file:<\/strong> <code>app.log<\/code><br><strong>Example log:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-10-25 10:15:23,123 - INFO - Application started\n2025-10-25 10:15:23,456 - WARNING - Disk usage high\n2025-10-25 10:15:23,789 - ERROR - Error while processing data\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddee <strong>8. Logging in Try\u2013Except Blocks<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import logging\n\nlogging.basicConfig(level=logging.ERROR,\n                    format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\ntry:\n    result = 10 \/ 0\nexcept ZeroDivisionError as e:\n    logging.error(\"Division by zero error: %s\", e)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-10-25 12:34:56,789 - ERROR - Division by zero error: division by zero\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udc1e <strong>9. Debugging with <code>pdb<\/code> (Python Debugger)<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the <strong>Python debugger<\/strong> to pause execution and inspect variables step-by-step.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pdb\n\ndef add_numbers(a, b):\n    pdb.set_trace()  # Debug breakpoint\n    return a + b\n\nprint(add_numbers(5, 10))\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\ud83d\udd39 Commands inside <code>pdb<\/code>:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Command<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td><code>n<\/code><\/td><td>Next line<\/td><\/tr><tr><td><code>c<\/code><\/td><td>Continue execution<\/td><\/tr><tr><td><code>p variable<\/code><\/td><td>Print variable value<\/td><\/tr><tr><td><code>q<\/code><\/td><td>Quit debugging<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udca1 <strong>10. Example \u2013 Logging in a Real Program<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import logging\n\nlogging.basicConfig(filename=\"bank.log\", level=logging.INFO,\n                    format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\nclass BankAccount:\n    def __init__(self, name, balance):\n        self.name = name\n        self.balance = balance\n        logging.info(f\"Account created for {self.name} with balance {self.balance}\")\n\n    def deposit(self, amount):\n        self.balance += amount\n        logging.info(f\"{self.name} deposited {amount}. New balance: {self.balance}\")\n\n    def withdraw(self, amount):\n        if amount &gt; self.balance:\n            logging.warning(f\"{self.name} tried to withdraw {amount} but insufficient funds.\")\n        else:\n            self.balance -= amount\n            logging.info(f\"{self.name} withdrew {amount}. Remaining: {self.balance}\")\n\nacc = BankAccount(\"Sameer\", 1000)\nacc.deposit(500)\nacc.withdraw(2000)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Log File (<code>bank.log<\/code>):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-10-25 12:40:05,123 - INFO - Account created for Sameer with balance 1000\n2025-10-25 12:40:05,456 - INFO - Sameer deposited 500. New balance: 1500\n2025-10-25 12:40:05,789 - WARNING - Sameer tried to withdraw 2000 but insufficient funds.\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\"><\/h2>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udfaf Lesson Objective To understand how to find and fix errors efficiently using debugging tools and how to track program execution using Python\u2019s logging module. \ud83e\udde9 1. What Is Debugging? Debugging is the process of identifying and fixing bugs (errors) in your code. Common debugging techniques: \u2699\ufe0f 2. Common Types of Errors Error Type Description [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,1],"tags":[],"class_list":["post-94","post","type-post","status-publish","format-standard","hentry","category-python-easy-course-outline","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/94","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=94"}],"version-history":[{"count":1,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/94\/revisions"}],"predecessor-version":[{"id":95,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/94\/revisions\/95"}],"wp:attachment":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=94"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=94"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=94"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}