【Python】Python中的logging模块介绍和示例

Python中的logging模块是一个强大的内置模块,用于记录和跟踪应用程序的运行过程。它提供了灵活的日志记录功能,可以将日志消息输出到多个目标(如控制台、文件、远程服务器等),并支持不同的日志级别。以下是logging模块的一些关键概念和使用方法:

关键概念

  1. Logger : 日志记录器,用于生成日志消息。应用程序代码中使用logger对象记录日志。
  2. Handler: 处理器,定义日志消息的输出位置(如控制台、文件、网络等)。
  3. Formatter: 格式化器,定义日志消息的格式(如时间戳、日志级别、消息内容等)。
  4. Log Level : 日志级别,用于表示日志消息的严重程度。常见的日志级别有:
    • DEBUG: 详细的调试信息,通常用于诊断问题。
    • INFO: 一般的运行信息,表示程序正常运行。
    • WARNING: 警告信息,表示可能的问题。
    • ERROR: 错误信息,表示发生了严重的问题。
    • CRITICAL: 致命错误信息,表示程序无法继续运行。

基本用法

以下是一个简单的示例,展示了如何使用logging模块记录日志:

python 复制代码
import logging

# 创建一个Logger对象
logger = logging.getLogger('example_logger')
logger.setLevel(logging.DEBUG)  # 设置日志级别

# 创建一个Handler对象,将日志输出到控制台
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)

# 创建一个Formatter对象,定义日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)

# 将Handler添加到Logger
logger.addHandler(console_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')

高级用法

将日志输出到文件

可以使用FileHandler将日志消息写入文件:

python 复制代码
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

配置多个Handler

可以为同一个Logger配置多个Handler,以实现日志消息的多种输出方式:

python 复制代码
logger.addHandler(console_handler)
logger.addHandler(file_handler)

使用配置文件配置日志

可以使用配置文件(如JSON或YAML)配置日志:

python 复制代码
import logging.config
import json

config = {
    "version": 1,
    "formatters": {
        "default": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "default"
        },
        "file": {
            "class": "logging.FileHandler",
            "level": "ERROR",
            "formatter": "default",
            "filename": "app.log"
        }
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console", "file"]
    }
}

logging.config.dictConfig(config)
logger = logging.getLogger()

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

自定义Logger

可以创建多个Logger对象,用于不同的模块或子系统:

python 复制代码
module_logger = logging.getLogger('module_logger')
module_logger.setLevel(logging.INFO)
module_logger.addHandler(console_handler)

module_logger.info('This is an info message from module_logger')

捕获异常信息

可以使用exception方法记录异常堆栈信息:

python 复制代码
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Exception occurred")

logging模块是Python应用程序中记录和调试的重要工具,灵活配置和使用该模块可以帮助开发者更好地了解和维护代码。

相关推荐
野生技术架构师8 分钟前
2026年牛客网最新Java面试题总结
java·开发语言
环黄金线HHJX.9 分钟前
Tuan符号系统重塑智能开发
开发语言·人工智能·算法·编辑器
XLYcmy9 分钟前
一个针对医疗RAG系统的数据窃取攻击工具
python·网络安全·ai·llm·agent·rag·ai安全
dog2509 分钟前
对数的大脑应对指数的世界
开发语言·php
Mr_Xuhhh19 分钟前
深入理解Java抽象类与接口:从概念到实战
java·开发语言
Islucas31 分钟前
Claude code入门保姆级教程
python·bash·claude
萝卜白菜。40 分钟前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
wb0430720141 分钟前
使用 Java 开发 MCP 服务并发布到 Maven 中央仓库完整指南
java·开发语言·spring boot·ai·maven
Rsun0455142 分钟前
设计模式应该怎么学
java·开发语言·设计模式