ApiLog.php 1.9 KB

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