插件窝 干货文章 Linux Swagger如何进行错误处理与日志记录

Linux Swagger如何进行错误处理与日志记录

错误 request response error 507    来源:    2025-05-06

Linux环境下Swagger的错误处理与日志记录方案

错误处理

1. 全局异常处理

在基于Swagger的API应用中,推荐使用全局异常处理机制:

# Python Flask示例
from flask import jsonify
from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # 如果是HTTP异常,返回标准HTTP响应
    if isinstance(e, HTTPException):
        response = {
            "error": e.name,
            "message": e.description,
            "status": e.code
        }
        return jsonify(response), e.code

    # 非HTTP异常的统一处理
    response = {
        "error": "Internal Server Error",
        "message": str(e),
        "status": 500
    }
    return jsonify(response), 500

2. Swagger文档中的错误定义

在Swagger/OpenAPI规范中明确定义可能的错误响应:

paths:
  /users/{id}:
    get:
      responses:
        '200':
          description: 成功获取用户信息
        '404':
          description: 用户不存在
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: 服务器内部错误
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        error:
          type: string
        message:
          type: string
        status:
          type: integer

3. 验证错误处理

对于请求参数验证错误:

# Python示例
from flask import request
from flasgger.utils import swag_from

@app.route('/api/data', methods=['POST'])
@swag_from('swagger_docs/data_post.yml')
def post_data():
    data = request.get_json()
    if not data or 'required_field' not in data:
        return {
            "error": "Validation Error",
            "message": "required_field is missing",
            "status": 400
        }, 400
    # 处理逻辑...

日志记录

1. 结构化日志配置

import logging
from pythonjsonlogger import jsonlogger

def setup_logging():
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    # 创建JSON格式的日志处理器
    logHandler = logging.StreamHandler()
    formatter = jsonlogger.JsonFormatter(
        '%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)s %(message)s'
    )
    logHandler.setFormatter(formatter)
    logger.addHandler(logHandler)

    return logger

logger = setup_logging()

2. 记录API请求和响应

@app.after_request
def after_request(response):
    # 记录请求信息
    logger.info("Request processed", extra={
        "path": request.path,
        "method": request.method,
        "status": response.status_code,
        "remote_addr": request.remote_addr,
        "user_agent": str(request.user_agent),
        "response_time": (datetime.now() - request.start_time).total_seconds()
    })
    return response

3. 错误日志记录

@app.errorhandler(Exception)
def handle_exception(e):
    # 记录错误详情
    logger.error("API error occurred", exc_info=True, extra={
        "error_type": type(e).__name__,
        "error_message": str(e),
        "request_path": request.path,
        "request_method": request.method
    })

    # 返回错误响应
    if isinstance(e, HTTPException):
        response = {
            "error": e.name,
            "message": e.description,
            "status": e.code
        }
        return jsonify(response), e.code

    response = {
        "error": "Internal Server Error",
        "message": str(e),
        "status": 500
    }
    return jsonify(response), 500

4. 日志轮转配置(Linux环境)

使用logrotate进行日志管理,创建配置文件/etc/logrotate.d/myapp

/var/log/myapp/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 root root
    sharedscripts
    postrotate
        systemctl reload myapp > /dev/null
    endscript
}

最佳实践建议

  1. 错误分类

    • 客户端错误 (4xx):记录为WARNING级别
    • 服务器错误 (5xx):记录为ERROR级别
  2. 敏感信息处理

    • 在记录日志前过滤掉敏感数据(如密码、token等)
    • 考虑使用日志脱敏工具
  3. 上下文信息

    • 在日志中包含请求ID,便于追踪
    • 记录用户ID(如果已认证)
  4. 监控集成

    • 将错误日志与监控系统(如Prometheus、ELK)集成
    • 设置错误告警阈值
  5. Swagger文档完善

    • 为每个API端点明确定义可能的错误响应
    • 提供错误代码和描述的详细说明

通过以上方法,您可以在Linux环境下为基于Swagger的API应用建立完善的错误处理和日志记录机制,便于问题排查和系统监控。