HttpLog.php 1.4 KB

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