Basic Logging with the logging Module

Ever Wonder What Your Python Code is REALLY Doing? Master Basic Logging!

Have you ever built a complex Python program and then… poof… something goes wrong? Finding the source of the error feels like searching for a needle in a digital haystack. The truth is, effective logging in Python, using the logging module, is your secret weapon to debugging and understanding your code’s behavior. It’s a powerful, yet surprisingly simple tool, and I’m here to show you exactly how it works.

Core Concepts: Unlocking the Power of Python’s logging Module

Core Concepts:  Unlocking the Power of Python's logging Module “Core Concepts: Unlocking the Power of Python’s logging Module”)

Imagine your code as a busy restaurant. The logging module is like a detailed logbook where every important event – a customer order, a payment, a kitchen mishap – is meticulously recorded. This logbook helps you understand what happened, when it happened, and why.

The logging module provides different levels of logging, each representing a different severity:

  • DEBUG: The most detailed level, perfect for tracking tiny details during development. (Like noting every ingredient used in a dish).
  • INFO: General information about the program’s progress. (Like recording the order details).
  • WARNING: Potential problems that aren’t critical errors. (Like a low stock of an ingredient).
  • ERROR: Actual errors that prevent the program from running smoothly. (Like a burnt dish!)
  • CRITICAL: Severe errors that might crash the whole system. (Like a kitchen fire!)

We configure the logging module to only show messages that meet or exceed a certain level. For instance, setting the level to WARNING will only display warning, error, and critical messages, hiding less important debug and info messages.

We use handlers to determine where these log messages are sent:

  • ConsoleHandler: Sends log messages to your console (your terminal window).
  • FileHandler: Sends log messages to a file, which is useful for keeping a permanent record.
  • RotatingFileHandler: (Advanced) This is a really useful handler that allows you to create multiple log files that cycle automatically – great for long-running applications. Learn more about this here.

3 Simple Projects: Putting Logging Into Action

3 Simple Projects:  Putting Logging Into Action “3 Simple Projects: Putting Logging Into Action”)

Let’s build three simple projects to show you the magic of logging in practice. Remember, the more you experiment, the better you’ll understand it!

Project 1: Logging to the Console

This project logs simple messages to your console using different logging levels.

import logging

# Configure the logging system
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# Log messages at different levels
logging.debug('This is a debug message.')  # Detailed debugging information
logging.info('This is an informational message.') # General information
logging.warning('This is a warning message.') # Potential problems
logging.error('This is an error message.') # Actual errors
logging.critical('This is a critical message!') # Severe errors

This code first configures basic logging, setting the logging level to DEBUG (so we see everything). Then it logs messages at different levels. The format argument formats how the log message is displayed (timestamp, level, message).

Project 2: Logging to a File

Here, we log to a file named my_log.txt.

import logging

# Configure logging to write to a file
logging.basicConfig(filename='my_log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Log some messages
logging.info('This message will go to the file.')
logging.warning('This warning will also go to the file.')

This time, we specify filename='my_log.txt'. Now, check your directory for a newly created file ‘my_log.txt’ containing your log messages! The level is set to INFO to show you that you can control which log messages are recorded.

Project 3: A Simple Function with Error Handling and Logging

This project demonstrates logging within a function, including error handling.

import logging

logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')

def divide(x, y):
    try:
        result = x / y
        logging.info(f"Division successful: {x} / {y} = {result}") #successful operation logged at INFO level
        return result
    except ZeroDivisionError:
        logging.error(f"Error: Cannot divide by zero when dividing {x} by {y}") # Error captured and logged
        return None

divide(10, 2)
divide(5, 0)

This example showcases using logging inside a function to track successful operations and to handle and log errors, such as ZeroDivisionError.

Summary: Level Up Your Python Debugging Skills

Summary:  Level Up Your Python Debugging Skills “Summary: Level Up Your Python Debugging Skills”)

Basic logging with Python’s logging module is a game-changer. It provides a structured way to monitor your application’s health and quickly diagnose issues. Mastering these fundamentals will dramatically improve your Python programming workflow and make debugging a breeze!

Want to take your Python logging skills to the next level? Or need help with a specific project? We’re happy to assist you. Reach out to our team; we love helping you turn your complex coding ideas into functioning realities. We’re here to partner with you every step of the way.


⬅️ Previous Post: Datetime Basics Dates Times and Timezones

Explore Our Series on This Topic:



Need Help with a Python Assignment or Project?

Learning Python is exciting — but it can also get tricky sometimes. Whether you're stuck on a bug, running out of time on an assignment, or building something cool and just need a little help...

We’ve got your back. 💪

Our team is here to support you with:

  • ✅ Python assignments & school projects
  • ✅ Debugging errors or fixing code
  • ✅ Custom scripts or mini tools
  • ✅ Personal coding challenges or portfolio projects

Don’t struggle alone — reach out and let us help you get it done the smart way.

📩 Click here to contact us or

Let’s build something awesome together! Contact Us Now!

Leave a Comment

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

Scroll to Top