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

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

关键概念

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

基本用法

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

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将日志消息写入文件:

file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

配置多个Handler

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

logger.addHandler(console_handler)
logger.addHandler(file_handler)

使用配置文件配置日志

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

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对象,用于不同的模块或子系统:

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方法记录异常堆栈信息:

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Exception occurred")

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

相关推荐

  1. 【Python】Pythonlogging模块介绍示例

    2024-05-14 17:00:03       37 阅读
  2. Pythontqdm模块常用方法示例

    2024-05-14 17:00:03       62 阅读
  3. 如何使用Pythonlogging模块进行日志记录?

    2024-05-14 17:00:03       34 阅读
  4. log4js-node在nodejs项目使用示例

    2024-05-14 17:00:03       54 阅读
  5. Pythontime_symmetrize介绍示例代码

    2024-05-14 17:00:03       56 阅读
  6. SpringBoot常见注解详细介绍,附带代码示例

    2024-05-14 17:00:03       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-14 17:00:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-14 17:00:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-14 17:00:03       82 阅读
  4. Python语言-面向对象

    2024-05-14 17:00:03       91 阅读

热门阅读

  1. 【FFmpeg】调用FFmpeg和SDL2进行解码后渲染播放

    2024-05-14 17:00:03       36 阅读
  2. 申请免费的Let‘s Encrypt 通配符 HTTPS 证书

    2024-05-14 17:00:03       35 阅读
  3. Python实战开发及案例分析(21)—— 广度优先

    2024-05-14 17:00:03       31 阅读
  4. Python数独游戏

    2024-05-14 17:00:03       36 阅读
  5. 【Python系列-01学习路线-01基础】03变量

    2024-05-14 17:00:03       60 阅读
  6. yarn 命令(防止遗忘)

    2024-05-14 17:00:03       31 阅读
  7. 深入理解 MySQL 视图

    2024-05-14 17:00:03       33 阅读
  8. MySQL创建储存过程函数

    2024-05-14 17:00:03       33 阅读
  9. 空格探究 空格ASCII码值不一样

    2024-05-14 17:00:03       29 阅读