Debugging and error tracking are fundamental aspects of software development. While small-scale Python projects might get by with simple print() statements, professional-grade applications require a more robust and scalable method. Python provides a powerful and flexible logging system through its built-in logging module. This logging system is capable of tracking errors, debugging issues, monitoring runtime behavior, and facilitating long-term maintenance and auditing.
import logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Application started")
The above command will print:
INFO:root:Application started
Here, "INFO" is the severity level, and "root" is the logger name.
Logging levels define the severity of the message. They help filter out unnecessary information and focus on important events.
| Level | Value | Description |
|---|---|---|
| DEBUG | 10 | Detailed information for diagnosing problems. |
| INFO | 20 | General information about program execution. |
| WARNING | 30 | Something unexpected happened, but the program continues. |
| ERROR | 40 | A serious issue occurred that needs attention. |
| CRITICAL | 50 | Severe error indicating the program may not continue running. |
logging.basicConfig(level=logging.WARNING)
Only logs with level WARNING and above will be shown.
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
Example output:
INFO:Application started
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG
)
Output:
2025-06-23 12:00:00,123 - root - DEBUG - Application started
logging.basicConfig(filename='app.log', level=logging.DEBUG)
Now all logs are saved to app.log instead of being displayed in the console.
filemode='a' # Append (default)
filemode='w' # Overwrite
Handlers define where the logs go: file, console, or other outputs.
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('my_app.log')
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
logger.debug("Debug message")
try:
1 / 0
except ZeroDivisionError:
logging.exception("Exception occurred")
Equivalent to:
logging.error("Exception occurred", exc_info=True)
ERROR:root:Exception occurred
Traceback (most recent call last):
File "script.py", line 2, in <module>
1 / 0
ZeroDivisionError: division by zero
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler('app.log', maxBytes=2000, backupCount=3)
logger = logging.getLogger()
logger.addHandler(handler)
Creates new log files after 2 KB and keeps 3 old files.
from logging.handlers import TimedRotatingFileHandler
handler = TimedRotatingFileHandler('timed.log', when='midnight', interval=1, backupCount=7)
Creates a new log file at midnight and keeps 7 days of logs.
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)
logger.info("Custom logger message")
class InfoFilter(logging.Filter):
def filter(self, record):
return record.levelno == logging.INFO
handler.addFilter(InfoFilter())
Useful for log aggregation tools:
formatter = logging.Formatter(
'{"time": "%(asctime)s", "level": "%(levelname)s", "message": "%(message)s"}'
)
Each module should have its own logger:
logger = logging.getLogger(__name__)
class Example:
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
def run(self):
self.logger.info("Running method")
import logging.config
LOGGING_CONFIG = {
'version': 1,
'formatters': {
'simple': {
'format': '%(asctime)s - %(levelname)s - %(message)s',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger(__name__)
logger.info("Message with dict config")
logging.disable(logging.CRITICAL)
Disables all messages at CRITICAL level and below.
from flask import Flask
import logging
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
app.logger.info("Flask app started")
LOGGING = {
'version': 1,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'django.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
Effective logging is a cornerstone of robust software development. Pythonβs logging module offers a powerful toolkit for developers to monitor applications, diagnose issues, and track errors. By using structured, leveled, and flexible log configurations, developers can ensure smooth operations and quick issue resolution. Whether you are writing a small script or developing a large web application, incorporating proper logging practices from the beginning will make your code more maintainable, traceable, and professional.
Start using logging in all your Python applicationsβit is an essential skill for any serious Python developer.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved