Search code examples
laravellumen

how log all queries of api in lumen 5.7


I need to see to all queries that executed in api. I tried 3 ways but none of them work

1:

\Illuminate\Support\Facades\DB::listen(function ($query) {
     Log::info($query->sql, ['Bindings' => $query->bindings, 'Time' => $query->time]);
});

listen method is not existed.

2:

Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    Log::debug($query->sql . ' - ' . serialize($query->bindings));
});

this one didn't work too.

3:

DB::connection("mysql2")->enableQueryLog();
DB::connection("mysql2")->getQueryLog();

I put 1 and 2 in bootstrap/app.php and third one in api controller.

I should mention that i have different databases.

Is there other way?


Solution

  • You can try using the 3rd approach in terminable middleware e.g.:

    namespace Illuminate\Session\Middleware;
    
    use Closure;
    
    class LogQueries
    {
        public function handle($request, Closure $next)
        {
            DB::connection("mysql2")->enableQueryLog();
            return $next($request);
        }
    
        public function terminate($request, $response)
        {
            Log::info('Queries executed', DB::connection("mysql2")->getQueryLog());
            
        }
    }
    

    You can then register this in your app/bootstrap.php as:

    $app->middleware([
       App\Http\Middleware\LogQueries::class
    ]);
    

    This should enable the query log at the start of the request and then log all queries at the end. The downside is if you perform many large queries (large as in long query string) you will need to keep them in memory until the end of the request which may not be ideal.

    Note: I don't fully recall the array structure of the query log so you may need to adjust the log step to work for your needs better.