RequestLogMiddleware.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Http\Utils\LoggerFactoryUtil;
  4. use App\Models\RequestLogModel;
  5. use Closure;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Config;
  8. use Tool\ShanTaoTool\MqTool;
  9. class RequestLogMiddleware
  10. {
  11. /**
  12. * Handle an incoming request.
  13. *
  14. * @param \Illuminate\Http\Request $request
  15. * @param \Closure $next
  16. * @param string|null $guard
  17. * @return mixed
  18. */
  19. public function handle(Request $request, Closure $next, $guard = null)
  20. {
  21. //获取请求数据
  22. $param = $request->all();
  23. $startTime = microtime(true);
  24. //判断请求参数中是否存在traceId
  25. if($request->header("traceId")){
  26. $traceId= $request->header("traceId");
  27. }else{
  28. $traceId = md5(uniqid().time());
  29. }
  30. $requestId = floor(microtime(true)*1000);
  31. LoggerFactoryUtil::setRequestId($requestId);
  32. $_GET["traceId"] = $traceId;
  33. //设置请求开时间
  34. LoggerFactoryUtil::setStartTime($startTime);
  35. /**
  36. * @var JsonResponse $response
  37. */
  38. $response = $next($request);
  39. //获取返回数据
  40. $endTime = microtime(true);
  41. $responseData = $response->getContent();
  42. //获取自定义的日志
  43. $requestLog = "";
  44. if(LoggerFactoryUtil::getMessage()){
  45. $requestLog = json_encode(LoggerFactoryUtil::getMessage());
  46. }
  47. //获取监听到的sql语句
  48. $requestSqlLog = "";
  49. if(LoggerFactoryUtil::getSqlMessage()){
  50. $requestSqlLog = json_encode(LoggerFactoryUtil::getSqlMessage());
  51. }
  52. //获取操作名称
  53. $path = $request->path();
  54. $notLogArr = [
  55. "api/loadswagger",//获取swagger
  56. ];
  57. if(env("REQUEST_LOG_FLAG")&& !in_array($path,$notLogArr)){//排除不需要记录的接口
  58. // RequestLogModel::query()->insert($logData);
  59. $mqMessage = [
  60. "requestPath"=>$request->path(),
  61. "requestParam"=>json_encode($param),
  62. "requestResponse"=>$responseData,
  63. "requestSqlLog"=>$requestSqlLog,
  64. "requestLog"=>$requestLog,
  65. "requestProjectName"=>"daogou",
  66. "createdAt"=>$startTime,
  67. "updatedAt"=>$endTime,
  68. "requestId"=>$requestId,
  69. "uniqueTraceId"=>$traceId
  70. ];
  71. try{
  72. if(LoggerFactoryUtil::getIsPush()==0){
  73. MqTool::pushLogMessage(json_encode($mqMessage),"daogouLogKey");
  74. }
  75. }catch (\Exception $exception){}finally{}
  76. }
  77. return $response;
  78. }
  79. }