Files
datahub/backend/app/Service/OperationLogService.php
T

89 lines
2.6 KiB
PHP
Raw Normal View History

2026-03-17 15:55:13 +08:00
<?php
declare(strict_types=1);
namespace App\Service;
use App\Middleware\RequestLogMiddleware;
use App\Model\OperationLog;
use App\Model\User;
use App\Utils\Log;
use Psr\Http\Message\ServerRequestInterface;
use Qbhy\HyperfAuth\AuthManager;
use Swoole\Coroutine;
class OperationLogService
{
/**
* 记录操作日志(异步写库,不阻塞业务)
*/
public static function log(
int $user_id,
string $action,
string $target_type,
?int $target_id,
string $description,
?array $detail = null,
?string $ip = null,
): void {
Coroutine::defer(static function () use (
$user_id, $action, $target_type, $target_id, $description, $detail, $ip
): void {
try {
OperationLog::query()->create([
'user_id' => $user_id,
'action' => $action,
'target_type' => $target_type,
'target_id' => $target_id,
'description' => $description,
'detail' => $detail,
'ip' => $ip,
]);
} catch (\Throwable $e) {
Log::get()->error('OperationLogService: 写入操作日志失败', [
'error' => $e->getMessage(),
'action' => $action,
]);
}
});
}
/**
* 从当前请求上下文获取客户端 IP
*/
public static function getRequestIp(): ?string
{
try {
$container = \Hyperf\Context\ApplicationContext::getContainer();
$request = $container->get(ServerRequestInterface::class);
return RequestLogMiddleware::getClientIp($request);
2026-03-18 08:37:14 +08:00
} catch (\Throwable $e) {
Log::get()->warning('OperationLogService: 获取客户端 IP 失败', [
'error' => $e->getMessage(),
]);
2026-03-17 15:55:13 +08:00
return null;
}
}
/**
* 从当前认证上下文获取用户 ID
*/
public static function getCurrentUserId(): ?int
{
try {
$container = \Hyperf\Context\ApplicationContext::getContainer();
$auth = $container->get(AuthManager::class);
$user = $auth->guard('jwt')->user();
if ($user instanceof User) {
return $user->id;
}
return $user?->getId();
2026-03-18 08:37:14 +08:00
} catch (\Throwable $e) {
Log::get()->warning('OperationLogService: 获取当前用户 ID 失败', [
'error' => $e->getMessage(),
]);
2026-03-17 15:55:13 +08:00
return null;
}
}
}