# 🐍 Stop Using print() for Debugging: Discover Python's Logging Module

in #python-dev • 6 hours ago

Hello Steemit community! 👋

Today, I'd like to share a useful Python programming technique that can make your applications easier to debug, monitor, and maintain.

If you've written Python code before, you've probably used print() to check variable values or understand what your program is doing.

While print() is convenient, Python provides a much more powerful alternative: the built-in logging module.

Let's explore why it's worth using!

🔹 The Common Approach: print()

Imagine you're writing a simple program that processes data.

def process_data(data):
    print("Starting data processing...")

    result = sum(data)

    print("Processing completed!")
    print("Result:", result)

    return result

process_data([10, 20, 30, 40])

Output:

Starting data processing...
Processing completed!
Result: 100

This works fine for small scripts.

However, as applications grow, using print() everywhere becomes difficult to manage.

What if you want to distinguish errors from normal messages? What if you want to save debugging information to a file?

That's where logging comes in!

✅ A Better Approach: Python Logging

Python includes a powerful logging system in its standard library.

Here's a simple example:

import logging

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

def process_data(data):
    logging.info("Starting data processing...")

    result = sum(data)

    logging.info("Processing completed!")
    logging.info("Result: %s", result)

    return result

process_data([10, 20, 30, 40])

Example output:

2026-11-22 10:30:00 - INFO - Starting data processing...
2026-11-22 10:30:00 - INFO - Processing completed!
2026-11-22 10:30:00 - INFO - Result: 100

Now every message includes a timestamp and a severity level.

This makes debugging much easier, especially when your program runs for hours or days.

🔍 Understanding Logging Levels

Python provides several logging levels for different situations.

LevelPurpose
DEBUGDetailed debugging information
INFONormal application events
WARNINGSomething unexpected happened
ERRORAn operation failed
CRITICALA serious failure occurred

For example:

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Checking input variables")
logging.info("Application started")
logging.warning("Memory usage is increasing")
logging.error("Failed to connect to database")
logging.critical("Application cannot continue")

By changing the logging level, you can control how much information your application displays.

For example:

logging.basicConfig(level=logging.WARNING)

This configuration normally displays only WARNING, ERROR, and CRITICAL messages.

No need to delete your debugging statements!

💾 Saving Logs to a File

One of the most useful features of logging is the ability to save messages to a file.

import logging

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

logging.info("Application started")

try:
    result = 100 / 0
except ZeroDivisionError:
    logging.exception("Calculation failed")

Instead of displaying messages on the screen, Python writes them to application.log.

The logging.exception() function also records the exception traceback, making it easier to identify exactly where something went wrong.

This is particularly useful for web applications, automation scripts, and long-running background processes.

🚀 Bonus Tip: Use a Logger for Each Module

When developing larger Python projects, it's good practice to create a separate logger for each module.

import logging

logger = logging.getLogger(__name__)

def calculate_average(numbers):
    if not numbers:
        logger.warning("Empty list provided")
        return None

    result = sum(numbers) / len(numbers)

    logger.info("Average calculated: %s", result)

    return result


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    calculate_average([10, 20, 30])

Using __name__ helps identify which part of your application generated each message.

This becomes especially valuable when working with projects containing many Python files.

⚡ When Should You Use Logging?

Logging is particularly helpful when:

  • Building web applications with Flask, Django, or FastAPI.
  • Running automated data processing scripts.
  • Developing machine learning pipelines.
  • Monitoring long-running applications.
  • Debugging programs deployed on remote servers.

One important reminder: never log passwords, API keys, authentication tokens, or other sensitive information.

🎯 Final Thoughts

Using print() is perfectly fine for quick experiments and small scripts.

However, when building applications that need to be reliable and maintainable, Python's logging module is a much better choice.

It provides timestamps, severity levels, file output, and flexible configuration without requiring any external packages.

A small change in your programming habits can make a big difference in the quality of your software!

Do you still use print() for debugging, or have you switched to logging?

Share your experience in the comments! 💬

Happy coding! 🐍💻


Thanks for reading! If you found this post useful, feel free to upvote, comment, and follow for more practical Python programming tips.

#python #programming #coding #tutorial #technology