Laravel sql 日誌記錄

生活無限好發表於2019-04-30
  1. 在 app/Providers/EventServicePorvider.php 檔案中 新增要註冊的事件
    use Illuminate\Database\Events\QueryExecuted;
    use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
    class EventServiceProvider extends ServiceProvider
    {
        protected $listen = [
            'Illuminate\Database\Events\QueryExecuted' => [
                'App\Listeners\QueryListener',
            ],
        ];
    }
  2. 執行 命令 php artisan event:generate

  3. App\Listeners\QueryListener 檔案的 handle方法中編寫記錄sql的業務邏輯,如:

    public function handle(QueryExecuted $event)
    {
        try{
            if (env('APP_DEBUG') == true) {
                $sql = str_replace("?", "'%s'", $event->sql);
                foreach ($event->bindings as $i => $binding) {
                    if ($binding instanceof DateTime) {
                        $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                    } else {
                        if (is_string($binding)) {
                            $event->bindings[$i] = "'$binding'";
                        }
                    }
                }
                $log = vsprintf($sql, $event->bindings);
                $log = $log.'  [ RunTime:'.$event->time.'ms ] ';
                (new Logger('sql'))->pushHandler(new RotatingFileHandler(storage_path('logs/sql/sql.log')))->info($log);
            }
        }catch (Exception $exception){
    
        }
    }

日誌檔案預設儲存在 storage/logs/sql/ 目錄下

相關文章