默认情况下,Laravel 5 中禁用了查询日志:
https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448
您需要通过调用启用查询日志:
DB::enableQueryLog();
// and then you can get query log
dd(DB::getQueryLog());
或者注册一个事件监听器:
DB::listen(
function ($sql, $bindings, $time) {
// $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
// $bindings - [5]
// $time(in milliseconds) - 0.38
}
);
一些提示
1。多个数据库连接
如果您有多个数据库连接,则必须指定记录哪个连接
启用my_connection的查询日志:
DB::connection('my_connection')->enableQueryLog();
获取my_connection的查询日志:
print_r(
DB::connection('my_connection')->getQueryLog()
);
2。在哪里启用查询日志?
对于 HTTP 请求生命周期,您可以在某些 `BeforeAnyDbQueryMiddleware` [中间件][1] 的 `handle` 方法中启用查询日志,然后在同一中间件的 [`terminate`][2] 方法中检索已执行的查询。
class BeforeAnyDbQueryMiddleware
{
public function handle($request, Closure $next)
{
DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
// Store or dump the log data...
dd(
DB::getQueryLog()
);
}
}
中间件的链不会针对工匠命令运行,因此对于 CLI 执行,您可以在 artisan.start 事件侦听器中启用查询日志。
例如你可以把它放在bootstrap/app.php文件中
$app['events']->listen('artisan.start', function(){
\DB::enableQueryLog();
});
3。内存
Laravel 将所有查询保存在内存中。因此,在某些情况下,例如插入大量行时,或者有大量查询的长时间运行作业时,这可能会导致应用程序使用过多的内存。
在大多数情况下,您只需要查询日志来进行调试,如果是这种情况,我建议您仅在开发时启用它。
if (App::environment('local')) {
// The environment is local
DB::enableQueryLog();
}
参考文献