UserLogLogic.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. namespace App\Module\Game\Logics;
  3. use App\Module\Game\Models\UserLog;
  4. use App\Module\Game\Models\UserLogClearRecord;
  5. use Illuminate\Pagination\LengthAwarePaginator;
  6. use Illuminate\Support\Facades\DB;
  7. use UCore\Helper\Logger;
  8. /**
  9. * 用户日志逻辑类
  10. *
  11. * 负责处理用户日志的业务逻辑,包括:
  12. * 1. 日志记录
  13. * 2. 日志查询
  14. * 3. 日志清理
  15. * 4. 批量处理
  16. */
  17. class UserLogLogic
  18. {
  19. /**
  20. * 记录用户日志
  21. *
  22. * @param int $userId 用户ID
  23. * @param string $message 日志消息
  24. * @param string|null $sourceType 来源类型
  25. * @param int|null $sourceId 来源记录ID
  26. * @param string|null $sourceTable 来源表名
  27. * @return UserLog|null
  28. */
  29. public static function log(
  30. int $userId,
  31. string $message,
  32. ?string $sourceType = null,
  33. ?int $sourceId = null,
  34. ?string $sourceTable = null
  35. ): ?UserLog {
  36. try {
  37. $userLog = new UserLog();
  38. $userLog->user_id = $userId;
  39. $userLog->message = $message;
  40. $userLog->source_type = $sourceType;
  41. $userLog->source_id = $sourceId;
  42. $userLog->source_table = $sourceTable;
  43. $userLog->save();
  44. return $userLog;
  45. } catch (\Exception $e) {
  46. Logger::exception('记录用户日志失败', $e, [
  47. 'user_id' => $userId,
  48. 'message' => $message,
  49. 'source_type' => $sourceType,
  50. 'source_id' => $sourceId,
  51. 'source_table' => $sourceTable,
  52. ]);
  53. return null;
  54. }
  55. }
  56. /**
  57. * 批量记录用户日志
  58. *
  59. * @param array $logs 日志数据数组
  60. * @return bool
  61. */
  62. public static function batchLog(array $logs): bool
  63. {
  64. if (empty($logs)) {
  65. return true;
  66. }
  67. try {
  68. DB::beginTransaction();
  69. // 准备批量插入数据
  70. $insertData = [];
  71. $now = now();
  72. foreach ($logs as $logData) {
  73. $insertData[] = [
  74. 'user_id' => $logData['user_id'],
  75. 'message' => $logData['message'],
  76. 'source_type' => $logData['source_type'] ?? null,
  77. 'source_id' => $logData['source_id'] ?? null,
  78. 'source_table' => $logData['source_table'] ?? null,
  79. 'original_time' => $logData['original_time'] ?? $now,
  80. 'collected_at' => $logData['collected_at'] ?? $now,
  81. 'created_at' => $now,
  82. ];
  83. }
  84. // 使用批量插入,每次最多插入1000条记录
  85. $chunks = array_chunk($insertData, 1000);
  86. foreach ($chunks as $chunk) {
  87. UserLog::insert($chunk);
  88. }
  89. DB::commit();
  90. Logger::info('批量记录用户日志成功', [
  91. 'logs_count' => count($logs),
  92. 'chunks_count' => count($chunks),
  93. ]);
  94. return true;
  95. } catch (\Exception $e) {
  96. DB::rollBack();
  97. Logger::exception('批量记录用户日志失败', $e, [
  98. 'logs_count' => count($logs),
  99. 'error' => $e->getMessage(),
  100. ]);
  101. return false;
  102. }
  103. }
  104. /**
  105. * 获取用户日志列表
  106. *
  107. * @param int $userId 用户ID
  108. * @param int $page 页码
  109. * @param int $pageSize 每页数量
  110. * @param array $filters 过滤条件
  111. * @return LengthAwarePaginator
  112. */
  113. public static function getUserLogs(
  114. int $userId,
  115. int $page = 1,
  116. int $pageSize = 20,
  117. array $filters = []
  118. ): LengthAwarePaginator {
  119. try {
  120. $query = UserLog::byUser($userId)->latest();
  121. // 获取用户的最后清理时间,只返回清理时间之后的日志
  122. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  123. if ($lastClearTime) {
  124. // 使用原始时间进行过滤
  125. $query->where('original_time', '>', $lastClearTime);
  126. }
  127. // 应用过滤条件
  128. if (!empty($filters['source_type'])) {
  129. $query->bySourceType($filters['source_type']);
  130. }
  131. if (!empty($filters['start_time']) && !empty($filters['end_time'])) {
  132. // 使用原始时间范围查询
  133. $query->byOriginalTimeRange($filters['start_time'], $filters['end_time']);
  134. }
  135. if (!empty($filters['keyword'])) {
  136. $query->where('message', 'like', '%' . $filters['keyword'] . '%');
  137. }
  138. return $query->paginate($pageSize, ['*'], 'page', $page);
  139. } catch (\Exception $e) {
  140. Logger::exception('获取用户日志列表失败', $e, [
  141. 'user_id' => $userId,
  142. 'page' => $page,
  143. 'page_size' => $pageSize,
  144. 'filters' => $filters,
  145. ]);
  146. // 返回空的分页结果
  147. return new LengthAwarePaginator([], 0, $pageSize, $page);
  148. }
  149. }
  150. /**
  151. * 清空用户日志(逻辑清理)
  152. * 不真实删除日志,而是记录清理时间,只返回清理时间之后的日志给用户
  153. * 这样可以避免影响日志收集备份工作
  154. *
  155. * @param int $userId 用户ID
  156. * @return bool
  157. */
  158. public static function clearUserLogs(int $userId): bool
  159. {
  160. try {
  161. // 获取当前时间作为清理时间
  162. $clearTime = now();
  163. // 记录用户的清理时间
  164. UserLogClearRecord::setUserClearTime($userId, $clearTime);
  165. Logger::info('清空用户日志成功(逻辑清理)', [
  166. 'user_id' => $userId,
  167. 'clear_time' => $clearTime->toDateTimeString(),
  168. ]);
  169. return true;
  170. } catch (\Exception $e) {
  171. Logger::exception('清空用户日志失败', $e, [
  172. 'user_id' => $userId,
  173. ]);
  174. return false;
  175. }
  176. }
  177. /**
  178. * 清理过期日志
  179. *
  180. * @param int $days 保留天数
  181. * @return int 删除的记录数
  182. */
  183. public static function cleanExpiredLogs(int $days = 30): int
  184. {
  185. try {
  186. $expiredDate = now()->subDays($days);
  187. $deletedCount = UserLog::where('created_at', '<', $expiredDate)->delete();
  188. Logger::info('清理过期日志成功', [
  189. 'days' => $days,
  190. 'expired_date' => $expiredDate->toDateTimeString(),
  191. 'deleted_count' => $deletedCount,
  192. ]);
  193. return $deletedCount;
  194. } catch (\Exception $e) {
  195. Logger::exception('清理过期日志失败', $e, [
  196. 'days' => $days,
  197. ]);
  198. return 0;
  199. }
  200. }
  201. /**
  202. * 获取用户日志统计信息
  203. *
  204. * @param int $userId 用户ID
  205. * @return array
  206. */
  207. public static function getUserLogStats(int $userId): array
  208. {
  209. try {
  210. // 获取用户的最后清理时间,只统计清理时间之后的日志
  211. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  212. $baseQuery = UserLog::byUser($userId);
  213. if ($lastClearTime) {
  214. $baseQuery->where('original_time', '>', $lastClearTime);
  215. }
  216. $stats = [
  217. 'total_count' => (clone $baseQuery)->count(),
  218. 'today_count' => (clone $baseQuery)
  219. ->whereDate('original_time', today())
  220. ->count(),
  221. 'week_count' => (clone $baseQuery)
  222. ->where('original_time', '>=', now()->startOfWeek())
  223. ->count(),
  224. 'month_count' => (clone $baseQuery)
  225. ->where('original_time', '>=', now()->startOfMonth())
  226. ->count(),
  227. ];
  228. // 按来源类型统计
  229. $sourceTypeStats = (clone $baseQuery)
  230. ->select('source_type', DB::raw('count(*) as count'))
  231. ->whereNotNull('source_type')
  232. ->groupBy('source_type')
  233. ->pluck('count', 'source_type')
  234. ->toArray();
  235. $stats['source_type_stats'] = $sourceTypeStats;
  236. return $stats;
  237. } catch (\Exception $e) {
  238. Logger::exception('获取用户日志统计信息失败', $e, [
  239. 'user_id' => $userId,
  240. ]);
  241. return [];
  242. }
  243. }
  244. /**
  245. * 检查用户是否有日志记录
  246. *
  247. * @param int $userId 用户ID
  248. * @return bool
  249. */
  250. public static function hasUserLogs(int $userId): bool
  251. {
  252. try {
  253. $query = UserLog::byUser($userId);
  254. // 获取用户的最后清理时间,只检查清理时间之后的日志
  255. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  256. if ($lastClearTime) {
  257. $query->where('original_time', '>', $lastClearTime);
  258. }
  259. return $query->exists();
  260. } catch (\Exception $e) {
  261. Logger::exception('检查用户日志记录失败', $e, [
  262. 'user_id' => $userId,
  263. ]);
  264. return false;
  265. }
  266. }
  267. /**
  268. * 获取最新的用户日志
  269. *
  270. * @param int $userId 用户ID
  271. * @param int $limit 数量限制
  272. * @return \Illuminate\Database\Eloquent\Collection
  273. */
  274. public static function getLatestUserLogs(int $userId, int $limit = 10)
  275. {
  276. try {
  277. $query = UserLog::byUser($userId)->latest();
  278. // 获取用户的最后清理时间,只返回清理时间之后的日志
  279. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  280. if ($lastClearTime) {
  281. $query->where('original_time', '>', $lastClearTime);
  282. }
  283. return $query->limit($limit)->get();
  284. } catch (\Exception $e) {
  285. Logger::exception('获取最新用户日志失败', $e, [
  286. 'user_id' => $userId,
  287. 'limit' => $limit,
  288. ]);
  289. return collect();
  290. }
  291. }
  292. }