


Python logging module: An advanced guide for beginners to masters
Beginner’s Guide
SettingsLogLogger
Thelogging 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)
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 消息")
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"))
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("子级日志记录器消息")
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)
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)
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)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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? 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 within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

Using python in Linux terminal...

Fastapi ...

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