Python logging module knowledge points revealed: common questions all in one place

王林
Release: 2024-03-08 08:00:14
forward
625 people have browsed it

Python logging 模块知识点大揭秘:常见问题一网打尽

python logging module basics

The basic principle of the logging module is to create a logger (logger) and then record messages by calling the logger method. A logger has a level that determines which messages will be logged. The logging module defines several predefined levels, including DEBUG, INFO, WARNING, ERROR, and CRITICAL.

import logging

# 创建一个名为 "my_logger" 的记录器,并设置其级别为 INFO
logger = logging.getLogger("my_logger")
logger.setLevel(logging.INFO)
Copy after login

A logger can log messages through its methods:

# 记录一条 INFO 级别的消息
logger.info("This is an INFO message")

# 记录一条 WARNING 级别的消息
logger.warning("This is a WARNING message")

# 记录一条 ERROR 级别的消息
logger.error("This is an ERROR message")
Copy after login

LogHandler

The log handler (handler) writes log messages to a specific destination, such as the console, file, or Networkserver. The logging module provides several predefined handlers:

# 创建一个控制台处理程序
handler = logging.StreamHandler()

# 创建一个文件处理程序,将日志写入文件 "my_log.txt"
handler = logging.FileHandler("my_log.txt")
Copy after login

Handlers can be attached to the logger by adding to the logger:

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

Log formatter

The log formatter (fORMatter) controls the appearance of log messages. The logging module provides several predefined formatters:

# 创建一个基本格式器
formatter = logging.BasicFormatter()

# 使用自定义格式字符串创建自定义格式器
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Copy after login

Formatters can be attached to handlers by adding to the handler:

# 将格式器添加到处理程序
handler.setFormatter(formatter)
Copy after login

common problem

1. How to set logging level in Python script?

import logging

# 设置根日志记录器的级别为 INFO
logging.basicConfig(level=logging.INFO)
Copy after login

2. How to log exceptions?

try:
# 尝试执行一些代码
except Exception as e:
# 记录异常
logger.error(e, exc_info=True)
Copy after login

3. How to disable a specific handler?

# 禁用控制台处理程序
logger.removeHandler(handler)
Copy after login

4. How to use custom log format?

# 使用自定义格式字符串创建自定义格式器
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# 将格式器添加到处理程序
handler.setFormatter(formatter)
Copy after login

5. How to catch uncaught exceptions and log them to a file?

import sys
import logging

def exception_handler(type, value, traceback):
# 记录未捕获的异常
logger.error(value, exc_info=(type, value, traceback))

sys.excepthook = exception_handler
Copy after login

in conclusion

Python The logging module is a powerful tool that can help you easily log and process application messages. By mastering its key points, you can effectively use the logging module to debug, troubleshoot, and analyze the behavior of your application.

The above is the detailed content of Python logging module knowledge points revealed: common questions all in one place. For more information, please follow other related articles on the PHP Chinese website!

source:lsjlt.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!