在laravel框架中使用中间件 + 队列的方式记录请求日志

2023-06-01 00:00:00 框架 队列 中间件

在laravel项目中使用中间件+队列实现日志记录

中间件代码

<?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 log.png


最后

这里是文件级保存,你也可以根据你的业务直接保存进数据库...等


相关文章