laravel5
用DB自带的getQueryLog方法直接打印:
use Illuminate\Support\Facades\DB;
1 DB::connection()->enableQueryLog(); // 开启QueryLog 2 \App\User::find(1); 3 dump(DB::getQueryLog());exit;
得到的结果语句与参数是分开的,非常不方便验证
1 array:1 [ 2 0 => array:3 [ 3 "query" => "select * from `fook_platform_ordercode` where `fook_platform_ordercode`.`id` = ? limit 1" 4 "bindings" => array:1 [ 5 0 => 1 6 ] 7 "time" => 11.47 8 ] 9 ]
若要打印出完整的sql语句,可将以下代码复制到AppServiceProvider中的boot方法中:
1 \DB::listen( 2 function ($sql) { 3 foreach ($sql->bindings as $i => $binding) { 4 if ($binding instanceof \DateTime) { 5 $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); 6 } else { 7 if (is_string($binding)) { 8 $sql->bindings[$i] = "'$binding'"; 9 } 10 } 11 } 12 13 // Insert bindings into query 14 $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql); 15 16 $query = vsprintf($query, $sql->bindings); 17 18 // Save the query to file 19 $logFile = fopen( 20 storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'), 21 'a+' 22 ); 23 fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL); 24 fclose($logFile); 25 } 26 );
日志在storage/log/xxx_query.log
轉載:https://blog.csdn.net/buer2202/article/details/75364465