文件路径 App\Providers\AppServiceProvider.php
在boot()方法中记录:
.env 配置文件中 APP_DEBUG=true
use Illuminate\Support\Facades\Log;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
if (env('APP_DEBUG')) {
\DB::listen(function ($query) {
$tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
$qBindings = [];
foreach ($query->bindings as $key => $value) {
if (is_numeric($key)) {
$qBindings[] = $value;
} else {
$tmp = str_replace(':'.$key, '"'.$value.'"', $tmp);
}
}
$tmp = vsprintf($tmp, $qBindings);
$tmp = str_replace("\\", "", $tmp);
//$query->time 是sql语句执行的时间
Log::info('execution time:'.$query->time.'ms; '.$tmp."\n\n\t");
});
}
}
}
此博客内容展示了如何在 Laravel 的 AppServiceProvider 类的 boot 方法中设置逻辑,当 APP_DEBUG 环境变量为 true 时,监听所有 SQL 查询并记录其执行时间和详细信息。通过使用 Log facade,每次 SQL 查询的执行时间及其带参数的 SQL 语句会被写入日志,有助于调试和性能分析。
321

被折叠的 条评论
为什么被折叠?



