【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应用程序中记录和调试的重要工具,灵活配置和使用该模块可以帮助开发者更好地了解和维护代码。

相关推荐
APIshop2 分钟前
API 接口文档测试:从“能跑”到“敢上线”的完整闭环
爬虫·python
AndrewHZ2 分钟前
【复杂网络分析】如何入门Louvain算法?
python·算法·复杂网络·社区发现·community det·louvain算法·图挖掘
froginwe112 分钟前
SQLite Indexed By
开发语言
虾说羊3 分钟前
JVM 高频面试题全解析
java·开发语言·jvm
沈浩(种子思维作者)6 分钟前
梦境意识之谜——豆包补充
人工智能·python·量子计算
毕设源码-赖学姐16 分钟前
【开题答辩全过程】以 基于PHP的国学诗词网站与推荐系统的设计与实现为例,包含答辩的问题和答案
开发语言·php
盼哥PyAI实验室17 分钟前
[特殊字符]️ 实战爬虫:Python 抓取【采购公告】接口数据(含踩坑解析)
开发语言·爬虫·python
Hello.Reader17 分钟前
Flink ML VectorAssembler 把多列特征“拼”成一个向量列(数值 + 向量都支持)
java·python·flink
wjs202420 分钟前
PostgreSQL NULL 值处理与优化
开发语言
Csvn21 分钟前
🐫 Ollama 基础使用指南
人工智能·python