VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • 使用 Python logging 模块记录不同级别的日志

使用 Python logging 模块记录不同级别的日志

在 Python 中,logging 模块提供了灵活的日志记录功能,可以记录不同级别的日志信息。通过合理配置,可以将不同级别的日志输出到不同的位置,方便开发和运维人员进行问题排查和系统监控。本文将详细介绍如何使用 logging 模块记录不同级别的日志。

一、日志级别概述

logging 模块定义了以下日志级别:

  • DEBUG:详细信息,通常用于调试。
  • INFO:确认事情按预期进行。
  • WARNING:表明可能发生了一些意外的事情,但系统仍继续运行。
  • ERROR:由于更严重的问题导致某些功能无法执行。
  • CRITICAL:严重的错误,表明系统可能无法继续运行。

这些级别按严重程度递增,每个级别都有一个对应的整数值:

logging.DEBUG    # 10
logging.INFO     # 20
logging.WARNING  # 30
logging.ERROR    # 40
logging.CRITICAL # 50

二、基本配置

在使用 logging 模块之前,需要进行基本配置。可以使用 logging.basicConfig() 函数来设置日志记录的基本参数,包括日志级别、格式和输出位置。

  1. 设置日志级别

通过 level 参数设置日志级别,只有大于或等于该级别的日志才会被记录。

import logging

logging.basicConfig(level=logging.DEBUG)
  1. 设置日志格式

通过 format 参数设置日志格式,可以包含时间、日志级别、模块、消息等内容。

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
  1. 设置输出位置

通过 filename 参数设置日志输出到文件。

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    filename="app.log"
)

三、记录不同级别的日志

  1. 使用 logger 对象

可以使用 logging.getLogger() 获取一个 logger 对象,用于记录日志。

logger = logging.getLogger(__name__)

logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
  1. 使用 logging 模块的函数

也可以直接使用 logging 模块的函数记录日志。

logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
  1. 示例代码
import logging

# 配置日志记录
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    filename="app.log"
)

# 获取 logger 对象
logger = logging.getLogger(__name__)

# 记录不同级别的日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

# 直接使用 logging 模块的函数
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
  1. 输出结果

在 app.log 文件中,将看到以下输出:

2024-06-05 10:00:00,000 - __main__ - DEBUG - This is a debug message
2024-06-05 10:00:00,000 - __main__ - INFO - This is an info message
2024-06-05 10:00:00,000 - __main__ - WARNING - This is a warning message
2024-06-05 10:00:00,000 - __main__ - ERROR - This is an error message
2024-06-05 10:00:00,000 - __main__ - CRITICAL - This is a critical message
2024-06-05 10:00:00,000 - root - DEBUG - This is a debug message
2024-06-05 10:00:00,000 - root - INFO - This is an info message
2024-06-05 10:00:00,000 - root - WARNING - This is a warning message
2024-06-05 10:00:00,000 - root - ERROR - This is an error message
2024-06-05 10:00:00,000 - root - CRITICAL - This is a critical message

四、高级配置

  1. 使用 FileHandler 和 StreamHandler

可以使用 FileHandler 将日志写入文件,使用 StreamHandler 将日志输出到控制台。

import logging

# 创建 logger 对象
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建文件处理器
file_handler = logging.FileHandler("app.log")
file_handler.setLevel(logging.DEBUG)

# 创建流处理器
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.WARNING)

# 定义日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)

# 添加处理器到 logger
logger.addHandler(file_handler)
logger.addHandler(stream_handler)

# 记录不同级别的日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
  1. 使用 RotatingFileHandler

可以使用 RotatingFileHandler 实现日志文件的轮转,避免日志文件过大。

import logging
from logging.handlers import RotatingFileHandler

# 创建 logger 对象
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建轮转文件处理器
rotating_file_handler = RotatingFileHandler(
    "app.log",
    maxBytes=1024 * 1024,  # 每个日志文件的最大大小为 1MB
    backupCount=5          # 保留 5 个备份文件
)
rotating_file_handler.setLevel(logging.DEBUG)

# 定义日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
rotating_file_handler.setFormatter(formatter)

# 添加处理器到 logger
logger.addHandler(rotating_file_handler)

# 记录不同级别的日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
  1. 使用 TimedRotatingFileHandler

可以使用 TimedRotatingFileHandler 实现基于时间的日志文件轮转。

import logging
from logging.handlers import TimedRotatingFileHandler

# 创建 logger 对象
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建基于时间的轮转文件处理器
timed_rotating_file_handler = TimedRotatingFileHandler(
    "app.log",
    when="D",  # 每天轮转一次
    interval=1,
    backupCount=7
)
timed_rotating_file_handler.setLevel(logging.DEBUG)

# 定义日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
timed_rotating_file_handler.setFormatter(formatter)

# 添加处理器到 logger
logger.addHandler(timed_rotating_file_handler)

# 记录不同级别的日志
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

五、总结

通过合理配置 logging 模块,可以记录不同级别的日志信息,方便开发和运维人员进行问题排查和系统监控。可以使用 FileHandler 和 StreamHandler 将日志写入文件和输出到控制台,使用 RotatingFileHandler 和 TimedRotatingFileHandler 实现日志文件的轮转。希望本文能够帮助您更好地理解和使用 Python 的 logging 模块记录不同级别的日志。

最后,如果你对python语言还有任何疑问或者需要进一步的帮助,请访问https://www.xin3721.com 本站原创,转载请注明出处:https://www.xin3721.com


相关教程