HttpLog.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\middleware;
  4. use app\user\model\SystemLog;
  5. use think\facade\Cache;
  6. class HttpLog
  7. {
  8. private $logid;
  9. /**
  10. * 处理请求
  11. *
  12. * @param \think\Request $request
  13. * @param \Closure $next
  14. * @return Response
  15. */
  16. public function handle($request, \Closure $next)
  17. {
  18. if ($request->isOptions()) {
  19. error('OPTIONS请求');
  20. }
  21. $response = $next($request);
  22. $token=$request->param('token');
  23. $userinfo = Cache::get('user:info:'.$token);
  24. $data=[
  25. 'system' =>strtolower(ltrim($request->root(),"/")),
  26. 'controller' => strtolower($request->controller()),
  27. 'action' =>strtolower($request->action()),
  28. 'param' =>json_encode($request->param(),JSON_UNESCAPED_UNICODE),
  29. 'response' =>"[]",
  30. 'client_ip'=>$request->ip(),
  31. 'action_id' => $userinfo['id']??0,
  32. 'action_name' => $userinfo['nickname']??'system'
  33. ];
  34. $log=SystemLog::create($data);
  35. $this->logid=$log->id;
  36. return $response;
  37. }
  38. public function end(\think\Response $response)
  39. {
  40. SystemLog::where('id',$this->logid)->update(['response'=>json_encode($response->getData(),JSON_UNESCAPED_UNICODE)]);
  41. }
  42. }