You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.9 KiB
76 lines
1.9 KiB
<?php
|
|
|
|
namespace app\home\middleware;
|
|
|
|
use app\home\service\BaseHomeService;
|
|
use app\model\UserModel;
|
|
use think\Response;
|
|
use think\facade\Log;
|
|
use think\Request;
|
|
|
|
/**
|
|
* @desc 记录接口日志
|
|
*/
|
|
class ApiLogMiddleware
|
|
{
|
|
|
|
// 配置需要记录日志的接口(路径部分)
|
|
protected $logRoutes = [
|
|
'phone_login',
|
|
'email_login',
|
|
'email',
|
|
'email_reg',
|
|
'sms',
|
|
'sms_reg',
|
|
'forget_email',
|
|
'forget_sms',
|
|
'user_recharge',
|
|
'transfer',
|
|
'user_drawal',
|
|
'pre_stock/order',
|
|
'fund/order',
|
|
];
|
|
|
|
|
|
public function handle(Request $request, \Closure $next)
|
|
{
|
|
|
|
// OPTIONS 请求直接返回空响应
|
|
if ($request->method(true) === 'OPTIONS') {
|
|
return response()->send();
|
|
}
|
|
$path = $request->pathinfo();
|
|
$shouldLog = in_array($path, $this->logRoutes);
|
|
$logData = [];
|
|
if ($shouldLog) {
|
|
$ip = (new BaseHomeService())->getClientRealIp();
|
|
$params = $request->param();
|
|
$logData = [
|
|
'url' => $request->url(),
|
|
'method' => $request->method(),
|
|
'params' => $params,
|
|
'ip' => $ip,
|
|
];
|
|
// 如果登录了,记录 user_id
|
|
if (!empty($request->user_id)) {
|
|
$logData['user_id'] = $request->user_id;
|
|
}
|
|
}
|
|
|
|
$response = $next($request);
|
|
|
|
if ($shouldLog && $response instanceof Response) {
|
|
|
|
$logData['response'] = $response->getData();
|
|
}
|
|
//写入redis
|
|
if (!empty($logData)) {
|
|
$logData['user_agent'] = $request->header('user-agent');
|
|
$logData['created_at'] = date('Y-m-d H:i:s');
|
|
// 记录日志到 Redis
|
|
\think\facade\Cache::store('redis')->lpush('api_log', json_encode($logData));
|
|
}
|
|
return $response;
|
|
|
|
}
|
|
}
|
|
|