第一步:打开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 开心的去调试吧
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。