laravel 記錄慢sql日誌
阿新 • • 發佈:2020-09-14
#在\app\Providers\AppServiceProvider.php裡面,boot方法裡寫
use Illuminate\Support\Facades\DB;
public function boot()
{
DB::listen(function($query){
try {
$sql = $query->sql;
$bingings = $query->bindings;
$time = $query->time;
//時間超過1000ms(1s)的做記錄
$msg = compact('sql', 'bingings', 'time');
$sql_type = substr($sql, 0, 6);//sql型別 增刪改查
//慢sql規則,根據不同語句判斷慢不慢
$slow_rule = ['select' => 1000, 'insert' => 100, 'update' => 100, 'delete' => 100];
$maxTime = $slow_rule[$sql_type] ?? 100;
if ($time >= $maxTime) {
LogUtil::LogDiyInfo($msg, 'slowlySql/' . $sql_type);
}
}catch (\Exception $exception){
$msg = Common::genErrMsg($exception);
LogUtil::writeLoc($msg,__CLASS__,__FUNCTION__,true);
}
});
}
注1:LogDiyInfo方法
public static function LogDiyInfo($msg,$file_name='info'){
Blogger::info($msg,$file_name);
}
注2:genErrMsg方法
public static function genErrMsg(\Exception $e){
$err_arr = [
'msg'=>$e->getMessage(),
'file'=>$e->getFile(),
'line'=>$e->getLine(),
];
return json_encode($err_arr,JSON_UNESCAPED_UNICODE);
}
注3:writeLoc方法
public static function writeLoc($msg,$class,$func,$is_err=false){
$class = str_replace('\\','/',$class);
$class_arr = explode('/',$class);
$file_name = 'writeLoc/'.array_pop($class_arr);
$msg = $class.'->'.$func.'()::'.$msg;
if($is_err===true){
self::LogDiyErr($msg,$file_name);
}else{
self::LogDiyInfo($msg,$file_name);
}
}
注4:Blogger類
namespace App\Libraries;
use Illuminate\Log\Writer;
use Monolog\Logger;
class Blogger
{
public static function __callStatic($name,$arguments) {
$msg = $arguments[0];
$file_name = isset($arguments[1])?$arguments[1]:$name;//獲取檔名稱,預設以日誌型別作為日誌檔名
$log= new Writer(new Logger(config('app.env')));
$log->useFiles(storage_path().'/logs/'.$file_name.'.log');//每個錯誤型別一個檔案
$log->$name($msg);
}
}