UserLogLogic.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. // 按原始时间排序,而不是创建时间,确保日志按业务发生时间显示
  121. $query = UserLog::byUser($userId)->orderBy('original_time', 'desc');
  122. // 获取用户的最后清理时间,只返回清理时间之后的日志
  123. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  124. if ($lastClearTime) {
  125. // 使用原始时间进行过滤
  126. $query->where('original_time', '>', $lastClearTime);
  127. }
  128. // 应用过滤条件
  129. if (!empty($filters['source_type'])) {
  130. $query->bySourceType($filters['source_type']);
  131. }
  132. if (!empty($filters['start_time']) && !empty($filters['end_time'])) {
  133. // 使用原始时间范围查询
  134. $query->byOriginalTimeRange($filters['start_time'], $filters['end_time']);
  135. }
  136. if (!empty($filters['keyword'])) {
  137. $query->where('message', 'like', '%' . $filters['keyword'] . '%');
  138. }
  139. return $query->paginate($pageSize, ['*'], 'page', $page);
  140. } catch (\Exception $e) {
  141. Logger::exception('获取用户日志列表失败', $e, [
  142. 'user_id' => $userId,
  143. 'page' => $page,
  144. 'page_size' => $pageSize,
  145. 'filters' => $filters,
  146. ]);
  147. // 返回空的分页结果
  148. return new LengthAwarePaginator([], 0, $pageSize, $page);
  149. }
  150. }
  151. /**
  152. * 清空用户日志(逻辑清理)
  153. * 不真实删除日志,而是记录清理时间,只返回清理时间之后的日志给用户
  154. * 这样可以避免影响日志收集备份工作
  155. *
  156. * @param int $userId 用户ID
  157. * @return bool
  158. */
  159. public static function clearUserLogs(int $userId): bool
  160. {
  161. try {
  162. // 获取当前时间作为清理时间
  163. $clearTime = now();
  164. // 记录用户的清理时间
  165. UserLogClearRecord::setUserClearTime($userId, $clearTime);
  166. Logger::info('清空用户日志成功(逻辑清理)', [
  167. 'user_id' => $userId,
  168. 'clear_time' => $clearTime->toDateTimeString(),
  169. ]);
  170. return true;
  171. } catch (\Exception $e) {
  172. Logger::exception('清空用户日志失败', $e, [
  173. 'user_id' => $userId,
  174. ]);
  175. return false;
  176. }
  177. }
  178. /**
  179. * 清理过期日志
  180. *
  181. * @param int $days 保留天数
  182. * @return int 删除的记录数
  183. */
  184. public static function cleanExpiredLogs(int $days = 30): int
  185. {
  186. try {
  187. $expiredDate = now()->subDays($days);
  188. $deletedCount = UserLog::where('created_at', '<', $expiredDate)->delete();
  189. Logger::info('清理过期日志成功', [
  190. 'days' => $days,
  191. 'expired_date' => $expiredDate->toDateTimeString(),
  192. 'deleted_count' => $deletedCount,
  193. ]);
  194. return $deletedCount;
  195. } catch (\Exception $e) {
  196. Logger::exception('清理过期日志失败', $e, [
  197. 'days' => $days,
  198. ]);
  199. return 0;
  200. }
  201. }
  202. /**
  203. * 获取用户日志统计信息
  204. *
  205. * @param int $userId 用户ID
  206. * @return array
  207. */
  208. public static function getUserLogStats(int $userId): array
  209. {
  210. try {
  211. // 获取用户的最后清理时间,只统计清理时间之后的日志
  212. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  213. $baseQuery = UserLog::byUser($userId);
  214. if ($lastClearTime) {
  215. $baseQuery->where('original_time', '>', $lastClearTime);
  216. }
  217. $stats = [
  218. 'total_count' => (clone $baseQuery)->count(),
  219. 'today_count' => (clone $baseQuery)
  220. ->whereDate('original_time', today())
  221. ->count(),
  222. 'week_count' => (clone $baseQuery)
  223. ->where('original_time', '>=', now()->startOfWeek())
  224. ->count(),
  225. 'month_count' => (clone $baseQuery)
  226. ->where('original_time', '>=', now()->startOfMonth())
  227. ->count(),
  228. ];
  229. // 按来源类型统计
  230. $sourceTypeStats = (clone $baseQuery)
  231. ->select('source_type', DB::raw('count(*) as count'))
  232. ->whereNotNull('source_type')
  233. ->groupBy('source_type')
  234. ->pluck('count', 'source_type')
  235. ->toArray();
  236. $stats['source_type_stats'] = $sourceTypeStats;
  237. return $stats;
  238. } catch (\Exception $e) {
  239. Logger::exception('获取用户日志统计信息失败', $e, [
  240. 'user_id' => $userId,
  241. ]);
  242. return [];
  243. }
  244. }
  245. /**
  246. * 检查用户是否有日志记录
  247. *
  248. * @param int $userId 用户ID
  249. * @return bool
  250. */
  251. public static function hasUserLogs(int $userId): bool
  252. {
  253. try {
  254. $query = UserLog::byUser($userId);
  255. // 获取用户的最后清理时间,只检查清理时间之后的日志
  256. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  257. if ($lastClearTime) {
  258. $query->where('original_time', '>', $lastClearTime);
  259. }
  260. return $query->exists();
  261. } catch (\Exception $e) {
  262. Logger::exception('检查用户日志记录失败', $e, [
  263. 'user_id' => $userId,
  264. ]);
  265. return false;
  266. }
  267. }
  268. /**
  269. * 获取最新的用户日志
  270. *
  271. * @param int $userId 用户ID
  272. * @param int $limit 数量限制
  273. * @return \Illuminate\Database\Eloquent\Collection
  274. */
  275. public static function getLatestUserLogs(int $userId, int $limit = 10)
  276. {
  277. try {
  278. // 按原始时间排序,而不是创建时间,确保日志按业务发生时间显示
  279. $query = UserLog::byUser($userId)->orderBy('original_time', 'desc');
  280. // 获取用户的最后清理时间,只返回清理时间之后的日志
  281. $lastClearTime = UserLogClearRecord::getUserLastClearTime($userId);
  282. if ($lastClearTime) {
  283. $query->where('original_time', '>', $lastClearTime);
  284. }
  285. return $query->limit($limit)->get();
  286. } catch (\Exception $e) {
  287. Logger::exception('获取最新用户日志失败', $e, [
  288. 'user_id' => $userId,
  289. 'limit' => $limit,
  290. ]);
  291. return collect();
  292. }
  293. }
  294. }