GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — Python - Logging
Selected Reading
Python - LoggingLogging in PythonLogging 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. Benefits of LoggingFollowing are the benefits of using logging in Python −
Components of Python LoggingPython logging consists of several key components that work together to manage and output log messages effectively −
Logging LevelsLogging 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 −
UsageFollowing are the usage scenarios for each logging level in Python applications − Choosing the Right Level − Selecting the appropriate logging level ensures that log messages provide relevant information without cluttering the logs. Setting Levels − Loggers, handlers, and specific log messages can be configured with different levels to control which messages are recorded and where they are outputted. Hierarchy − Logging levels are hierarchical, meaning that setting a level on a logger also affects the handlers and log messages associated with it. Basic Logging ExampleFollowing is a basic logging example in Python to demonstrate its usage and functionality − 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")
OutputFollowing 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 LoggingConfiguring 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. ExampleIn 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 − 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')
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 HandlersLogging 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. Types of Logging HandlersFollowing are the various types of logging handlers in Python −
Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |