Laravel 中输出 SQL 语句的到 log 日志

时间:2023-03-09 19:13:31
Laravel 中输出 SQL 语句的到 log 日志

在 AppServiceProvider.php 中的 boot 方法中添加如下代码 即可

 public function boot() {
//数据库监听
DB::listen(function ($query) { //排除时间
//%Y-%m-%d %H:%i
$tmp = str_replace('%', '"' . '^^' . '"', $query->sql);
$tmp = str_replace('?', '"' . '%s' . '"', $tmp); $qBindings = [];
foreach ($query->bindings as $key => $value) {
if (is_numeric($key)) {
$qBindings[] = $value;
} else {
$tmp = str_replace(':' . $key, '"' . $value . '"', $tmp);
}
}
//var_dump($query->sql,$tmp,$qBindings);
if (count($qBindings)) {
$tmp = vsprintf($tmp, $qBindings);
}
$tmp = str_replace("\\", "", $tmp);
if ($query->time > 1000) { //添加慢日志
BLog::warning('use time: ' . $query->time . 'ms; ' . $tmp);
}
BLog::db('use time: ' . $query->time . 'ms; ' . $tmp);
}); }