在laravel框架中使用中间件 + 队列的方式记录请求日志
Laravel  /  管理员 发布于 1年前   1004
在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框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..博主 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号