为 Laravel Http 客户端添加详细的请求日志

1,484次阅读
没有评论

有时候难免要对 Http 的请求和响应包体进行记录以方便查找问题或做什么。

Laravel 的 Http 客户端是基于 Guzzle 进行封装的,在上层进行了简化,并没有直接给我们留相关的日志配置,想要对请求的 http 进行详细的记录,则需要借助于 Guzzle 的 Handler/中间件,和 withOptions 方法。

首先们要使用 composer 安装一个第三方的 Guzzle 日志中间件。

composer require rtheunissen/guzzle-log-middleware

该中间件比较简单,仅是在请求发生时将请求和响应对象传递给我们指定的闭包,然后我们在闭包中直接调用 Log 的方法进行记录即可。

简单的演示如下:

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler()); //使用 HandlerStack 后必须指定一个 Handler

//日志中间件
$logger = new Logger(function ($level, $message, array $context) {
    Log::log($level, $message);
});

$stack->push($logger);

$res = Http::withOptions([
    'handler' => $stack
])->post($url, $data);

此时请求发生时我们就会在日志里看到一条这样的简单日志:

[2021-04-28 17:00:30] local.INFO: homestead GuzzleHttp/7 - [28/Apr/2021:17:00:30 +0800] "POST /your/request/url HTTP/1.1" 200 136

不过显示这个日志太简单了,我们需要更详细的信息,比如请求和响应的头信息及主体内容,通过该中间件的主页得知可使用一个闭包来进行 message 的格式化。

于是我们对 Logger 进行一番修改,从 Request 和 Response 中取出相应的信息,并且拼装成 Http 的包体结构,结果如下:

$logger = new Logger(function ($level, $message, array $context) {
    Log::log($level, $message);
}, function ($request, $response, $reason) {
    /**
     * @var Request $request
     * @var Response $response
     */
    $requestBody = $request->getBody();
    $requestBody->rewind();
    
    //请求头
    $requestHeaders = [];
    
    foreach ($request->getHeaders() as $k => $vs) {
        foreach ($vs as $v) {
            $requestHeaders[] = "$k: $v";
        }
    }
    
    //响应头
    $responseHeaders = [];
    
    foreach ($response->getHeaders() as $k => $vs) {
        foreach ($vs as $v) {
            $responseHeaders[] = "$k: $v";
        }
    }
    
    $uri = $request->getUri();
    $path = $uri->getPath();
    
    if ($query = $uri->getQuery()) {
        $path .= '?'.$query;
    }
    
    return sprintf(
        "Request %s\n%s %s HTTP/%s\r\n%s\r\n\r\n%s\r\n--------------------\r\nHTTP/%s %s %s\r\n%s\r\n\r\n%s",
        $uri,
        $request->getMethod(),
        $path,
        $request->getProtocolVersion(),
        join("\r\n", $requestHeaders),
        $requestBody->getContents(),
        $response->getProtocolVersion(),
        $response->getStatusCode(),
        $response->getReasonPhrase(),
        join("\r\n", $responseHeaders),
        $response->getBody()->getContents()
    );
});

发送请求后,日志内容如下:

[2021-04-28 17:06:11] local.NOTICE: Request https://www.baidu.com/
POST / HTTP/1.1
User-Agent: GuzzleHttp/7
Content-Type: application/json
Host: www.baidu.com

{"hello":"I am a fake POST."}
--------------------
HTTP/1.1 302 Found
Bdpagetype: 3
Connection: keep-alive
Content-Length: 154
Content-Type: text/html
Date: Wed, 28 Apr 2021 09:06:11 GMT
Location: https://www.baidu.com/search/error.html
Server: BWS/1.1
Set-Cookie: BDSVRTM=0; path=/
Traceid: 161960077103724047468432068516915727024
X-Ua-Compatible: IE=Edge,chrome=1

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2023 年 10 月
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
手把手教你用AI 10分钟生成一个APP!零基础也能搞定

手把手教你用AI 10分钟生成一个APP!零基础也能搞定

今日,我将向大家展示DeepSeek的全新玩法——从零开始,利用AI创建一个完整的应用程序。借助DeepSee...
开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二! 西风 2026-01-08 19:02:20 来源:...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
给AI打个分,结果搞出17亿估值独角兽???

给AI打个分,结果搞出17亿估值独角兽???

给AI打个分,结果搞出17亿估值独角兽??? 闻乐 2026-01-07 17:32:01 来源:量子位 「匿...
全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026

全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026

全自主、更好用!北京人形 “干活机器人” 惊艳亮相 CES2026 量子位的朋友们 2026-01-06 16...
杜比在CES 2026重塑了观影、娱乐的方式

杜比在CES 2026重塑了观影、娱乐的方式

杜比在CES 2026重塑了观影、娱乐的方式 十三 2026-01-07 12:47:06 来源:量子位 树立...
OceanBase蝉联中国分布式数据库本地部署市场第一,领跑国产数据库

OceanBase蝉联中国分布式数据库本地部署市场第一,领跑国产数据库

OceanBase蝉联中国分布式数据库本地部署市场第一,领跑国产数据库 闻乐 2026-01-07 12:36...