日报
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
namespace app\middleware;
|
||||
|
||||
use app\model\RequestTracks;
|
||||
|
||||
class DataTracker
|
||||
{
|
||||
public function process($request, \Closure $next)
|
||||
{
|
||||
// 前置处理
|
||||
if($request->path() != 'user/login'){
|
||||
return $request;
|
||||
}
|
||||
$this->logRequestData($request);
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
// 后置处理
|
||||
// $this->logResponseData($response);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
protected function logRequestData($request)
|
||||
{
|
||||
$trackData = [
|
||||
'app_id' => 'crm/api',
|
||||
'user_id' => $request->user['id'],
|
||||
'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 sendToQueue($data)
|
||||
{
|
||||
// 使用Redis队列
|
||||
try {
|
||||
redis()->lpush('track_queue', json_encode($data));
|
||||
} catch (\Exception $e) {
|
||||
// 失败降级处理
|
||||
file_put_contents(
|
||||
runtime_path('logs/track_fallback.log'),
|
||||
json_encode($data) . PHP_EOL,
|
||||
FILE_APPEND
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user