ubuntu

Ubuntu中Python日志如何配置与管理

小樊
43
2025-06-13 08:31:01
栏目: 编程语言

在Ubuntu系统中,Python日志的配置和管理可以通过以下几种方法实现:

1. 使用Python内置的logging模块

Python标准库中的logging模块提供了灵活且强大的日志记录功能。以下是一个基本的配置示例:

import logging

# 配置日志记录器
logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # 日志格式
    datefmt='%Y-%m-%d %H:%M:%S',  # 时间格式
    filename='app.log',  # 日志文件名
    filemode='a'  # 文件模式(追加)
)

# 获取日志记录器实例
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')

2. 使用配置文件进行日志管理

你可以使用配置文件(如JSON、YAML或INI格式)来管理日志配置,这样可以更方便地进行修改和维护。

示例:使用JSON配置文件

config.json

{
    "version": 1,
    "formatters": {
        "standard": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        }
    },
    "handlers": {
        "file": {
            "class": "logging.FileHandler",
            "filename": "app.log",
            "level": "DEBUG",
            "formatter": "standard",
            "mode": "a"
        }
    },
    "loggers": {
        "": {
            "handlers": ["file"],
            "level": "DEBUG",
            "propagate": true
        }
    }
}

Python代码

import logging
import json

# 读取配置文件
with open('config.json', 'r') as f:
    config = json.load(f)

# 配置日志记录器
logging.config.dictConfig(config)

# 获取日志记录器实例
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')

3. 使用第三方库进行日志管理

有一些第三方库提供了更高级的日志管理功能,例如loguru

示例:使用loguru

from loguru import logger

# 配置日志记录器
logger.add("app.log", rotation="500 MB", level="DEBUG")

# 记录不同级别的日志
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')

4. 管理日志文件

示例:日志轮转

import logging
from logging.handlers import RotatingFileHandler

# 配置日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建一个RotatingFileHandler,最大文件大小为1MB,保留3个备份
handler = RotatingFileHandler('app.log', maxBytes=1*1024*1024, backupCount=3)
handler.setLevel(logging.DEBUG)

# 设置日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# 添加处理器到记录器
logger.addHandler(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')

通过以上方法,你可以在Ubuntu系统中灵活地配置和管理Python日志。

0
看了该问题的人还看了