|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ilzrv\LaravelSlowQueryDetector\Http\Middleware; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Support\Str; |
| 7 | + |
| 8 | +class SlowQueryDetectorMiddleware |
| 9 | +{ |
| 10 | + protected $queriesCount = 0; |
| 11 | + protected $heavyQueryCount = 0; |
| 12 | + protected $heaviestQueryTime = 0; |
| 13 | + protected $heaviestQuery = ''; |
| 14 | + protected $executionTime = 0; |
| 15 | + |
| 16 | + /** |
| 17 | + * Handle an incoming request. |
| 18 | + * |
| 19 | + * @param \Illuminate\Http\Request $request |
| 20 | + * @param \Closure $next |
| 21 | + * @return mixed |
| 22 | + */ |
| 23 | + public function handle($request, Closure $next) |
| 24 | + { |
| 25 | + $this->executionTime = -round(microtime(true) * 1000); |
| 26 | + |
| 27 | + \DB::listen(function ($query) { |
| 28 | + $this->queriesCount++; |
| 29 | + if ($query->time > config('slow-query-detector.query.max_time')) { |
| 30 | + $this->heavyQueryCount++; |
| 31 | + if ($query->time > $this->heaviestQueryTime) { |
| 32 | + $this->heaviestQueryTime = $query->time; |
| 33 | + $this->heaviestQuery = $this->getQuery($query); |
| 34 | + } |
| 35 | + } |
| 36 | + }); |
| 37 | + |
| 38 | + $next = $next($request); |
| 39 | + |
| 40 | + $this->executionTime += round(microtime(true) * 1000); |
| 41 | + |
| 42 | + if ($this->needNotify()) { |
| 43 | + $this->notify($request); |
| 44 | + } |
| 45 | + |
| 46 | + return $next; |
| 47 | + } |
| 48 | + |
| 49 | + protected function needNotify() |
| 50 | + { |
| 51 | + return $this->queriesCount > config('slow-query-detector.code.max_queries') |
| 52 | + || $this->executionTime > config('slow-query-detector.code.max_time') |
| 53 | + || $this->heaviestQueryTime > config('slow-query-detector.query.max_time'); |
| 54 | + } |
| 55 | + |
| 56 | + protected function notify($request) |
| 57 | + { |
| 58 | + app('log')->critical(print_r([ |
| 59 | + 'Execution Time' => $this->executionTime, |
| 60 | + 'Queries Count' => $this->queriesCount, |
| 61 | + 'Heavy Queries Count' => $this->heavyQueryCount, |
| 62 | + 'Full URL' => $request->fullUrl(), |
| 63 | + 'Action' => $request->route()->getActionName(), |
| 64 | + 'Heaviest Query' => [ |
| 65 | + 'Query' => $this->heaviestQuery, |
| 66 | + 'Time' => $this->heaviestQueryTime, |
| 67 | + ] |
| 68 | + ], true)); |
| 69 | + } |
| 70 | + |
| 71 | + protected function getQuery($query) |
| 72 | + { |
| 73 | + return config('slow-query-detector.query.with_bindings') |
| 74 | + ? Str::replaceArray('?', $query->bindings, $query->sql) |
| 75 | + : $query->sql; |
| 76 | + } |
| 77 | +} |
0 commit comments