This commit is contained in:
87
app/Job/OpLogsJob.php
Executable file
87
app/Job/OpLogsJob.php
Executable file
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Job;
|
||||
|
||||
use App\Constants\SourceConst;
|
||||
use App\JsonRpc\EasyAppServiceInterface;
|
||||
use App\Model\OperatorLogs;
|
||||
use Exception;
|
||||
use Hyperf\Collection\Collection;
|
||||
use function Hyperf\Collection\collect;
|
||||
use function Hyperf\Config\config;
|
||||
use function Hyperf\Support\make;
|
||||
|
||||
/**
|
||||
* Author: ykxiao
|
||||
* Date: 2024/12/25
|
||||
* Time: 上午9:36
|
||||
* Description: 操作日志记录任务.
|
||||
*
|
||||
* (c) ykxiao <yk_9001@hotmail.com>
|
||||
*
|
||||
* This source file is subject to the MIT license that is bundled
|
||||
* with this source code in the file LICENSE.
|
||||
*/
|
||||
class OpLogsJob extends BaseJob
|
||||
{
|
||||
/**
|
||||
* 处理日志记录逻辑。
|
||||
* 该方法首先尝试获取日志操作信息,如果信息不为空,则根据这些信息填充操作日志数组,
|
||||
* 包括日志类型、标题、计时器以及来源信息。随后,它将尝试获取当前用户信息,并最后创建操作日志记录。
|
||||
*
|
||||
* @return void 该方法没有返回值。
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function process(): void
|
||||
{
|
||||
// 尝试获取日志操作信息
|
||||
$logAction = $this->getLogAction();
|
||||
// 如果日志操作信息为空,则直接返回,不进行后续操作
|
||||
if ($logAction->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$rpcResult = make(EasyAppServiceInterface::class)->getClientIPInfo(['ip' => $this->data['ip']]);
|
||||
|
||||
// 构建请求日志消息
|
||||
$clientIPInfo = $rpcResult['result']['ip_info'] ?? '';
|
||||
|
||||
// 从日志操作信息中提取日志类型,并保存到操作日志数组中
|
||||
$type = $logAction->first()['id'] ?? 0;
|
||||
$this->data['type'] = $type;
|
||||
// 同样从日志操作信息中提取日志标题,并保存
|
||||
$this->data['log_title'] = $logAction->first()['name'] ?? '';
|
||||
// 初始化计时器
|
||||
$this->data['timer'] = 0;
|
||||
// 设置日志来源,优先使用已存在的来源信息,如果不存在,则尝试从路由前缀获取来源信息
|
||||
$this->data['source'] = $this->data['source'] ?: $this->getRoutePrefix();
|
||||
// 查询IP属地,并保存到操作日志数组中
|
||||
$this->data['location'] = $clientIPInfo;
|
||||
|
||||
// 创建操作日志记录
|
||||
OperatorLogs::query()->create($this->data);
|
||||
}
|
||||
|
||||
|
||||
private function getLogAction(): Collection
|
||||
{
|
||||
$defineLogs = config('op_logs');
|
||||
return collect($defineLogs)->where('action', '=', $this->data['action']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取路由前缀.
|
||||
*/
|
||||
private function getRoutePrefix(): int
|
||||
{
|
||||
$arr = explode('/', $this->data['route']);
|
||||
$res = $arr[0] ?? '';
|
||||
return match ($res) {
|
||||
'api' => SourceConst::SOURCE_PC,
|
||||
'mobile' => SourceConst::SOURCE_MOBILE,
|
||||
default => 0,
|
||||
};
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user