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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

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

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles