关于php:laravel-输出sql

38次阅读

共计 1471 个字符,预计需要花费 4 分钟才能阅读完成。

第一步:关上 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 开心的去调试吧

正文完
 0