您将需要通过调用以下命令来启用查询日志:
DB::enableQueryLog();
或注册一个事件监听器:
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请求生命周期,可以在
handle某些
BeforeAnyDbQueryMiddleware
中间件的方法中启用查询日志,然后
terminate在同一中间件的方法中检索已执行的查询。
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();}


