You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python FASTAPI依赖服务HTTPS请求响应全日志记录异常求助

问题解决:Swagger Codegen客户端POST请求体及请求/响应头日志缺失修复

问题背景

使用Uvicorn运行FastAPI应用,通过Swagger Codegen生成依赖服务的Python客户端,当前日志仅能记录GET请求及POST请求的响应体,但无法记录POST请求体、请求头和响应头,已尝试调整debug级别、参考requests日志方案等未解决。

核心解决方案

1. 完善日志DictConfig配置

修改get_logging_config()中的loggers节点,补充缺失的关键日志器配置,确保所有HTTP相关日志能被捕获:

def get_logging_config():
    return { 
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': { 
            'standard': {
                '()': ColoredFormatter
            },
        },
        'handlers': { 
            'console': { 
                'level': logging.getLevelName(logging.DEBUG),
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
                'stream': 'ext://sys.stdout'
            }
        },
        'loggers': { 
            '': {  # root logger
                'handlers': ['console'],
                'level': logging.getLevelName(get_logging_level()),
                'propagate': False
            },
            'uvicorn': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.WARN),
                'propagate': False
            },
            'urllib3': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': False
            },
            'urllib3.connectionpool': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': False
            },
            'requests.packages.urllib3': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': True
            },
            # 新增以下日志器配置
            'http.client': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': False
            },
            'requests': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': False
            },
            'dependent_service.client.swagger_client.rest': {
                'handlers': ['console'],
                'level': logging.getLevelName(logging.DEBUG),
                'propagate': False
            }
        } 
    }

2. 修复HTTP客户端日志Patch逻辑

修改http_client_logger.py,解决HTTPS连接下请求体无法输出的问题,手动补充请求头和请求体的日志记录:

import logging
import http.client

httpclient_logger = logging.getLogger("http.client")

def httpclient_logging_patch(level=logging.DEBUG):
    """Enable HTTPConnection debug logging to the logging framework"""

    def httpclient_log(*args):
        msg = "".join(str(arg) for arg in args).strip()
        if msg:
            httpclient_logger.log(level, msg)

    # 替换http.client的print函数,捕获原生debug输出
    http.client.print = httpclient_log
    # 设置最高debug级别
    http.client.HTTPConnection.debuglevel = 2
    http.client.HTTPSConnection.debuglevel = 2

    # 修复HTTPSConnection请求体/头无法输出的问题
    original_send_request = http.client.HTTPSConnection._send_request
    def patched_send_request(self, method, url, body=None, headers=None):
        # 手动记录请求头和请求体
        if headers:
            httpclient_logger.debug(f"Request Headers: {headers}")
        if body and method in ("POST", "PUT", "PATCH"):
            httpclient_logger.debug(f"Request Body: {body}")
        return original_send_request(self, method, url, body, headers)
    http.client.HTTPSConnection._send_request = patched_send_request

3. 验证日志输出

重启服务后发送POST请求,日志将包含:

  • 请求行、请求头、请求体
  • 响应行、响应头、响应体

关键说明

  • HTTPSConnection因SSL包装层拦截,原生debug级别无法输出请求体,需通过patch_send_request方法手动记录
  • Swagger Codegen生成的客户端底层依赖requests/urllib3,需同时配置requests、urllib3、http.client三类日志器
  • 确保disable_existing_loggers设为False,避免生成的客户端日志器被禁用

内容的提问来源于stack exchange,提问作者Aman Sinha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:55:18