Logging is a crucial practice that helps developers monitor, debug, and maintain their applications. Python, a versatile and widely used programming language, provides a comprehensive logging module that makes it easy to integrate logging into your applications. This post introduces Python logging, covering the basics, various logging levels, practical implementations, and more. By the end of this post, you should have a concrete understanding of Python logging and how to use it effectively in your projects.
Logging in Python refers to the process of recording messages generated by a program’s execution. These messages can provide insights into the program’s flow, errors, performance, and other crucial metrics. The Python logging module provides a versatile structure for generating log messages within Python programs, enabling developers to log messages at different severity levels, direct log output to various destinations, and customize log formats. Monitor everything about your Python applications with one tool here.
The logging module in Python provides various functions and classes to configure logging effectively, including:
Python logging works by creating loggers that generate log messages, handlers that send these messages to designated destinations, formatters that define the structure of the log messages, and filters that control which log records are output. When a logger records a message, it passes through the filters and is sent to the handlers, where it is formatted and finally output to the configured destination such as a file, console, or external logging service. This modular architecture allows flexible and powerful logging configurations to suit various needs.
Python logging has five standard levels of severity to categorize log messages:
Here’s an example demonstrating different logging levels:
import logging
# Configure the logging
# Log messages with different severity levels
logging.debug("This is a debug message.")
logging.info("This is an info message.")
logging.warning("This is a warning message.")
logging.error("This is an error message.")
logging.critical("This is a critical message.")
This code configures logging to display all messages from the DEBUG level and higher.
When you run this code, you will see messages for all severity levels as shown in the figure above since the logging level is set to DEBUG.
To log messages to a file instead of the console, you can configure the logging module with a filename parameter. This is shown below:
import logging
# Configure logging to a file
logging.basicConfig(filename='app.log', level=logging.INFO)
# Log a message
logging.info("This message will be logged to a file.")
This code configures logging to write messages to a file named app.log.
If you want to log messages to stdout, the standard output stream, which is typically the console or terminal where your Python program is running, you can use the stream handler. The code example below shows this:
import logging
import sys
# Configure logging to stdout
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# Log a message
logging.info("This message will be logged to stdout.")
This code configures logging to write messages to stdout.
Logging to the console can be achieved by using the StreamHandler. The code example below shows this:
import logging
# Create a custom logger
logger = logging.getLogger(__name__)
# Create handlers
console_handler = logging.StreamHandler()
# Set level for handlers
console_handler.setLevel(logging.INFO)
# Create formatters and add them to handlers
console_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
# Add handlers to the logger
logger.addHandler(console_handler)
# Log a message
logger.info("This message will be logged to the console.")
This code creates a custom logger, adds a handler for logging to the console, and logs an informational message.
Setting the logging level allows you to control the severity of messages that your application logs. Here are examples on how to set different log levels.
This code sets the log level to DEBUG, so all messages will be logged.
import logging
# Create a logger
logger = logging.getLogger(__name__)
# Set the logging level to DEBUG
logger.setLevel(logging.DEBUG)
# Log messages with different severity levels
logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")
This code sets the log level to WARNING, so only WARNING, ERROR, and CRITICAL messages will be logged.
import logging
# Create a logger
logger = logging.getLogger(__name__)
# Set the logging level to WARNING
logger.setLevel(logging.WARNING)
# Log messages with different severity levels
logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")
This code sets the log level to ERROR, so only ERROR and CRITICAL messages will be logged.
import logging
# Create a logger
logger = logging.getLogger(__name__)
# Set the logging level to ERROR
logger.setLevel(logging.ERROR)
# Log messages with different severity levels
logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
logger.critical("This is a critical message.")
Understanding when and where to use each logging level is crucial for effective logging. Here’s a detailed guide on the practical usage of each logging level in different environments.
We can further summarize each of these log levels into this practical usage:
Python logging is important for several reasons:
To make the most out of Python logging, follow these best practices:
By understanding and implementing best practices, you will enhance the reliability, security, and maintainability of your applications.
Python logging is a powerful tool that aids in developing reliable and maintainable software. By using the features of the logging module, you can create informative log messages that help monitor and debug your applications effectively. Remember to configure logging appropriately, use different logging levels wisely, and follow best practices to ensure your logs serve their intended purpose efficiently. Using products like Stackify Retrace enhances the usefulness of your logs by providing context to performance issues and advance features for fast remediation. Start your free Stackify Retrace trial today.
Theophilus Onyejiaku has over five years of experience as data scientist and a machine learning engineer. His expertise includes data science, machine learning, computer vision, deep learning, object detection, model application development and deployment. He has written over 650 articles in python programming, data analytics, the aforementioned fields, and so much more.
If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]