How to register long query callback in Laravel

Categorized as Laravel

If you are running your Laravel app in production mode, you may want to register long running queries, which is very useful for debugging purposes:

DB::enableQueryLog();

DB::whenQueryingForLongerThan(1000, function ($connection) {
  Log::warning(
    'Long running queries have been detected.',
    $connection->getQueryLog()
  );
});

You can also sort these long queries by their duration of execution, so that the longest running ones are easier to see:

DB::enableQueryLog();

DB::whenQueryingForLongerThan(10, function (Connection $connection) {
  $logs = Arr::sort($connection->getQueryLog(),
    fn ($log) => $log['time']
  );

  Log::warning(
    'Long running queries have been detected.',
    array_reverse($logs)
  );
});

Via @realstevebauman.

Leave a reply

Your email address will not be published. Required fields are marked *