Table of Contents
LogLevel" >1. Customize LogLevel
2. Use different processors
3. Use filters
4. Format log output
5. Using context processor
6. Use dictionary configuration
7. Integrate third-party packages
Multi-threadingSupport" >8. Use Multi-threadingSupport
9. Record exceptions
10. Using extended logging
Home Backend Development Python Tutorial 10 Tips for Mastering the Python Logging Module

10 Tips for Mastering the Python Logging Module

Feb 21, 2024 am 09:30 AM
python debug logging Maintainability

掌握 Python Logging 模块的 10 个技巧

In addition to the default DEBUG, INFO, WARNING, ERROR and CRITICAL levels, you can create custom levels. This is useful for differentiating events of varying severity.

import logging

# 创建自定义日志级别
CUSTOM_LEVEL = logging.INFO + 5
logging.addLevelName(CUSTOM_LEVEL, "CUSTOM")

# 创建一个 Logger 并设置自定义日志级别
logger = logging.getLogger("my_logger")
logger.setLevel(CUSTOM_LEVEL)
Copy after login

2. Use different processors

The processor is responsible for sending log events to a specific destination, such as a file or console. You can customize the processor to meet your specific needs.

import logging

# 创建一个 FileHandler 并设置日志文件名
file_handler = logging.FileHandler("my_log.txt")

# 创建一个 StreamHandler 并输出到控制台
stream_handler = logging.StreamHandler()

# 将处理器添加到 Logger
logger = logging.getLogger("my_logger")
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
Copy after login

3. Use filters

Filters allow you to filter log events based on specific criteria. This is useful for logging only events of interest.

import logging

# 创建一个过滤器以过滤 INFO 级别以上的事件
info_filter = logging.Filter()
info_filter.filter = lambda record: record.levelno >= logging.INFO

# 将过滤器添加到 Logger
logger = logging.getLogger("my_logger")
logger.addFilter(info_filter)
Copy after login

4. Format log output

You can customize the format of log events to provide the required information.

import logging

# 创建一个 FORMatter 并设置格式字符串
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

# 将 Formatter 添加到处理器
handler = logging.StreamHandler()
handler.setFormatter(formatter)

# 将处理器添加到 Logger
logger = logging.getLogger("my_logger")
logger.addHandler(handler)
Copy after login

5. Using context processor

Context processors allow you to add additional information when logging. This is useful for tracking context within a request or transaction.

import logging
from contextlib import contextmanager

# 创建一个上下文处理器以添加请求 ID
@contextmanager
def request_id_context(request_id):
previous_request_id = logging.currentframe().f_locals.get("request_id")
try:
logging.currentframe().f_locals["request_id"] = request_id
yield
finally:
logging.currentframe().f_locals["request_id"] = previous_request_id

# 使用上下文处理器
logger = logging.getLogger("my_logger")
with request_id_context("1234"):
logger.info("Received request")
Copy after login

6. Use dictionary configuration

You can easily configure the Logging module using a dictionary.

import logging

# 配置字典
logging_config = {
"version": 1,
"formatters": {
"default": {
"format": "%(asctime)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"file": {
"class": "logging.FileHandler",
"filename": "my_log.txt",
"formatter": "default",
},
"console": {
"class": "logging.StreamHandler",
"formatter": "default",
}
},
"loggers": {
"my_logger": {
"handlers": ["file", "console"],
"level": "INFO",
}
}
}

# 从字典配置 Logging
logging.config.dictConfig(logging_config)
Copy after login

7. Integrate third-party packages

The Logging module can be integrated with third-party packages such as Sentry or Rollbar. This allows you to easily send log events to a remote service.

import logging
import sentry_sdk

# 初始化 Sentry 并与 Logging 集成
sentry_sdk.init()
logging.basicConfig(level=logging.INFO, handlers=[sentry_sdk.handler.SentryHandler()])
Copy after login

Logging module supports multi-threaded applications. It uses thread local storage to ensure that each thread has its own independent log processor.

import logging
import threading

# 创建线程安全的 Logger
logger = logging.getLogger("my_logger")

# 创建一个线程并向 Logger 记录
def thread_function():
logger.info("Executing in a separate thread")

# 启动线程
thread = threading.Thread(target=thread_function)
thread.start()
Copy after login

9. Record exceptions

Logging module can automatically record exceptions that occur.

import logging

# 创建一个 Logger
logger = logging.getLogger("my_logger")

# 记录一个异常
try:
raise Exception("An error occurred")
except Exception as e:
logger.exception(e)
Copy after login

10. Using extended logging

python 3.8 introduces support for extended logging. This allows you to create custom logging functions and handlers.

import logging

# 创建一个自定义日志记录函数
def my_log_function(logger, level, msg, *args, **kwargs):
# 您的自定义日志记录逻辑

# 添加自定义日志记录函数到 Logger
logger = logging.getLogger("my_logger")
logger.addHandler(logging.NullHandler())
logger.addFilter(logging.Filter())
logger.log = my_log_function
Copy after login

The above is the detailed content of 10 Tips for Mastering the Python Logging Module. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles