123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Http\Middleware;
- use App\Http\Utils\LoggerFactoryUtil;
- use App\Models\RequestLogModel;
- use Closure;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Config;
- use Tool\ShanTaoTool\MqTool;
- class RequestLogMiddleware
- {
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @param string|null $guard
- * @return mixed
- */
- public function handle(Request $request, Closure $next, $guard = null)
- {
- //获取请求数据
- $param = $request->all();
- $startTime = microtime(true);
- //判断请求参数中是否存在traceId
- if($request->header("traceId")){
- $traceId= $request->header("traceId");
- }else{
- $traceId = md5(uniqid().time());
- }
- $requestId = floor(microtime(true)*1000);
- LoggerFactoryUtil::setRequestId($requestId);
- $_GET["traceId"] = $traceId;
- //设置请求开时间
- LoggerFactoryUtil::setStartTime($startTime);
- /**
- * @var JsonResponse $response
- */
- $response = $next($request);
- //获取返回数据
- $endTime = microtime(true);
- $responseData = $response->getContent();
- //获取自定义的日志
- $requestLog = "";
- if(LoggerFactoryUtil::getMessage()){
- $requestLog = json_encode(LoggerFactoryUtil::getMessage());
- }
- //获取监听到的sql语句
- $requestSqlLog = "";
- if(LoggerFactoryUtil::getSqlMessage()){
- $requestSqlLog = json_encode(LoggerFactoryUtil::getSqlMessage());
- }
- //获取操作名称
- $path = $request->path();
- $notLogArr = [
- "api/loadswagger",//获取swagger
- ];
- if(env("REQUEST_LOG_FLAG")&& !in_array($path,$notLogArr)){//排除不需要记录的接口
- // RequestLogModel::query()->insert($logData);
- $mqMessage = [
- "requestPath"=>$request->path(),
- "requestParam"=>json_encode($param),
- "requestResponse"=>$responseData,
- "requestSqlLog"=>$requestSqlLog,
- "requestLog"=>$requestLog,
- "requestProjectName"=>"daogou",
- "createdAt"=>$startTime,
- "updatedAt"=>$endTime,
- "requestId"=>$requestId,
- "uniqueTraceId"=>$traceId
- ];
- try{
- if(LoggerFactoryUtil::getIsPush()==0){
- MqTool::pushLogMessage(json_encode($mqMessage),"daogouLogKey");
- }
- }catch (\Exception $exception){}finally{}
- }
- return $response;
- }
- }
|