Python Logging Tutorial | Logging Module, Log Levels & Best Practices
When developing software, simply printing messages to the console using print() is not enough for debugging and monitoring applications. Professional developers use Logging to record application events, errors, warnings, and system information.
Python’s built-in logging module provides a flexible and scalable way to track program execution. Logging helps developers troubleshoot issues, monitor application performance, maintain audit trails, and diagnose problems in production environments.
Logging is widely used in Artificial Intelligence, Machine Learning, Web Development, Backend Engineering, DevOps, Cloud Computing, Cybersecurity, and Enterprise Applications.
In this lesson, you’ll learn how to configure logging, work with different log levels, save logs to files, format log messages, log exceptions, and implement production-ready logging practices.
By the end of this lesson, you’ll be able to replace print() statements with professional logging techniques suitable for real-world software development.
Learning Objectives
After completing this lesson, you will be able to:
- Understand Python Logging.
- Configure the logging module.
- Use different log levels.
- Write logs to files.
- Format log messages.
- Log exceptions.
- Rotate log files.
- Apply logging in production applications.
Topics Covered
- Introduction to Logging
- Why Logging is Important
- Logging Module
- Log Levels
- Log Formatting
- Logging to Files
- Exception Logging
- Rotating Log Files
- Best Practices
Detailed Lesson Content
Introduction to Logging
Imagine you’re developing an AI-Based Student Portal.
Thousands of users log in every day.
Sometimes users report:
- Login failures
- Payment errors
- Server crashes
- API failures
- Database issues
Using:
print("Error")
is not enough because the message disappears once the program ends.
Instead, professional developers save events inside Log Files.
Example:
2026-07-10 09:45:11
INFO
Student Login Successful
2026-07-10 09:46:22
ERROR
Database Connection Failed
This process is called Logging.
What is Logging?
Logging is the process of recording events that occur while a program is running.
Logs help developers:
- Debug programs
- Monitor applications
- Identify errors
- Analyze system performance
- Maintain security audits
Importing the Logging Module
import logging
Basic Logging
import logging
logging.warning("This is a warning message")
Output
WARNING:root:This is a warning message
Log Levels
Python provides several logging levels.
| Level | Purpose |
|---|---|
| DEBUG | Detailed debugging information |
| INFO | General application events |
| WARNING | Potential problems |
| ERROR | Errors preventing execution |
| CRITICAL | Serious system failures |
Logging Different Levels
import logging
logging.debug("Debug Message")
logging.info("Information")
logging.warning("Warning")
logging.error("Error")
logging.critical("Critical Error")
Configuring Logging
import logging
logging.basicConfig(
level=logging.DEBUG
)
logging.debug("Application Started")
Now all messages from DEBUG level and above will be displayed.
Logging to a File
Instead of displaying messages on the screen, save them to a file.
import logging
logging.basicConfig(
filename="application.log",
level=logging.INFO
)
logging.info("Application Started")
A file named:
application.log
is created automatically.
Formatting Log Messages
import logging
logging.basicConfig(
filename="application.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
logging.info("Student Login Successful")
Output inside log file
2026-07-10 09:40:22
INFO
Student Login Successful
Useful Format Specifiers
| Specifier | Description |
|---|---|
%(asctime)s |
Date & Time |
%(levelname)s |
Log Level |
%(message)s |
Log Message |
%(filename)s |
File Name |
%(lineno)d |
Line Number |
%(funcName)s |
Function Name |
Logging Exceptions
import logging
try:
result = 10 / 0
except Exception as error:
logging.error(error)
Output
ERROR
division by zero
Logging Complete Exception Details
import logging
try:
number = 10/0
except Exception:
logging.exception(
"Exception Occurred"
)
This records:
- Error message
- Stack trace
- Line number
making debugging much easier.
Rotating Log Files
Large applications generate huge log files.
Python provides:
from logging.handlers import RotatingFileHandler
Example
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler(
"app.log",
maxBytes=10000,
backupCount=3
)
logger = logging.getLogger()
logger.addHandler(handler)
logger.warning("Application Started")
When the file reaches the specified size, a new backup log file is created automatically.
Real-World Example 1: Student Login
import logging
logging.basicConfig(
filename="student.log",
level=logging.INFO
)
logging.info(
"Student Rahul Logged In"
)
Real-World Example 2: Payment Gateway
import logging
try:
payment = 1000
print(payment)
except Exception:
logging.exception(
"Payment Failed"
)
Real-World Example 3: API Monitoring
import logging
logging.info(
"API Request Sent"
)
logging.info(
"Response Received"
)
Real-World Example 4: AI Model Training
import logging
logging.info(
"Training Started"
)
logging.info(
"Epoch 1 Completed"
)
logging.info(
"Training Finished"
)
Logs help monitor long-running AI training processes.
Logging vs print()
| print() | logging |
|---|---|
| Temporary output | Permanent records |
| Console only | Console and Files |
| No log levels | Multiple log levels |
| No timestamps | Supports timestamps |
| Not suitable for production | Production ready |
Professional software should use logging instead of print() for application monitoring.
Common Mistakes
Using print() Instead of Logging
Incorrect
print("Error")
Correct
logging.error("Error")
Logging Sensitive Information
Avoid logging:
- Passwords
- OTPs
- Credit Card Numbers
- API Keys
- Personal Information
Using the Wrong Log Level
Use:
- DEBUG → Development
- INFO → Normal events
- WARNING → Potential issues
- ERROR → Failures
- CRITICAL → System crashes



