Python 简明教程

Python - Logging

Logging in Python

日志记录是在程序执行期间记录消息的过程,以便提供运行时信息,这些信息对于监视、调试与审核非常有用。

Logging 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.

在 Python 中,日志记录通过内置 logging 模块实现,该模块提供了一个灵活的框架,用于生成日志消息。

In Python, logging is achieved through the built-in logging module, which provides a flexible framework for generating log messages.

Benefits of Logging

以下是使用 Python 进行日志记录的一些好处−

Following are the benefits of using logging in Python −

  1. Debugging − Helps identify and diagnose issues by capturing relevant information during program execution.

  2. Monitoring − Provides insights into the application’s behavior and performance.

  3. Auditing − Keeps a record of important events and actions for security purposes.

  4. Troubleshooting − Facilitates tracking of program flow and variable values to understand unexpected behavior.

Components of Python Logging

Python 日志记录包含几个主要组件,协同工作以有效地管理和输出日志消息 −

Python logging consists of several key components that work together to manage and output log messages effectively −

  1. Logger − It is the main entry point that you use to emit log messages. Each logger instance is named and can be configured independently.

  2. Handler − It determines where log messages are sent. Handlers send log messages to different destinations such as the console, files, sockets, etc.

  3. Formatter − It specifies the layout of log messages. Formatters define the structure of log records by specifying which information to include (e.g., timestamp, log level, message).

  4. Logger Level − It defines the severity level of log messages. Messages below this level are ignored. Common levels include DEBUG, INFO, WARNING, ERROR, and CRITICAL.

  5. Filter − It is the optional components that provide finer control over which log records are processed and emitted by a handler.

Logging Levels

Python 中的日志级别定义了日志消息的严重性,允许开发者根据重要性对消息进行分类和筛选。每个日志级别都有特定的用途,并且有助于理解已记录信息的重要性 −

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 −

  1. DEBUG − Detailed information, typically useful only for debugging purposes. These messages are used to trace the flow of the program and are usually not seen in production environments.

  2. INFO − Confirmation that things are working as expected. These messages provide general information about the progress of the application.

  3. WARNING − Indicates potential issues that do not prevent the program from running but might require attention. These messages can be used to alert developers about unexpected situations.

  4. ERROR − Indicates a more serious problem that prevents a specific function or operation from completing successfully. These messages highlight errors that need immediate attention but do not necessarily terminate the application.

  5. CRITICAL − The most severe level, indicating a critical error that may lead to the termination of the program. These messages are reserved for critical failures that require immediate intervention.

Usage

以下是 Python 应用程序中每个日志级别的使用场景 −

Following are the usage scenarios for each logging level in Python applications −

Choosing the Right Level − 选择适当的日志级别可确保日志消息提供相关信息,而不会使日志混乱。

Choosing the Right Level − Selecting the appropriate logging level ensures that log messages provide relevant information without cluttering the logs.

Setting Levels − 可以使用不同的级别来配置记录器、处理器和特定的日志消息,以控制记录哪些消息以及输出到哪里。

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 − 日志级别是分层的,这意味着在一个记录器上设置一个级别也会影响关联的处理器和日志消息。

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 Example

以下是一个在 Python 中的基本日志记录示例,展示了它的用法和功能 −

Following 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")

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

在 Python 中配置日志记录是指设置记录器、处理器和格式化程序等各种组件,以控制日志消息如何以及在哪里存储和显示。此配置允许开发者根据应用程序的要求和部署环境来自定义日志记录行为。

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.

Example

在以下示例中,getLogger() 函数会检索或创建一个具名的记录器。记录器根据它们的名称按层次组织。然后,创建诸如 "StreamHandler"(控制台处理器)之类的处理器,以定义日志消息的去向。它们可以用特定的日志级别和格式化程序进行配置。

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 −

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 Handlers

Python 中的日志记录处理器决定日志消息如何以及在哪里处理和输出。它们在将日志消息定向到特定目的地(例如控制台、文件、电子邮件、数据库甚至远程服务器)方面发挥着重要作用。

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.

Types of Logging Handlers

以下是 Python 中各种类型的日志记录处理器 −

Following are the various types of logging handlers in Python −

  1. StreamHandler − Sends log messages to streams such as sys.stdout or sys.stderr. Useful for displaying log messages in the console or command line interface.

  2. FileHandler − Writes log messages to a specified file on the file system. Useful for persistent logging and archiving of log data.

  3. RotatingFileHandler − Similar to FileHandler but automatically rotates log files based on size or time intervals. Helps manage log file sizes and prevent them from growing too large.

  4. SMTPHandler − Sends log messages as emails to designated recipients via SMTP. Useful for alerting administrators or developers about critical issues.

  5. SysLogHandler − Sends log messages to the system log on Unix-like systems (e.g., syslog). Allows integration with system-wide logging facilities.

  6. MemoryHandler − Buffers log messages in memory and sends them to a target handler after reaching a certain buffer size or timeout. Useful for batching and managing bursts of log messages.

  7. HTTPHandler − Sends log messages to a web server via HTTP or HTTPS. Enables logging messages to a remote server or logging service.