[2023-12-29 06:53:34] local.INFO:
url : http://laravel.test/api/test?k1=v1&k2=v2
method : POST
ip : 127.0.0.1
ua : PostmanRuntime-ApipostRuntime/1.1.0
payload : {"key1":"val1","key2":"val2"}
file : {"file":["测试图片1.jpeg","测试图片2.jpeg"]}
header : {"content-type":"multipart\/form-data; boundary=--------------------------771657688394796615738323"}
user_id : 0
time : 53.10
mem : 15.54 MB
code : 200
response : {"code":0,"msg":"","data":[]}
#在config/logging.php中的channels项添加如下配置
'request' => [
'driver' => 'daily',
'path' => storage_path('logs/request.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 3,
'permission' => 0777
],
#进入laravel所在目录,用artisan命令创建中间件
php artisan make:middleware RequestMiddleware
//在app/Http/Kernel.php文件的protected $middleware数组中追加一行,用于注册全局中间件
\App\Http\Middleware\RequestMiddleware::class
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* @Class RequestMiddleware 记录请求日志,方便开发者调试
* @package App\Http\Middleware
*/
class RequestMiddleware {
/**
* @function 设置不记录日志的url
* @param \Illuminate\Http\Request $request
* @return array
* @other 排除规则依照request()->is()方法
*/
private function setExceptUrl($request) {
return [
'admin/logs*', 'admin/logs/*',
];
}
/**
* @function 设置不记录响应日志的url
* @param \Illuminate\Http\Request $request
* @return array
* @other 排除规则依照request()->is()方法
*/
private function setExceptRecordResponseDataUrl($request) {
return [
];
}
/**
* @function 设置不记录的荷载项
* @param \Illuminate\Http\Request $request
* @return array
* @other 比如防止CSRF的_token
*/
private function setExceptPayload($request) {
return [
'_token', '_method'
];
}
/**
* @function 设置不记录日志的请求头
* @param \Illuminate\Http\Request $request
* @return array
* @other void
*/
private function setExceptHeader($request) {
return [
//官方
'accept', 'accept-encoding', 'accept-language', 'authorization',
'access-control-allow-credentials', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-allow-origin',
'access-control-expose-headers', 'access-control-max-age', 'access-control-request-headers', 'access-control-request-method',
'cache-control', 'charset', 'connection', 'content-length', 'content-type_except', 'cookie',
'host', 'origin', 'pragma', 'referer',
'sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform', 'sec-fetch-dest', 'sec-fetch-mode', 'sec-fetch-site',
'upgrade-insecure-requests', 'user-agent', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-proto', 'x-requested-with',
//自定义
];
}
/**
* @function 是否记录非json格式的响应的数据
* @param \Illuminate\Http\Request $request
* @return bool
* @other void
*/
private function isRecordNotJsonResponseData($request) {
return false;
}
//------------------------------------------------此分割线以下代码无需修改------------------------------------------------
/**
* @function 请求日志中间件
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
* @other void
*/
public function handle(Request $request, Closure $next) {
if($this->getExceptUrl($request)) {
return $next($request);
}
$request_and_response = [
'url' => $this->getFullUrl($request),
'method' => $this->getRequestMethod($request),
'ip' => $this->getClientIp($request),
'ua' => $this->getUa($request),
'payload' => $this->getRequestPayload($request),
'file' => $this->getClearRequestFile($request),
'header' => $this->getClearRequestHeader($request),
'time' => 0,
'mem' => '0B',
'code' => 0,
'response' => '""',
];
$is_except_record_response_data_url = $this->getExceptRecordResponseDataUrl($request);
if($is_except_record_response_data_url) {
Log::channel('request')->info($this->dataFormat($request_and_response));
}
$start = microtime(true);
$response = $next($request);
$end = microtime(true);
if(! $is_except_record_response_data_url) {
$request_and_response['time'] = bcmul(bcsub($end, $start, 6), 1000, 2);
$request_and_response['mem'] = $this->getUsageMemory();
$request_and_response['code'] = $this->getHttpCode($response);
$request_and_response['response'] = $this->responseFormat($request, $response);
Log::channel('request')->info($this->dataFormat($request_and_response));
}
return $response;
}
/**
* @function 获取不记录日志的url
* @param \Illuminate\Http\Request $request
* @return bool
* @other void
*/
private function getExceptUrl($request) {
$blacklist = array_filter($this->setExceptUrl($request));
if(! $blacklist) {
return false;
}
foreach($blacklist as $every_blacklist) {
if($request->is($every_blacklist)) {
return true;
}
}
return false;
}
/**
* @function 获取不记录响应日志的url
* @param \Illuminate\Http\Request $request
* @return bool
* @other void
*/
private function getExceptRecordResponseDataUrl($request) {
$blacklist = array_filter($this->setExceptRecordResponseDataUrl($request));
if(! $blacklist) {
return false;
}
foreach($blacklist as $every_blacklist) {
if($request->is($every_blacklist)) {
return true;
}
}
return false;
}
/**
* @function 获取完整的请求路径
* @param \Illuminate\Http\Request $request
* @return string
* @other void
*/
private function getFullUrl($request) {
return urldecode($request->fullUrl());
}
/**
* @function 获取请求方式
* @param \Illuminate\Http\Request $request
* @return string
* @other 由于laravel存在_method覆盖机制,若有括号,则括号内的为真正的请求方式
*/
private function getRequestMethod($request) {
$real_method = $_SERVER['REQUEST_METHOD'] ?? '';
//防止乱传参导致的错误
try{
$laravel_method = $request->method();
} catch (\Exception $exception) {
$laravel_method = $real_method;
}
if($real_method === $laravel_method) {
return $real_method;
}
return "{$laravel_method}({$real_method})";
}
/**
* @function 获取客户端的IP
* @param \Illuminate\Http\Request $request
* @return string
* @other void
*/
private function getClientIp($request) {
return $request->getClientIp();
}
/**
* @function 获取用户代理
* @param \Illuminate\Http\Request $request
* @return string
* @other void
*/
private function getUa($request) {
return $request->header('user-agent') ?? '""';
}
/**
* @function 获取请求荷载,包含x-www-form-urlencoded、multipart/form-data、application/json、application/xml等纯文本荷载数据
* @param \Illuminate\Http\Request $request
* @return array
* @other void
*/
private function getRequestPayload($request) {
if($request->method() === 'GET') {
return [];
}
$except = collect($request->query())->keys()->merge($this->setExceptPayload($request))->filter();
$input = collect($request->input())->except($except)->map(function ($val) {
if (is_null($val)) {
return '';
}
return $val;
})->toArray();
if($input) {
return $input;
}
$raw = $request->getContent();
//兼容application/xml、text/xml
if(strstr($request->header('content-type'), 'xml')) {
if(! $raw) {
return [];
}
if(! $this->isXml($raw)) {
return [$raw];
}
return json_decode(json_encode(simplexml_load_string(str_replace(["\r", "\n"], '', $raw))), true);
}
return array_filter([$raw]);
}
/**
* @function 获取简洁的文件上传数据
* @param \Illuminate\Http\Request $request
* @return array
* @other void
*/
private function getClearRequestFile($request) {
return collect($request->allFiles())->map(function($val) {
if(is_array($val)) {
$res = collect($val)->map(function($v) {
return $v->getClientOriginalName();
});
} else {
$res = $val->getClientOriginalName();
}
return $res;
})->toArray();
}
/**
* @function 获取干净的请求头
* @param \Illuminate\Http\Request $request
* @return array
* @other void
*/
private function getClearRequestHeader($request) {
return collect($request->header())->except(array_filter($this->setExceptHeader($request)))->map(function($every_header, $key) {
return (count($every_header) === 1) ? collect($every_header)->values()->first() : $every_header;
})->toArray();
}
/**
* @function 通过token获取user_id,这个有伪造的风险
* @param \Illuminate\Http\Request $request
* @return int
* @other void
*/
private function getIdWithToken($request) {
$token = $request->header('authorization');
if(! $token) {
return 0;
}
$payload = (explode('.', $token)[1]) ?? null;
if(is_null($payload)) {
return 0;
}
$json = base64_decode($payload);
$arr = json_decode($json, true);
if(is_null($arr)) {
return 0;
}
return $arr['sub'] ?? 0;
}
/**
* @function 获取状态码
* @param \Illuminate\Http\JsonResponse|\Illuminate\Http\Response $response
* @return string|array
* @other void
*/
private function getHttpCode($response) {
return $response->getStatusCode();
}
/**
* @function 格式化响应数据
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\JsonResponse|\Illuminate\Http\Response $response
* @return string|array
* @other void
*/
private function responseFormat($request, $response) {
if($response instanceof \Illuminate\Http\JsonResponse) {
return collect($response->getData())->toArray();
}
if(! $this->isRecordNotJsonResponseData($request)) {
return '""';
}
if($response instanceof \Illuminate\Http\Response) {
return $response->getContent();
}
return '""';
}
/**
* @function 格式化数组并转换为字符串
* @param $request_and_response array
* @return string
* @other void
*/
private function dataFormat($request_and_response) {
$str = "\n";
foreach($request_and_response as $k => $v) {
$k = str_pad($k, 9, ' ', STR_PAD_RIGHT);
$v = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
$str .= "{$k}: {$v}\n";
}
return $str;
}
/**
* @function 获取程序占用的内存
* @return string
* @other void
*/
private function getUsageMemory() {
$bytes = memory_get_usage();
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes /= pow(1024, ($i = floor(log($bytes, 1024))));
return round($bytes, 2) . ' ' . $units[$i];
}
/**
* @function 判断是否是xml
* @param $str string 要判断的xml数据
* @return bool
*/
private function isXml($str) {
libxml_use_internal_errors(true);
simplexml_load_string($str);
$errors = libxml_get_errors();
libxml_clear_errors();
return ! $errors;
}
}
// [1.2345678912345678e+17]
echo json_encode([123456789123456789.123456789123456789]);
//Array ( [0] => 1.2345678912346E+17 )
print_r(json_decode('[123456789123456789.123456789123456789]', true));
这个是编程语言层面的问题,所以在传输大数据时一定要转化为字符串去解决精度问题。
// ["123456789123456789.123456789123456789"]
echo json_encode(["123456789123456789.123456789123456789"]);
//Array ( [0] => 123456789123456789.123456789123456789)
print_r(json_decode('["123456789123456789.123456789123456789"]', true));