溫馨提示×

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. 管理日志文件

  • 日志輪轉:使用logging.handlers.RotatingFileHandlerlogging.handlers.TimedRotatingFileHandler來實現日志文件的自動輪轉。
  • 日志清理:定期清理舊的日志文件,可以使用cron任務來實現。

示例:日志輪轉

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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女