97 lines
3.0 KiB
PHP
97 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace app\admin\controller\OperationLog;
|
|
|
|
use app\model\OperationLog;
|
|
use think\facade\Request;
|
|
use think\facade\Session;
|
|
|
|
/**
|
|
* 操作日志记录助手类
|
|
*/
|
|
class OperationLogHelper
|
|
{
|
|
/**
|
|
* 记录操作日志
|
|
* @param string $module 操作模块
|
|
* @param string $action 操作动作
|
|
* @param array $requestData 请求数据
|
|
* @param array $responseData 响应数据
|
|
* @param int $status 操作状态:1-成功,0-失败
|
|
* @param string $errorMessage 错误信息
|
|
* @param float $executionTime 执行时间(秒)
|
|
* @return bool
|
|
*/
|
|
public static function log(
|
|
string $module,
|
|
string $action,
|
|
array $requestData = [],
|
|
array $responseData = [],
|
|
int $status = 1,
|
|
string $errorMessage = '',
|
|
float $executionTime = 0.0
|
|
): bool {
|
|
try {
|
|
// 获取用户信息
|
|
$userInfo = Session::get('user');
|
|
$userId = $userInfo['id'] ?? 0;
|
|
$userAccount = $userInfo['account'] ?? '';
|
|
$userName = $userInfo['name'] ?? '';
|
|
|
|
// 获取请求信息
|
|
$method = Request::method();
|
|
$url = Request::url(true);
|
|
$ip = Request::ip();
|
|
$userAgent = Request::header('user-agent', '');
|
|
|
|
// 过滤敏感信息(如密码)
|
|
$filteredRequestData = self::filterSensitiveData($requestData);
|
|
|
|
// 记录日志
|
|
OperationLog::create([
|
|
'user_id' => $userId,
|
|
'user_account' => $userAccount,
|
|
'user_name' => $userName,
|
|
'module' => $module,
|
|
'action' => $action,
|
|
'method' => $method,
|
|
'url' => $url,
|
|
'ip' => $ip,
|
|
'user_agent' => $userAgent,
|
|
'request_data' => !empty($filteredRequestData) ? json_encode($filteredRequestData, JSON_UNESCAPED_UNICODE) : null,
|
|
'response_data' => !empty($responseData) ? json_encode($responseData, JSON_UNESCAPED_UNICODE) : null,
|
|
'status' => $status,
|
|
'error_message' => $errorMessage,
|
|
'execution_time' => $executionTime,
|
|
]);
|
|
|
|
return true;
|
|
} catch (\Exception $e) {
|
|
// 记录日志失败不应该影响主流程,只记录错误
|
|
error_log('操作日志记录失败: ' . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 过滤敏感数据
|
|
* @param array $data
|
|
* @return array
|
|
*/
|
|
private static function filterSensitiveData(array $data): array
|
|
{
|
|
$sensitiveKeys = ['password', 'pwd', 'token', 'api_key', 'secret'];
|
|
|
|
foreach ($data as $key => $value) {
|
|
if (in_array(strtolower($key), $sensitiveKeys)) {
|
|
$data[$key] = '***';
|
|
} elseif (is_array($value)) {
|
|
$data[$key] = self::filterSensitiveData($value);
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
}
|
|
|