Site icon Full-Stack

Introduction to Python’s logging Module for Better Debugging

Printing errors with print() can only take you so far. For scalable, professional Python applications, using the built-in logging module is the right way to debug and track issues.

This beginner-friendly guide explains what the logging module is, why it matters, and how you can start using it effectively in your Python projects.


Why Use the logging Module?


Basic Logging Example

python

Copy code

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug(“This is a debug message”)

logging.info(“Informational message”)

logging.warning(“This is a warning”)

logging.error(“An error occurred”)

logging.critical(“Critical issue”)

By default, basicConfig() sends logs to the console.


Logging to a File

python

Copy code

logging.basicConfig(filename=”app.log”, level=logging.INFO, format=”%(asctime)s – %(levelname)s – %(message)s”)

logging.info(“Application started”)

✅ Logs will be saved in app.log with timestamps and severity levels.


Understanding Logging Levels

LevelUse Case
DEBUGDetailed info, mostly for developers
INFOGeneral info about program execution
WARNINGSomething unexpected, but recoverable
ERRORMore serious issue; might crash soon
CRITICALMajor failure; program can’t continue

Use levels to control the verbosity of logs and filter unnecessary messages.


Custom Logger Example

python

Copy code

logger = logging.getLogger(“my_app”)

logger.setLevel(logging.DEBUG)

handler = logging.FileHandler(“my_app.log”)

formatter = logging.Formatter(“%(name)s – %(levelname)s – %(message)s”)

handler.setFormatter(formatter)

logger.addHandler(handler)

logger.info(“Custom logger initialized”)

This setup gives you full control over where and how logs are recorded.


Practice Tip

Convert one of your Python scripts to use logging instead of print(). Set it up to log both to the console and to a file. This is especially useful for debugging long-running scripts or automation tools.


Build Smarter, Debug Faster

Learning logging not only improves your debugging process—it also prepares your projects for real-world deployment.

🚀 Want hands-on practice with real-world Python tools and workflows?
👉 https://www.thefullstack.co.in/courses/

You might be like this:-

What is AWS Lambda?A Beginner’s Guide to Serverless Computing in 2025

Java vs. Kotlin: Which One Should You Learn for Backend Development?

Where to Find Your Salesforce Organization ID

How Salesforce Stands Out from Other CRMs

Exit mobile version