Day30 laravel Log 纪录request,response

Day30 laravel Log 纪录request,response

历经千辛万苦终於来到铁人赛第30天,今天来用用laravel的Log功能,log再debug时候蛮重要的,利用middleware功能,可以使用Log看到request和response的内容可以拿来跟前端吵架用,可以清楚的知道错的是前端还是後端。

设定Log

log设定档放在config/logging.php内,里面有许多channel可以选择,laravel预设使用stack channel,若要更改log模式,可以参考官网,我这边先直接使用预设值。log会储存在storage/logs/laravel.log

使用middleware

我希望所有request和response都纪录下来,可以使用之前讲过的after,before middleware,然後在Kernel.php注册在全域使用,这样就可以纪录每一笔输入和输出了。

可以参考我之前的middleware文章Day15 laravel middleware篇

使用log

要使用log很简单,直接使用Log类别info()这个方法可以简单的纪录Log,info()的第一个参数是字串,填入message名称,第二个参数是array,看需要纪录什麽内容,下面的范例是全部记下来。

  • 使用before middleware纪录request Log
use Illuminate\Support\Facades\Log;
    public function handle($request, Closure $next)
    {
        Log::info('request', ['request' => $request]);
        return $next($request);
    }
}
  • 使用after middleware纪录reponse Log
use Illuminate\Support\Facades\Log;
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        Log::info('response', ['response' => $response]);
        return $response;
    }

结果:

[2020-10-14 17:08:26] local.INFO: request {"request":{"Illuminate\\Http\\Request":"GET /api/card HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate, br
Connection:      keep-alive
Content-Length:  29
Content-Type:    application/json
Host:            127.0.0.1:8003
Postman-Token:   e5b9a16f-4d63-4e6e-a4fb-c2843b8a3ac6
User-Agent:      PostmanRuntime/7.26.5
Usertoken:       IpRQEsFsp1BUde5

{
    \"card_name\" : \"ggggg\"
}"}} 
[2020-10-14 17:08:26] local.INFO: response {"response":{"Illuminate\\Http\\JsonResponse":"HTTP/1.1 200 OK
Cache-Control:         no-cache, private
Content-Type:          application/json
Date:                  Wed, 14 Oct 2020 09:08:26 GMT
X-Ratelimit-Limit:     60
X-Ratelimit-Remaining: 59

{\"status\":true,\"user_data\":{\"id\":3,\"username\":\"gill\",\"email\":\"[email protected]\",\"image\":\"\",\"created_at\":\"2020-09-15T04:01:19.000000Z\",\"updated_at\":\"2020-10-14T09:07:33.000000Z\",\"show_cards\":[]}}"}} 


这样request和response的header和body都一清二楚了,在debug的时候方便了,可以检查自己的输入输出有没有符合自己的设计。

铁人赛终於结束了,想想6个月前的自己啥也不懂,到现在可以发表30篇技术心得,我真的为自己感到高兴,同时也希望看这系列文章的人能有收获。
虽然已经完成30天的挑战了,不过我的後端之路还很长,若还有机会,会再发表文章,看我文章的大佬们,也请不吝赐教,谢谢各位,我们下次见。


<<:  [Day 30] SQLite 下

>>:  [Day. 30] 总结&完赛心得

没想太多就用了 MongoDB 的结果 (上)

为什麽会用mongoDB 一开始决定要用 SQL 或 NoSQL时,因为考虑到 不用定义 schem...

Day7绑手绑脚绑Class

延续昨天 今天主要研究如何把v-for里面的item做一个客制化的css或是icon 找了许久发现一...

Day 26 | 使用ManoMotion制作Flappy Bird游戏 Part2 - ManoMotion侦测Grab动作并往上飞

上一篇已将障碍物山的建置与移动做好,今天要来做帝江的跳跃。 目录 ManoMotion手部Grab动...

Material UI in React [ Day 29 ] Customization Component 自订组件 (part2)

...接续前一篇 2.一次性情况的动态变化 在上一篇中讲解如何覆盖 Material-UI 组件的样...

IT铁人DAY 10-Abstract Factory 抽象工厂

  今天要认识的Abstract Factory与Factory Method很像,算是Factor...