1 添加到服务容器AppServiceProvider.php 2 boot 方法中 3 if (env(‘APP_ENV‘) != ‘production‘) { 4 \DB::listen( 5 function ($sql) { 6 foreach ($sql->bindings as $i => $binding) { 7 if ($binding instanceof \DateTime) { 8 $sql->bindings[$i] = $binding->format(‘\‘Y-m-d H:i:s\‘‘); 9 } else { 10 if (is_string($binding)) { 11 $sql->bindings[$i] = "‘$binding‘"; 12 } 13 } 14 } 15 16 // Insert bindings into query 17 $query = str_replace(array(‘%‘, ‘?‘), array(‘%%‘, ‘%s‘), $sql->sql); 18 19 $query = vsprintf($query, $sql->bindings); 20 21 // Save the query to file 22 $logFile = fopen( 23 storage_path(‘logs‘ . DIRECTORY_SEPARATOR . date(‘Y-m-d‘) . ‘_query.log‘), 24 ‘a+‘ 25 ); 26 fwrite($logFile, date(‘Y-m-d H:i:s‘) . ‘: ‘ . $query . PHP_EOL); 27 fclose($logFile); 28 } 29 ); 30 }
可以在执行查询的时候,记录下所有连锁查询的sql语句,便于排查性能和查找问题