#在\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);
}
}


posted on 2020-09-14 15:34  cyqAkin  阅读(543)  评论(0编辑  收藏  举报