Lumen 實時記錄 SQL 執行解決方案

994914376發表於2019-08-13

發現好多小夥伴除錯程式碼時對sql 列印不方便,特整理怎麼實時在日誌檔案中列印所執行的 sql 語句

1、在 Listeners目錄新建 QueryListener.php 檔案 程式碼如下:
<?php
namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;

class QueryListener
{
    public function handle(QueryExecuted $event)
    {
        if (env('APP_ENV', 'production') == 'local') {
            $sql = str_replace('?', "'%s'", $event->sql);
            $log = vsprintf($sql, $event->bindings);
            $this->put_log('sql', $log);
        }
    }

    private function put_log($file = 'app', $content = '')
    {
        $data = date('Y-m-d');
        $cut_line = str_repeat("-", 100);
        is_dir(storage_path('logs/sql')) or mkdir (storage_path('logs/sql'), 0777, true); // 資料夾不存在則建立
        $content = '[' . date('Y-m-d H:i:s') . "]" . $content;
        @file_put_contents(storage_path('logs/sql/' . $file . '-' . $data . '.log'), $content . "\n" . $cut_line . "\n\n", FILE_APPEND);
    }
}
2、在Providers/EventServiceProvider.php 新增如下程式碼
<?php

namespace App\Providers;

use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [

        'Illuminate\Database\Events\QueryExecuted' => [
            'App\Listeners\QueryListener'
        ],
    ];
}
3、在 bootstrap/app.php檔案中開啟 EventServiceProvider註冊即可
 $app->register(App\Providers\EventServiceProvider::class);
4、接下來寫一個 sql 語句就能在 storage/logs/sql看到生成的 sql 日誌了
    app('db')->where('id', '>', '5')->get();

希望能對大家有所幫助

相關文章