laravel如何利用中介軟體優雅的記錄請求日誌

Sume發表於2022-07-05

中介軟體程式碼

<?php

namespace App\Http\Middleware;

use App\Jobs\LogJob;
use Closure;

class RequestLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $time1 = microtime(true);
        $response = $next($request);
        $time2 = microtime(true);
        //通過中介軟體 記錄操作記錄
        LogJob::dispatch([
            'url'       => $request->path(),
            'request'   => $request->all(),
            'response'  => $response,
            'time'      => sprintf("%.4f",($time2-$time1)).'秒',
            'method'    => $request->method(),
        ]);
        return $response;
    }
}

佇列程式碼

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class LogJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $data;

    public $RunJob = __CLASS__;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        //
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('--------------------------請求日誌佇列開始--------------------------');
        Log::info('佇列名稱:'.$this->RunJob);
        Log::info('請求地址:'.$this->data['url']);
        Log::info('請求方式:'.$this->data['method']);
        Log::info('請求引數:'.json_encode($this->data['request'] ,JSON_UNESCAPED_UNICODE));
        Log::info('返回結果:'.json_encode($this->data['response'] ,JSON_UNESCAPED_UNICODE));
        Log::info('執行時長:'.$this->data['time']);
        Log::info('--------------------------請求日誌佇列結束--------------------------');
        Log::info('');
    }
}

執行結果 也可以把資料記錄在資料庫中 具體怎麼看使用場景就可以 這樣可以更方便的看到錯誤級引數及結果
laravel中介軟體記錄請求日誌

能看到這篇文章的應該都是程式設計師 可能需要買一臺伺服器練手等 下邊推薦下伺服器 有需要的可以點選 不需要直接濾過即可

阿里雲伺服器低至0.9元/月阿里雲伺服器低至0.9元/月

騰訊雲伺服器
2核4G伺服器1m頻寬 一年不到200米!

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章