Python logging module decrypted: revealing its unknown side

王林
Release: 2024-03-08 08:19:17
forward
353 people have browsed it

Python logging 模块解密:揭示其不为人知的一面

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)
Copy after login

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"
Copy after login

You can customize the format using the following code:

# 设置自定义日志格式
logging.basicConfig(fORMat="%(asctime)s %(levelname)-8s %(message)s")
Copy after login

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"))
Copy after login

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)
Copy after login

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("调试信息")
Copy after login

6. Advanced skills:

  • Use dictionary configurator: Use dictionary configurator to provide more flexible configuration options.
  • Create your own log levels: Extend the built-in levels by writing a custom log level.
  • Use a logging framework: such as structlog or loguru, which provides advanced functionality and scalability.
  • Asynchronous Logging: Improve the performance of large applications by using asynchronous processors.
  • Logging exceptions: Use logging.exception() or logging.log_exception() to log exception stack traces.

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!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template