Laravel5.2 实时记录sql语句log

Laravel version: 5.2

创建监听器

php artisan make:listener QueryListener --event=Illuminate\\Database\\Events\\QueryExecuted

生成文件于 app/Listeners/QueryListener.php

注册事件

打开 app/Providers/EventServiceProvider.php,在 $listen 中添加 illuminate.query 事件的监听器为 QueryListener

protected $listen = [
    \Illuminate\Database\Events\QueryExecuted::class => [
        QueryListener::class
    ],
];

添加逻辑

编辑刚才生成的 QueryListener .php 文件

log = new Logger('sql');
        $this->log->pushHandler(
            new StreamHandler(
                storage_path('logs/sql.log'), 
                Logger::INFO
            )
        );
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        if (env('APP_ENV', 'production') == 'local') {
            $sql = str_replace("?", "'%s'", $event->sql);

            $log = vsprintf($sql, $event->bindings);

            // Log::info($log);
            $this->log->addInfo($log);
        }
    }
}

这样所有的sql语句都会记录在 storage/logs/sql.log 文件里,结果如下

[2017-01-20 14:43:57] sql.INFO: update `user_login_count` set `register_user_num` = '5' where `id` = '182' [] []

参考文章

  • 保存log到指定目录
  • Laravel 5.2中记录运行时 SQL

你可能感兴趣的:(Laravel5.2 实时记录sql语句log)