Home  >  Article  >  Backend Development  >  Python logging module: An advanced guide for beginners to masters

Python logging module: An advanced guide for beginners to masters

王林
王林forward
2024-03-08 08:20:13575browse

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

Beginner’s Guide

SettingsLogLogger

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)

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!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete