在app/Providers/EventServiceProvider.php的boot方法中加入监听:
public function boot()
{
try{
if (env('APP_DEBUG_SQL') == true) {
DB::listen(function ($query) {
$tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
$arrBindings = [];
foreach ($query->bindings as $key => $value) {
if (is_numeric($key)) {
$arrBindings[] = $value;
} else {
$tmp = str_replace(':'.$key, '"'.$value.'"', $tmp);
}
}
if($arrBindings){
$tmp = vsprintf($tmp, $arrBindings);
$tmp = str_replace("\\", "", $tmp);
}
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
$strShowLog='--------------------------------------------------------------------start'. PHP_EOL;
$strShowLog.=date('Y-m-d H:i:s') . ': ' . ' '.Request::url(). ' '.Common::get_real_ip() . PHP_EOL;
$strShowLog.=date('Y-m-d H:i:s') . ': ' . ' execution time: '.$query->time.'ms; '.$tmp . PHP_EOL;
$strShowLog.='--------------------------------------------------------------------end'. PHP_EOL;
fwrite($logFile, $strShowLog);
fclose($logFile);
});
}else{
//关闭debug不记录sql
}
}catch (\Exception $e){
//异常继续
}
}
|