0

Laravel 记录 SQL 查询语句到日志

neo created at6 years ago view count: 2670

使用 Laravel 开发项目常常需要查看打印输出SQL到日志文件中。用来Debug查看执行的SQL

在 app/Providers/AppServiceProvider.php 文件中添加下面代码

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment() == 'local') {
            \DB::enableQueryLog();

            \DB::listen(
                function ($sql) {
                    // $sql is an object with the properties:
                    //  sql: The query
                    //  bindings: the sql query variables
                    //  time: The execution time for the query
                    //  connectionName: The name of the connection

                    // To save the executed queries to file:
                    // Process the sql and the bindings:
                    foreach ($sql->bindings as $i => $binding) {
                        if ($binding instanceof \DateTime) {
                            $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                        } else {
                            if (is_string($binding)) {
                                $sql->bindings[$i] = "'$binding'";
                            }
                        }
                    }

                    // Insert bindings into query
                    $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
                    $query = vsprintf($query, $sql->bindings);
                    \Log::info($query);
                }
            );
        }

    }

只要是在本地就能够在storage/logs/laravel.log 中查看原生的SQL语句。

report
回复

Recent search keywords