ApiLog.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Support\Facades\Cache;
  7. use App\Tools\RedisClusters;
  8. use Illuminate\Support\Facades\Redis;
  9. class ApiLog
  10. {
  11. /**
  12. * Handle an incoming request.
  13. *
  14. * @param \Illuminate\Http\Request $request
  15. * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
  16. * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
  17. */
  18. public function handle(Request $request, Closure $next)
  19. {
  20. $response = $next($request);
  21. if (defined('LARAVEL_START'))
  22. {
  23. $delay = round((microtime(true) - LARAVEL_START)*1000,2);
  24. $api = [];
  25. $api[] = date("h:i:sa",LARAVEL_START);
  26. $api[] = $delay;
  27. $api[] = $request->method();
  28. $api[] = $request->path();
  29. Storage::disk('local')->append("logs/api/".date("Y-m-d").".log",\implode(',',$api) );
  30. //实时监控
  31. $apiPath = explode('/',$request->path());
  32. if(count($apiPath)>=3 && $apiPath[2] !== 'api'){
  33. $timeMinute = intval(time()/60);
  34. $timeSecond = time();
  35. $apiName = $apiPath[2];
  36. $this->UpdateCache("pref-m/all/{$timeMinute}",$delay);
  37. $this->UpdateCache("pref-m/{$apiName}/{$timeMinute}",$delay);
  38. $this->UpdateCache("pref-s/all/{$timeSecond}",$delay,30);
  39. $this->UpdateCache("pref-s/{$apiName}/{$timeSecond}",$delay,30);
  40. }
  41. }
  42. return $response;
  43. }
  44. private function UpdateCache($key,$delay,$expire=3600){
  45. Redis::set($key."/count",Redis::get($key."/count",0)+1,$expire);
  46. Redis::expire($key."/count",$expire);
  47. Redis::set($key."/delay",Redis::get($key."/delay",0)+$delay,$expire);
  48. Redis::expire($key."/delay",$expire);
  49. }
  50. }