Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 3 additions & 17 deletions src/Outputs/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,13 @@ public function boot()

public function output(Collection $detectedQueries, Response $response)
{
$this->log('Detected N+1 Query');

foreach ($detectedQueries as $detectedQuery) {
$logOutput = 'Model: '.$detectedQuery['model'] . PHP_EOL;

$logOutput .= 'Relation: '.$detectedQuery['relation'] . PHP_EOL;

$logOutput .= 'Num-Called: '.$detectedQuery['count'] . PHP_EOL;

$logOutput .= 'Call-Stack:' . PHP_EOL;

foreach ($detectedQuery['sources'] as $source) {
$logOutput .= '#'.$source->index.' '.$source->name.':'.$source->line . PHP_EOL;
}

$this->log($logOutput);
$this->log($detectedQuery);
}
}

private function log(string $message)
private function log(array $context = [])
{
LaravelLog::channel(config('querydetector.log_channel'))->info($message);
logger()?->warning('Detected N+1 Query', $context);
}
}
46 changes: 21 additions & 25 deletions src/QueryDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,35 +81,29 @@ public function logQuery($query, Collection $backtrace)
if (is_array($relation) && isset($relation['object'])) {
if ($relation['class'] === Relation::class) {
$model = get_class($relation['object']->getParent());
$relationName = get_class($relation['object']->getRelated());
$relatedModel = $relationName;
} else {
$model = get_class($relation['object']);
$relationName = $relation['args'][0];
$relatedModel = $relationName;
}

$sources = $this->findSource($backtrace);

if (empty($sources)) {
return;
}

$key = md5($query->sql . $model . $relationName . $sources[0]->name . $sources[0]->line);

$count = Arr::get($this->queries, $key . '.count', 0);
$time = Arr::get($this->queries, $key . '.time', 0);

$this->queries[$key] = [
'count' => ++$count,
'time' => $time + $query->time,
'query' => $query->sql,
'model' => $model,
'relatedModel' => $relatedModel,
'relation' => $relationName,
'sources' => $sources
];
} else {
$model = get_class($modelTrace['object'] ?? '');
}
$key = md5($query->sql);
$count = Arr::get($this->queries, $key . '.count', 0);
$time = Arr::get($this->queries, $key . '.time', 0);
$sources = Arr::get($this->queries, $key . '.sources', []);
$sources[] = array_slice($this->findSource($backtrace), 0, 5);

$bindings = Arr::get($this->queries, $key . '.bindings', []);
$bindings[] = $query->bindings;

$this->queries[$key] = [
'count' => ++$count,
'time' => $time + $query->time,
'query' => $query->sql,
'model' => $model,
'sources' => $sources,
'bindings_json' => json_encode($bindings),
];
}
}

Expand Down Expand Up @@ -148,6 +142,7 @@ public function parseTrace($index, array $trace)
* Check if the given file is to be excluded from analysis
*
* @param string $file
*
* @return bool
*/
protected function fileIsInExcludedPath($file)
Expand All @@ -172,6 +167,7 @@ protected function fileIsInExcludedPath($file)
* Shorten the path by removing the relative links and base dir
*
* @param string $path
*
* @return string
*/
protected function normalizeFilename($path): string
Expand Down
22 changes: 22 additions & 0 deletions src/QueryDetectorServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
namespace BeyondCode\QueryDetector;

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

class QueryDetectorServiceProvider extends ServiceProvider
Expand All @@ -19,6 +23,24 @@ public function boot()
}

$this->registerMiddleware(QueryDetectorMiddleware::class);

Queue::before(static function (JobProcessing $event) {
$jobData = $event->job->payload();
Log::withContext(['job_name' => $jobData['displayName'] ?? $event->job::class]);
/** @var QueryDetector $detector */
$detector = app()->make(QueryDetector::class);
if ($detector->isEnabled()) {
$detector->boot();
}
});

Queue::after(static function (JobProcessed $event) {
/** @var QueryDetector $detector */
$detector = app()->make(QueryDetector::class);
if ($detector->isEnabled()) {
$detector->output(request(), response()->json());
}
});
}

/**
Expand Down