Home Backend Development Python Tutorial The secret recipe of Python's logging module: building an efficient logging system

The secret recipe of Python's logging module: building an efficient logging system

Mar 08, 2024 am 08:40 AM

Python logging 模块的秘密配方:打造高效日志系统

python The logging module is a powerful and versatile tool that can be used for logging in Python applications and admin log messages. By mastering the secret recipe of the logging module, you can create an efficient and easy-to-maintain logging system that improves the reliability and debuggability of your application.

Custom log level

The logging module provides a set of predefined log levels, including DEBUG, INFO, WARNING, ERROR, and CRITICAL. You can customize these levels to create a more granular logging hierarchy based on your application's needs. For example, you can add a custom level, such as "TRACE", to log detailed events that occur in your application.

import logging

# 创建自定义日志级别
TRACE = logging.DEBUG - 5
logging.addLevelName(TRACE, "TRACE")

# 创建一个使用自定义级别的日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(TRACE)
Copy after login

Use multiple log handlers

The log handler is responsible for sending log messages to different destinations, such as a file, the console, or a remote server . The logging module provides a range of built-in handlers, and you can create custom handlers to meet your specific needs. Using multiple handlers, you can log messages to multiple targets simultaneously, providing more comprehensive logging.

# 创建一个文件处理程序
file_handler = logging.FileHandler("my_log.log")

# 创建一个控制台处理程序
console_handler = logging.StreamHandler()

# 为日志记录器添加处理程序
logger.addHandler(file_handler)
logger.addHandler(console_handler)
Copy after login

Log format

The log format specifies the structure and layout of the log message. The logging module provides a flexible formatting system that allows you to customize the appearance of log messages. Using the log format, you can include information such as message content, timestamp, log level, and calling code source.

# 创建一个自定义日志格式
fORMatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# 将格式应用于处理程序
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
Copy after login

Filter log messages

The logging module allows you to filter log messages and only log messages that match certain criteria. Filters can be created based on log level, message content, or other custom criteria. Filtering log messages can reduce log output and ensure that only messages useful for debugging or analysis are logged.

# 创建一个过滤器以只记录 ERROR 和 CRITICAL 消息
filter = logging.Filter()
filter.filter = lambda record: record.levelno >= logging.ERROR

# 将过滤器应用于一个处理程序
file_handler.addFilter(filter)
Copy after login

Log propagation

Log propagation controls how log messages are propagated. By default, log messages are propagated to all loggers in the application that contain handlers. However, you can control the flow of messages through the logger hierarchy by configuring log propagation. This helps prevent duplicate and redundant log messages.

# 禁用日志传播
logger.propagate = False
Copy after login

Log rotation

Log rotation limits the maximum size of a single log file, preventing the file from becoming too large to manage. The logging module provides a FileHandler class that supports automatic log rotation and creates new log files when the log file reaches a specified size or time limit.

# 创建一个带日志旋转的文件处理程序
file_handler = logging.handlers.RotatingFileHandler("my_log.log", maxBytes=1024, backupCount=5)
Copy after login

Performance optimization

The logging module incurs some overhead when recording log messages. To optimize performance, you can use the following tips:

  • Only log information useful for debugging or analysis.
  • Use filters to reduce log output.
  • Use efficient log format.
  • Avoid frequent creation and destruction of loggers.
  • Use an asynchronous logger to reduce main thread blocking.

By mastering these secret recipes of the Python logging module, you can create powerful logging systems and improve the reliability and debuggability of your applications.

The above is the detailed content of The secret recipe of Python's logging module: building an efficient logging system. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles