CodingNic

Error Handling and Debugging

Logging

Error Handling and Debugging 26 min read

Logging

Logging

Sometimes print() is not enough.

Real programs need a better way to record what happened.

Python gives us the logging module.

What Is Logging?

Logging means saving messages about your program.

These messages can show:

  • normal actions
  • warnings
  • errors
  • debugging information

Why Logging Matters

Logging helps you:

  • understand what happened
  • find bugs later
  • track errors
  • monitor programs

Import logging

python
import logging

Basic Logging Setup

Use basicConfig().

python
import logging

logging.basicConfig(level=logging.INFO)

logging.info("Program started")

Output Example

text
INFO:root:Program started

Common Log Levels

  • DEBUG = detailed info
  • INFO = normal events
  • WARNING = something unusual
  • ERROR = problem happened
  • CRITICAL = serious problem

Example: Different Levels

python
import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Loading data")
logging.info("User logged in")
logging.warning("Low disk space")
logging.error("File missing")
logging.critical("System stopped")

Example Output

text
DEBUG:root:Loading data
INFO:root:User logged in
WARNING:root:Low disk space
ERROR:root:File missing
CRITICAL:root:System stopped

Logging to a File

Save logs into a file.

python
import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO
)

logging.info("App opened")

Now the message is saved in app.log.

Logging Errors with try

python
import logging

logging.basicConfig(level=logging.ERROR)

try:
    print(10 / 0)
except ZeroDivisionError:
    logging.error("Cannot divide by zero")

Output Example

text
ERROR:root:Cannot divide by zero

Why Not Only print()?

print() is useful while learning.

Logging is better for real apps because it can:

  • show levels
  • save to files
  • keep history
  • organize messages

Code Along

Create a program that logs:

  • Program started
  • User clicked button
  • Program ended

Mini Challenge

Build a safe logger.

Steps:

  • Ask for a number
  • If valid, log:
text
INFO: Number accepted
  • If invalid, log:
text
ERROR: Invalid number

Real World Use Case

Apps use logging for websites, servers, finance tools, mobile apps, and debugging systems.

Quiz

  1. What is logging?
  2. Name two log levels.
  3. Why is logging better than print() in real apps?
  4. Can logs be saved to a file?

Assignment

Create a program that logs three messages: one info, one warning, and one error.

Summary

You learned how to use Python logging to record events, warnings, and errors for debugging and monitoring.