Table of Contents
ToggleLogging is the process of recording messages during the execution of a program to provide runtime information that can be useful for monitoring, debugging, and auditing.
In Python, logging is achieved through the built-in logging module, which provides a flexible framework for generating log messages.
Following are the benefits of using logging in Python −
Python logging consists of several key components that work together to manage and output log messages effectively −
Logging levels in Python define the severity of log messages, allowing developers to categorize and filter messages based on their importance. Each logging level has a specific purpose and helps in understanding the significance of the logged information −
Following are the usage scenarios for each logging level in Python applications −
Following is a basic logging example in Python to demonstrate its usage and functionality −
# Open Compiler
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Example usage
def calculate_sum(a, b):
logging.debug(f"Calculating sum of {a} and {b}")
result = a + b
logging.info(f"Sum calculated successfully: {result}")
return result
# Main program
if __name__ == "__main__":
logging.info("Starting the program")
result = calculate_sum(10, 20)
logging.info("Program completed")
Output:
Following is the output of the above code −
2024-06-19 09:00:06,774 – INFO – Starting the program
2024-06-19 09:00:06,774 – DEBUG – Calculating sum of 10 and 20
2024-06-19 09:00:06,774 – INFO – Sum calculated successfully: 30
2024-06-19 09:00:06,775 – INFO – Program completed
Configuring logging in Python refers to setting up various components such as loggers, handlers, and formatters to control how and where log messages are stored and displayed. This configuration allows developers to customize logging behavior according to their application’s requirements and deployment environment.
In the following example, the getLogger() function retrieves or creates a named logger. Loggers are organized hierarchically based on their names. Then, handlers like “StreamHandler” (console handler) are created to define where log messages go. They can be configured with specific log levels and formatters.
The formatters specify the layout of log records, determining how log messages appear when printed or stored −
# Open Compiler
import logging
# Create logger
logger = logging.getLogger('my_app')
logger.setLevel(logging.DEBUG) # Set global log level
# Create console handler and set level to debug
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# Add console handler to logger
logger.addHandler(console_handler)
# Example usage
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')
Output:
The result produced is as shown below −
2024-06-19 09:05:20,852 – my_app – DEBUG – This is a debug message
2024-06-19 09:05:20,852 – my_app – INFO – This is an info message
2024-06-19 09:05:20,852 – my_app – WARNING – This is a warning message
2024-06-19 09:05:20,852 – my_app – ERROR – This is an error message
2024-06-19 09:05:20,852 – my_app – CRITICAL – This is a critical message
Logging handlers in Python determine where and how log messages are processed and outputted. They play an important role in directing log messages to specific destinations such as the console, files, email, databases, or even remote servers.
Each handler can be configured independently to control the format, log level, and other properties of the messages it processes.
Following are the various types of logging handlers in Python −
Key Takeaway: Master logging in Python—track runtime with the logging module—at Vista Academy!
