Laravel 开启sql调试

时间:2022-12-10 13:00:38

1.在config/database.php添加以下内容

'enableQueryLog' => env('ENABLE_QUERY_LOG',false),

2.打开app\Providers\AppServiceProvider.PHP,在boot方法中添加如下内容

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
public function boot()
{
if (config('database.enableQueryLog')) {
DB::listen(
function ($sql) {
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('查询语句耗时 - ' . $sql->time . ' 毫秒 ', [
'链接名称' => $sql->connectionName,
'Sql语句' => $query
]);
}
);
}
}

 

作者:joshua317