DEV Community

Manish Chaudhary
Manish Chaudhary

Posted on

1 1

Listen to query event and save to separate log file in Laravel

Add below code to AppServiceProvider boot method

DB::listen(function ($query) {
    File::append(storage_path('/logs/query.log'),
        '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $query->sql . 
        ' [' . implode(', ',$query->bindings) . ']' . PHP_EOL . 
        PHP_EOL
    );
);
Enter fullscreen mode Exit fullscreen mode

The all the query that are run in your app will be saved in storage/logs/query.log file

Top comments (1)

Collapse
 
theccode profile image
Eric A. Kumah

Concise but quite handy piece of code. Great!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs