78 lines
2.0 KiB
PHP
78 lines
2.0 KiB
PHP
<?php
|
|
namespace app\middleware;
|
|
|
|
use app\model\RequestTracks;
|
|
|
|
class DataTracker
|
|
{
|
|
// 不需要埋点的路径
|
|
protected $excludePaths = [
|
|
'/user/login'
|
|
];
|
|
|
|
public function process($request, \Closure $next)
|
|
{
|
|
if ($this->shouldSkipTracking($request)) {
|
|
return $next($request);
|
|
}
|
|
// 前置处理
|
|
$this->logRequestData($request);
|
|
|
|
$response = $next($request);
|
|
|
|
// 后置处理
|
|
// $this->logResponseData($response);
|
|
|
|
return $response;
|
|
}
|
|
|
|
protected function shouldSkipTracking($request)
|
|
{
|
|
$currentPath = $request->path();
|
|
|
|
$eventTracking = config('const.event_tracking');
|
|
|
|
// 检查是否在排除列表中
|
|
// foreach ($this->excludePaths as $path) {
|
|
// if (str_starts_with($currentPath, $path)) {
|
|
// return true;
|
|
// }
|
|
// }
|
|
|
|
if (in_array($currentPath, $eventTracking)) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
protected function logRequestData($request)
|
|
{
|
|
$trackData = [
|
|
'app_id' => 'crm/api',
|
|
'user_id' => $request->user['id']??0,
|
|
'ip' => $request->getRealIp(),
|
|
'method' => $request->method(),
|
|
'path' => $request->path(),
|
|
'params' => json_encode($request->all()),
|
|
'header' => json_encode($request->header()),
|
|
'uuid' => $this->generateTraceId(),
|
|
'user_agent' => $request->header('user-agent'),
|
|
'referer' => $request->header('referer'),
|
|
];
|
|
$requestTrack = RequestTracks::create($trackData);
|
|
}
|
|
|
|
|
|
|
|
protected function generateTraceId()
|
|
{
|
|
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
|
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
|
|
mt_rand(0, 0xffff),
|
|
mt_rand(0, 0x0fff) | 0x4000,
|
|
mt_rand(0, 0x3fff) | 0x8000,
|
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
|
|
);
|
|
}
|
|
} |