laravel中把查询数据库的sql写入日志中

来源:互联网 发布:java while sleep 编辑:程序博客网 时间:2024/05/07 20:06

1、在app\Providers\EventServiceProvider.php中添加一个触发

<pre name="code" class="html">protected $listen = [        'App\Events\SomeEvent' => [            'App\Listeners\EventListener',        ],        'Illuminate\Database\Events\QueryExecuted' => [            'App\Listeners\QueryListener'        ]];
然后在listenrs文件夹中创建一个文件app\Listeners\QueryListener.php
class QueryListener{    /**     * Create the event listener.     *     * @return void     */    public function __construct()    {        //    }    /**     * Handle the event.     *     * @param  QueryExecuted  $event     * @return void     */    public function handle(QueryExecuted $event)    {        //        $sql = str_replace("?", "'%s'", $event->sql);        $log = vsprintf($sql, $event->bindings);        Log::info($log);    }}

然后你就能到

storage\logs\laravel.log 查询你的sql了,优化sql合查询bug有很大的帮助。

1 0