laravel 输出sql

Posted mrshao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel 输出sql相关的知识,希望对你有一定的参考价值。

第一步:打开Providers/AppServiceProvider.php,新增方法sql_listen()

/**
 * listen database and dump sql which only be used for debug
 * @param bool|false $isShowTime
 */
function sql_listen($isShowTime = false)
{
    app(\'db\')->listen(function ($queryExecuted, $bindings = [], $time = \'\') use ($isShowTime) {
        static $_static_sql = [];
        $sql = \'\';
        if (is_object($queryExecuted)) {
            $sql      = $queryExecuted->sql;
            $bindings = $queryExecuted->bindings;
            $time     = $queryExecuted->time;
        }

        foreach ($bindings as $i => $binding) {
            if (is_string($binding)) {
                $bindings[$i] = "\'$binding\'";
            }
        }

        $rawSql = str_replace(array(
            \'%\',
            \'?\'
        ), array(
            \'%%\',
            \'%s\'
        ), $sql);
        $rawSql = vsprintf($rawSql, $bindings) . \';\';

        if (!$_static_sql || !in_array($rawSql, $_static_sql)) {
            $_static_sql[] = $rawSql;
        } else {
            return;
        }

        $usedTime = \'\';
        if ($isShowTime) {
            $time     = $time / 1000;
            $usedTime = " ({$time}s)";
        }
        $sqlContent     = $rawSql . $usedTime;

        logger()->channel(\'sqlLog\')->info("我是SQL:" . $sqlContent . PHP_EOL, [
            //\'raw_sql\'         => $sql,
            \'connection_name\' => isset($queryExecuted->connectionName) ? $queryExecuted->connectionName : \'\',
            \'duration_time\'   => round($time, 5),
            \'created_at\'      => date(\'Y-m-d H:i:s\')
        ]);
    });
}

然后boot方法注册sql_listen()函数

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    $this->sql_listen(true);    //sql监听,用于调试或者查看慢sql
    Schema::defaultStringLength(191); //add fixed sql
}

第二步:config/logging.php channels 中增加sqlLog数组

\'sqlLog\' => [
    \'driver\'     => \'daily\',
    \'name\'       => \'sql监听\',
    \'path\'       => storage_path(\'logs/sql.log\'),
    \'level\'      => \'debug\',
    \'days\'       => 15,
    \'permission\' => 0664,
],

第三步:清除下缓存

第四步:去执行一个带数据库的操作,然后回来查看有没有日志
日志目录:项目目录 /storage/logs/

tail -f sql-2021-04-23.log 开心的去调试吧

以上是关于laravel 输出sql的主要内容,如果未能解决你的问题,请参考以下文章

需要一种有效的方法来避免使用 Laravel 5 重复代码片段

laravel 输出sql

Laravel:如何在控制器的几种方法中重用代码片段

php Laravel输出所有数据库执行SQL

laravel如何输出最后一条执行的SQL

Laravel Controller SQL:连接两个表使输出相乘