Table of Contents
Beginner’s Guide
LogLogger" >SettingsLogLogger
Record log messages
Log format
Intermediate Guide
Log Hierarchy and Propagator
Log filter
Advanced Guide
Log rotation
Custom log handle
in conclusion
Home Backend Development Python Tutorial Python logging module: An advanced guide for beginners to masters

Python logging module: An advanced guide for beginners to masters

Mar 08, 2024 am 08:20 AM

Python logging 模块:初学者到大师的进阶指南

Beginner’s Guide

The

logging module provides a convenient api for setting up loggers. The logger will be responsible for processing the log messages and writing them to a file or console:

import logging

# 创建一个名为 "my_logger" 的日志记录器
logger = logging.getLogger("my_logger")

# 设置日志级别为 DEBUG,表示要记录所有级别的日志消息
logger.setLevel(logging.DEBUG)
Copy after login

Record log messages

To log log messages, use the debug(), info(), warning(), error( provided by the logger ) or critical() method. Each method corresponds to a different log level:

logger.debug("这是 debug 消息")
logger.info("这是 info 消息")
logger.warning("这是 warning 消息")
logger.error("这是 error 消息")
logger.critical("这是 critical 消息")
Copy after login

Log format

By default, the logging module uses a simple log format, including log level, timestamp and message. You can customize the log format to include additional information such as function name, line number, or process ID:

# 使用 %(asctime)s、%(levelname)s 和 %(message)s 占位符自定义日志格式
fORMatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

# 将格式器添加到日志记录器
logger.addHandler(logging.StreamHandler())
logger.addHandler(logging.FileHandler("my_log.log"))
Copy after login

Intermediate Guide

Log Hierarchy and Propagator

The logging module supports logging hierarchies, where loggers can have parents and children. The parent logger will log all messages in the child logger:

# 创建一个名为 "parent_logger" 的父级日志记录器
parent_logger = logging.getLogger("parent_logger")

# 创建一个名为 "child_logger" 的子级日志记录器
child_logger = logging.getLogger("parent_logger.child_logger")

# 设置子级日志记录器的日志级别为 INFO,表示仅记录 info 和更高级别的消息
child_logger.setLevel(logging.INFO)

# 父级日志记录器中的消息将传播到子级日志记录器
parent_logger.info("父级日志记录器消息")
child_logger.info("子级日志记录器消息")
Copy after login

Log filter

You can use log filters to control which log messages are logged or propagated. Filters can be based on log level, message content, or other properties:

# 创建一个过滤器,仅允许记录 error 级别及以上的消息
filter = logging.Filter()
filter.filter = lambda record: record.levelno >= logging.ERROR

# 将过滤器添加到日志记录器
logger.addFilter(filter)
Copy after login

Advanced Guide

Log rotation

Log rotation can automatically manage and split log files when they become too large. You can set a maximum log file size or keep a certain number of log files:

# 使用 RotatingFileHandler 设置日志轮转,最大日志文件大小为 10MB
handler = logging.handlers.RotatingFileHandler("my_log.log", maxBytes=10240000)

# 将处理程序添加到日志记录器
logger.addHandler(handler)
Copy after login

Custom log handle

The logging module allows you to create your own log handlers, providing greater flexibility. You can use <strong class="keylink">Socket</strong>Handler to send log messages to a remote server, or use TimedRotatingFileHandler to rotate log files based on time intervals instead of file size :

# 创建一个自定义日志句柄,将日志消息发送到远程服务器
handler = logging.handlers.SocketHandler("localhost", 1234)

# 将处理程序添加到日志记录器
logger.addHandler(handler)
Copy after login

in conclusion

python The logging module is a powerful and flexible tool that can significantly improve the logging and debugging capabilities of your program. By understanding and using the techniques described in this guide, you'll be able to effectively manage logs, troubleshoot problems, and ensure your programs run stably and reliably.

The above is the detailed content of Python logging module: An advanced guide for beginners to masters. 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 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 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 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