1. Log level: precise control of log information
The logging module defines five standard log levels: DEBUG, INFO, WARNING, ERROR, and CRITICAL. These levels determine the importance and severity of messages to be logged. By default, logging only logs messages of level WARNING and above. You can fine-tune the behavior of logging by setting the logger's level. For example:
import logging # 设置 root 日志器的级别为 INFO logging.basicConfig(level=logging.INFO)
2. Log format: Customized log output
The logging module provides a powerful log formatting mechanism that allows you to customize the appearance of log messages. Format StringSpecifies the information contained in the log message, such as timestamp, log level, message text, and stack trace. The default format is:
"[%(asctime)s] %(levelname)s %(module)s.%(funcName)s: %(message)s"
You can customize the format using the following code:
# 设置自定义日志格式 logging.basicConfig(fORMat="%(asctime)s %(levelname)-8s %(message)s")
3. Log processor: Extended log output destination
The processor is responsible for sending log messages to a specific destination, such as a file, console, or remote server . The logging module provides several built-in handlers such as StreamHandler and FileHandler.
Creating custom processors is also very simple. You need to create a class and override the handle method which writes the log message to the target. For example, to write logs to a custom file:
class MyFileHandler(logging.FileHandler): def __init__(self, filename): super().__init__(filename) # 将自定义处理器添加到 root 日志器 logging.getLogger().addHandler(MyFileHandler("my_log.txt"))
4. Log filter: filter unnecessary log messages
Filters allow you to filter log messages based on specific criteria. You can create filters based on log level, message text, or other criteria. Filters can be attached to processors to allow only messages that meet criteria to pass through.
For example, a filter that ignores messages with level WARNING:
import logging # 创建筛选器忽略 WARNING 级别的消息 filter = logging.Filter() filter.filter = lambda record: record.levelno < logging.WARNING # 将筛选器添加到 root 日志器的处理器 logging.getLogger().handlers[0].addFilter(filter)
5. Log context management: elegant logging
logging.LoggerContextManager The context manager provides a concise way to log messages in blocks. This is useful for temporarily changing log levels or disabling logging.
with logging.LoggerContextManager(): # 临时将日志级别设置为 DEBUG logging.getLogger().setLevel(logging.DEBUG) # 在块内记录 DEBUG 级的消息 logging.debug("调试信息")
6. Advanced skills:
in conclusion:
python The logging module is a powerful tool that can be used to efficiently log application activities. By understanding log levels, log formats, log processors, log filters, and advanced techniques, you can take full advantage of logging's capabilities and create flexible and meaningful logging solutions for your applications.
The above is the detailed content of Python logging module decrypted: revealing its unknown side. For more information, please follow other related articles on the PHP Chinese website!