|
|
<?php
|
|
|
namespace App\Services;
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
class LogService
|
|
|
{
|
|
|
|
|
|
public function RequestLog($arr){ //记录请求日志
|
|
|
self::CheckTableName();
|
|
|
$table_name='zz_request_log_' . date('ym');
|
|
|
$response_data =self::JsonEncode($arr['response_data']);
|
|
|
$header_data = self::JsonEncode($arr['request_header']);
|
|
|
$post_data = self::JsonEncode($arr['post_data']);
|
|
|
$get_data = json_encode($arr['get_data'], JSON_UNESCAPED_UNICODE);
|
|
|
$milliseconds = round(microtime(true) * 1000);
|
|
|
$date = date("Y-m-d H:i:s", $milliseconds / 1000);
|
|
|
$formatted_date = sprintf("%s.%03d", $date, $milliseconds % 1000);
|
|
|
|
|
|
$i=DB::insert("insert into ".$table_name." (request_ip, response_data,header_data,post_data,get_data,request_url,create_time,update_time)
|
|
|
values (?,?,?,?,?,?,?,?)",[$arr['ip'],$response_data,$header_data,$post_data,$get_data,$arr['request_url'],$formatted_date,$formatted_date]);
|
|
|
}
|
|
|
public static function CheckTableName(){ // 查看日志表是否存在,每月一个表,如果没有就创建
|
|
|
$table_name='zz_request_log_' . date('ym');
|
|
|
if(Schema::hasTable($table_name)){
|
|
|
|
|
|
}else{
|
|
|
Schema::create($table_name, function (Blueprint $table) {
|
|
|
$table->id();
|
|
|
$table->string('request_ip', 15);
|
|
|
$table->text('post_data');
|
|
|
$table->text('get_data');
|
|
|
$table->text('header_data');
|
|
|
$table->text('response_data')->nullable();
|
|
|
$table->string('request_url', 300);
|
|
|
$table->string('create_time', 30);
|
|
|
$table->string('update_time', 30);
|
|
|
$table->timestamps();
|
|
|
});
|
|
|
}
|
|
|
}
|
|
|
public static function JsonEncode($data){ //格式化数据,转json
|
|
|
$post_data =$data;
|
|
|
foreach ($post_data as $key => $post_datum) {
|
|
|
$str_len = mb_strlen(json_encode($post_datum, JSON_UNESCAPED_UNICODE));
|
|
|
$str_size = $str_len / 1024;
|
|
|
if ($str_size > 10) {
|
|
|
$post_data["$key"] = 'Row size too large';
|
|
|
}
|
|
|
}
|
|
|
$post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
|
|
|
$str_len = mb_strlen($post_data);
|
|
|
$str_size = $str_len / 1024;
|
|
|
if ($str_size > 40) $post_data = '{"data":"Row size too large"}';
|
|
|
return $post_data;
|
|
|
}
|
|
|
}
|