| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- <?php
- namespace App\Module\Game\Logics;
- use App\Module\Game\Models\UserLog;
- use App\Module\Game\Models\UserLogClearRecord;
- use Illuminate\Pagination\LengthAwarePaginator;
- use Illuminate\Support\Facades\DB;
- use UCore\Helper\Logger;
- /**
- * 用户日志逻辑类
- *
- * 负责处理用户日志的业务逻辑,包括:
- * 1. 日志记录
- * 2. 日志查询
- * 3. 日志清理
- * 4. 批量处理
- */
- class UserLogLogic
- {
- /**
- * 记录用户日志
- *
- * @param int $userId 用户ID
- * @param string $message 日志消息
- * @param string|null $sourceType 来源类型
- * @param int|null $sourceId 来源记录ID
- * @param string|null $sourceTable 来源表名
- * @return UserLog|null
- */
- public static function log(
- int $userId,
- string $message,
- ?string $sourceType = null,
- ?int $sourceId = null,
- ?string $sourceTable = null
- ): ?UserLog {
- try {
- $userLog = new UserLog();
- $userLog->user_id = $userId;
- $userLog->message = $message;
- $userLog->source_type = $sourceType;
- $userLog->source_id = $sourceId;
- $userLog->source_table = $sourceTable;
- $userLog->save();
- return $userLog;
- } catch (\Exception $e) {
- Logger::exception('记录用户日志失败', $e, [
- 'user_id' => $userId,
- 'message' => $message,
- 'source_type' => $sourceType,
- 'source_id' => $sourceId,
- 'source_table' => $sourceTable,
- ]);
- return null;
- }
- }
- /**
- * 批量记录用户日志
- *
- * @param array $logs 日志数据数组
- * @return bool
- */
- public static function batchLog(array $logs): bool
- {
- try {
- DB::beginTransaction();
- foreach ($logs as $logData) {
- $userLog = new UserLog();
- $userLog->user_id = $logData['user_id'];
- $userLog->message = $logData['message'];
- $userLog->source_type = $logData['source_type'] ?? null;
- $userLog->source_id = $logData['source_id'] ?? null;
- $userLog->source_table = $logData['source_table'] ?? null;
- $userLog->save();
- }
- DB::commit();
- return true;
- } catch (\Exception $e) {
- DB::rollBack();
- Logger::exception('批量记录用户日志失败', $e, [
- 'logs_count' => count($logs),
- ]);
- return false;
- }
- }
- /**
- * 获取用户日志列表
- *
- * @param int $userId 用户ID
- * @param int $page 页码
- * @param int $pageSize 每页数量
- * @param array $filters 过滤条件
- * @return LengthAwarePaginator
- */
- public static function getUserLogs(
- int $userId,
- int $page = 1,
- int $pageSize = 20,
- array $filters = []
- ): LengthAwarePaginator {
- try {
- $query = UserLog::byUser($userId)->latest();
- // 获取用户的最后清理时间,只返回清理时间之后的日志
- $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
- if ($lastClearTime) {
- $query->where('created_at', '>', $lastClearTime);
- }
- // 应用过滤条件
- if (!empty($filters['source_type'])) {
- $query->bySourceType($filters['source_type']);
- }
- if (!empty($filters['start_time']) && !empty($filters['end_time'])) {
- $query->byTimeRange($filters['start_time'], $filters['end_time']);
- }
- if (!empty($filters['keyword'])) {
- $query->where('message', 'like', '%' . $filters['keyword'] . '%');
- }
- return $query->paginate($pageSize, ['*'], 'page', $page);
- } catch (\Exception $e) {
- Logger::exception('获取用户日志列表失败', $e, [
- 'user_id' => $userId,
- 'page' => $page,
- 'page_size' => $pageSize,
- 'filters' => $filters,
- ]);
- // 返回空的分页结果
- return new LengthAwarePaginator([], 0, $pageSize, $page);
- }
- }
- /**
- * 清空用户日志(逻辑清理)
- * 不真实删除日志,而是记录清理时间,只返回清理时间之后的日志给用户
- * 这样可以避免影响日志收集备份工作
- *
- * @param int $userId 用户ID
- * @return bool
- */
- public static function clearUserLogs(int $userId): bool
- {
- try {
- // 获取当前时间作为清理时间
- $clearTime = now();
- // 记录用户的清理时间
- UserLogClearRecord::setUserClearTime($userId, $clearTime);
- Logger::info('清空用户日志成功(逻辑清理)', [
- 'user_id' => $userId,
- 'clear_time' => $clearTime->toDateTimeString(),
- ]);
- return true;
- } catch (\Exception $e) {
- Logger::exception('清空用户日志失败', $e, [
- 'user_id' => $userId,
- ]);
- return false;
- }
- }
- /**
- * 清理过期日志
- *
- * @param int $days 保留天数
- * @return int 删除的记录数
- */
- public static function cleanExpiredLogs(int $days = 30): int
- {
- try {
- $expiredDate = now()->subDays($days);
- $deletedCount = UserLog::where('created_at', '<', $expiredDate)->delete();
- Logger::info('清理过期日志成功', [
- 'days' => $days,
- 'expired_date' => $expiredDate->toDateTimeString(),
- 'deleted_count' => $deletedCount,
- ]);
- return $deletedCount;
- } catch (\Exception $e) {
- Logger::exception('清理过期日志失败', $e, [
- 'days' => $days,
- ]);
- return 0;
- }
- }
- /**
- * 获取用户日志统计信息
- *
- * @param int $userId 用户ID
- * @return array
- */
- public static function getUserLogStats(int $userId): array
- {
- try {
- // 获取用户的最后清理时间,只统计清理时间之后的日志
- $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
- $baseQuery = UserLog::byUser($userId);
- if ($lastClearTime) {
- $baseQuery->where('created_at', '>', $lastClearTime);
- }
- $stats = [
- 'total_count' => (clone $baseQuery)->count(),
- 'today_count' => (clone $baseQuery)
- ->whereDate('created_at', today())
- ->count(),
- 'week_count' => (clone $baseQuery)
- ->where('created_at', '>=', now()->startOfWeek())
- ->count(),
- 'month_count' => (clone $baseQuery)
- ->where('created_at', '>=', now()->startOfMonth())
- ->count(),
- ];
- // 按来源类型统计
- $sourceTypeStats = (clone $baseQuery)
- ->select('source_type', DB::raw('count(*) as count'))
- ->whereNotNull('source_type')
- ->groupBy('source_type')
- ->pluck('count', 'source_type')
- ->toArray();
- $stats['source_type_stats'] = $sourceTypeStats;
- return $stats;
- } catch (\Exception $e) {
- Logger::exception('获取用户日志统计信息失败', $e, [
- 'user_id' => $userId,
- ]);
- return [];
- }
- }
- /**
- * 检查用户是否有日志记录
- *
- * @param int $userId 用户ID
- * @return bool
- */
- public static function hasUserLogs(int $userId): bool
- {
- try {
- $query = UserLog::byUser($userId);
- // 获取用户的最后清理时间,只检查清理时间之后的日志
- $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
- if ($lastClearTime) {
- $query->where('created_at', '>', $lastClearTime);
- }
- return $query->exists();
- } catch (\Exception $e) {
- Logger::exception('检查用户日志记录失败', $e, [
- 'user_id' => $userId,
- ]);
- return false;
- }
- }
- /**
- * 获取最新的用户日志
- *
- * @param int $userId 用户ID
- * @param int $limit 数量限制
- * @return \Illuminate\Database\Eloquent\Collection
- */
- public static function getLatestUserLogs(int $userId, int $limit = 10)
- {
- try {
- $query = UserLog::byUser($userId)->latest();
- // 获取用户的最后清理时间,只返回清理时间之后的日志
- $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
- if ($lastClearTime) {
- $query->where('created_at', '>', $lastClearTime);
- }
- return $query->limit($limit)->get();
- } catch (\Exception $e) {
- Logger::exception('获取最新用户日志失败', $e, [
- 'user_id' => $userId,
- 'limit' => $limit,
- ]);
- return collect();
- }
- }
- }
|