laravel: 用中间件把请求和响应log下来

一,代码:

1, 中间件

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\extend\LogEs;

class LogSearch
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        //只记录request的话,代码可以写在这里
        $response = $next($request);
        //log request
        $request = [
            'url' => $request->fullUrl(),
            'method' => $request->method(),
            'input' => $request->input(),
        ];
        //把响应的content转为数组记录,如果是object不能直接log
        $resLog = json_decode($response->getContent());
        $resLog = (array)$resLog;
        LogEs::logSearch($request,$resLog);
        //返回
        return $response;
    }
}

2,routes

Route::controller(SouController::class)->middleware([LogSearch::class])->group(function () {
    Route::post('/sou/souershou', 'souershou');
});

3,log类

<?php
namespace App\extend;

use App\Business\BaseBusiness;
use Illuminate\Support\Facades\Log;

class LogEs extends BaseBusiness
{
     //写搜索的日志
     static public function logSearch($arr_request,$arr_response) {
        Log::channel('essearch')->info($arr_request);
        Log::channel('essearch')->info($arr_response);
    }
}

 

二,测试效果:

[2024-08-07 15:48:59] local.INFO: array (
  'url' => 'http://192.168.219.6/api/soud/souershou?wushi%5B0%5D=1&wushi%5B1%5D=3&city=%E5%8C%97%E4%BA%AC&keystr=%E4%B8%87%E8%BE%BE&order=areaasc&p=1&zhuangxiu%5B0%5D=1',
  'method' => 'POST',
  'input' => 
  array (
    'city' => '北京',
    'keystr' => '万达',
    'order' => 'areaasc',
    'wushi' => 
    array (
      0 => '1',
      1 => '3',
    ),
    'zhuangxiu' => 
    array (
      0 => '1',
    ),
    'p' => '1',
  ),
)  
[2024-08-07 15:48:59] local.INFO: array (
  'status' => 'success',
  'code' => 200,
  'time' => '2024-08-07 15:48:59',
  'msg' => '',
  'data' => 
  (object) array(
     'total' => 1,
     'data' => 
    array (
      0 => 
      (object) array(
         'f_id' => 6,
         'f_type' => 1,
         'f_district' => '通州区',
         'f_cover_image' => NULL,
         'f_area' => '55㎡',
         'f_toward' => '南',
         'f_title' => '二手房·中仓小区 万达商圈 满五年唯一 6号地铁',
         'f_district' => '万达,通州万达',
      ),
    ),
  ),
)  

三,说明:

生产环境中会影响性能,通常用于测试阶段供调试使用

 

posted @ 2024-08-07 17:26  刘宏缔的架构森林  阅读(21)  评论(0编辑  收藏  举报