CollectUserLogsCommand.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. <?php
  2. namespace App\Module\Game\Commands;
  3. use App\Module\Game\Logics\UserLogCollectorManager;
  4. use App\Module\Game\Services\GameConfigService;
  5. use UCore\Command\Command;
  6. /**
  7. * 用户日志收集命令
  8. *
  9. * 定时执行的计划任务,每2秒收集一次用户日志
  10. */
  11. class CollectUserLogsCommand extends Command
  12. {
  13. /**
  14. * 命令名称和参数
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'game:collect-user-logs {--info : 显示收集器信息} {--statistics : 显示收集统计信息} {--detail : 显示详细的处理过程} {--limit=1000 : 单次处理最大记录数} {--force : 强制执行,忽略自动收集配置}';
  19. /**
  20. * 命令描述
  21. *
  22. * @var string
  23. */
  24. protected $description = '收集用户日志,将各模块的原始日志转换为用户友好的日志消息
  25. 选项说明:
  26. --info 显示收集器信息
  27. --statistics 显示收集统计信息
  28. --detail 显示详细的处理过程
  29. --limit 单次处理最大记录数(默认1000)
  30. --force 强制执行,忽略自动收集配置
  31. 注意:进度追踪基于user_logs表中的已处理记录,系统会自动从上次处理位置继续收集';
  32. /**
  33. * 执行命令
  34. */
  35. public function handleRun()
  36. {
  37. // 检查是否允许自动收集日志(除非强制执行)
  38. if (!$this->option('force') && !$this->isAutoCollectEnabled()) {
  39. $this->warn("⚠️ 自动收集日志功能已禁用");
  40. $this->line("💡 如需强制执行,请使用 --force 选项");
  41. return 0;
  42. }
  43. // 显示统计信息
  44. if ($this->option('statistics')) {
  45. $manager = new UserLogCollectorManager();
  46. $collectorsInfo = $manager->getCollectorsInfo();
  47. $this->info("📊 收集器统计信息:");
  48. $this->line("");
  49. $this->line("收集器数量: " . count($collectorsInfo));
  50. // 动态显示所有收集器
  51. foreach ($collectorsInfo as $name => $info) {
  52. $icon = $this->getCollectorIcon($info['source_type']);
  53. $description = $this->getCollectorNameDescription($name);
  54. $this->line("- {$name}: {$icon} {$description}");
  55. }
  56. $this->line("");
  57. // 显示用户日志表统计
  58. try {
  59. $totalUserLogs = \App\Module\Game\Models\UserLog::count();
  60. $this->line("📋 用户日志表统计:");
  61. $this->line(" 📝 总日志数: {$totalUserLogs}");
  62. if ($totalUserLogs > 0) {
  63. $latestLog = \App\Module\Game\Models\UserLog::orderBy('created_at', 'desc')->first();
  64. $oldestLog = \App\Module\Game\Models\UserLog::orderBy('created_at', 'asc')->first();
  65. $this->line(" 🕐 最新日志时间: " . $latestLog->created_at);
  66. $this->line(" 🕐 最旧日志时间: " . $oldestLog->created_at);
  67. // 按类型统计 - 动态获取所有收集器类型
  68. $this->line(" 📊 按类型统计:");
  69. foreach ($collectorsInfo as $name => $info) {
  70. $sourceType = $info['source_type'];
  71. $count = \App\Module\Game\Models\UserLog::where('source_type', $sourceType)->count();
  72. $icon = $this->getCollectorIcon($sourceType);
  73. $description = $this->getCollectorDescription($sourceType);
  74. $this->line(" {$icon} {$description}: {$count}");
  75. }
  76. }
  77. } catch (\Exception $e) {
  78. $this->line(" ⚠️ 无法获取用户日志统计: " . $e->getMessage());
  79. }
  80. $this->line("");
  81. return 0;
  82. }
  83. $manager = new UserLogCollectorManager();
  84. // 显示收集器信息
  85. if ($this->option('info')) {
  86. $this->showCollectorsInfo($manager);
  87. return 0;
  88. }
  89. // 执行日志收集
  90. return $this->executeCollection($manager);
  91. }
  92. /**
  93. * 执行日志收集
  94. *
  95. * @param UserLogCollectorManager $manager
  96. * @return int
  97. */
  98. private function executeCollection(UserLogCollectorManager $manager): int
  99. {
  100. $detail = $this->option('detail');
  101. $limit = (int)$this->option('limit');
  102. $force = $this->option('force');
  103. try {
  104. if ($force) {
  105. $this->info("🚀 强制执行用户日志收集...");
  106. $this->line("⚡ 忽略自动收集配置,强制执行收集任务");
  107. } else {
  108. $this->info("🚀 开始按时间线收集用户日志...");
  109. }
  110. if ($detail) {
  111. $this->showTimelineProgress();
  112. }
  113. $result = $this->executeTimelineCollection($manager, $limit, $detail);
  114. $this->displayTimelineResult($result);
  115. return 0;
  116. } catch (\Exception $e) {
  117. $this->error("❌ 日志收集失败: {$e->getMessage()}");
  118. return 1;
  119. }
  120. }
  121. /**
  122. * 执行单个收集器并显示进度
  123. *
  124. * @param UserLogCollectorManager $manager
  125. * @param string $collectorName
  126. * @param bool $detail
  127. * @param bool $showProgress
  128. * @return array
  129. */
  130. private function executeCollectorWithProgress(UserLogCollectorManager $manager, string $collectorName, bool $detail, bool $showProgress): array
  131. {
  132. if ($detail) {
  133. $this->line("📊 检查收集器状态...");
  134. $this->showCollectorProgress($manager, $collectorName);
  135. }
  136. $startTime = microtime(true);
  137. $result = $manager->collectByName($collectorName);
  138. $endTime = microtime(true);
  139. if ($detail) {
  140. $this->line("⏱️ 执行时间: " . round(($endTime - $startTime) * 1000, 2) . "ms");
  141. }
  142. return $result;
  143. }
  144. /**
  145. * 执行所有收集器并显示进度
  146. *
  147. * @param UserLogCollectorManager $manager
  148. * @param bool $detail
  149. * @param bool $showProgress
  150. * @return array
  151. */
  152. private function executeAllCollectorsWithProgress(UserLogCollectorManager $manager, bool $detail, bool $showProgress): array
  153. {
  154. $collectorsInfo = $manager->getCollectorsInfo();
  155. if ($detail) {
  156. $this->line("📋 收集器总数: " . count($collectorsInfo));
  157. $this->line("");
  158. }
  159. $results = $manager->collectAll();
  160. return $results;
  161. }
  162. /**
  163. * 显示收集器详细信息
  164. *
  165. * @param UserLogCollectorManager $manager
  166. * @param string $collectorName
  167. * @return void
  168. */
  169. private function showCollectorDetails(UserLogCollectorManager $manager, string $collectorName): void
  170. {
  171. $collectorsInfo = $manager->getCollectorsInfo();
  172. if (!isset($collectorsInfo[$collectorName])) {
  173. $this->error("收集器 {$collectorName} 不存在");
  174. return;
  175. }
  176. $info = $collectorsInfo[$collectorName];
  177. $this->line("📝 收集器详情:");
  178. $this->line(" 名称: <comment>{$info['name']}</comment>");
  179. $this->line(" 类名: {$info['class']}");
  180. $this->line(" 源表: <info>{$info['source_table']}</info>");
  181. $this->line(" 类型: <info>{$info['source_type']}</info>");
  182. $this->line("");
  183. }
  184. /**
  185. * 显示收集器进度信息
  186. *
  187. * @param UserLogCollectorManager $manager
  188. * @param string $collectorName
  189. * @return void
  190. */
  191. private function showCollectorProgress(UserLogCollectorManager $manager, string $collectorName): void
  192. {
  193. $collectorsInfo = $manager->getCollectorsInfo();
  194. $info = $collectorsInfo[$collectorName];
  195. // 从user_logs表获取最后处理的记录
  196. $lastProcessedId = $this->getLastProcessedIdFromUserLogs($info['source_table'], $info['source_type']);
  197. $lastProcessedTimestamp = $this->getLastProcessedTimestampFromUserLogs($info['source_table'], $info['source_type']);
  198. // 获取源表的最大ID
  199. $maxId = $this->getTableMaxId($info['source_table']);
  200. // 计算待处理记录数
  201. $pendingCount = max(0, $maxId - $lastProcessedId);
  202. $this->line("📈 处理进度:");
  203. $this->line(" 最后处理ID: <comment>{$lastProcessedId}</comment>");
  204. $this->line(" 最后处理时间: <comment>" . ($lastProcessedTimestamp > 0 ? date('Y-m-d H:i:s', $lastProcessedTimestamp) : '未开始') . "</comment>");
  205. $this->line(" 源表最大ID: <comment>{$maxId}</comment>");
  206. $this->line(" 待处理记录: <comment>{$pendingCount}</comment>");
  207. $this->line("");
  208. }
  209. /**
  210. * 获取表的最大ID
  211. *
  212. * @param string $tableName
  213. * @return int
  214. */
  215. private function getTableMaxId(string $tableName): int
  216. {
  217. try {
  218. // 根据表名使用对应的模型
  219. switch ($tableName) {
  220. case 'fund_logs':
  221. return \App\Module\Fund\Models\FundLogModel::max('id') ?: 0;
  222. case 'item_transaction_logs':
  223. return \App\Module\GameItems\Models\ItemTransactionLog::max('id') ?: 0;
  224. case 'farm_harvest_logs':
  225. return \App\Module\Farm\Models\FarmHarvestLog::max('id') ?: 0;
  226. case 'farm_upgrade_logs':
  227. return \App\Module\Farm\Models\FarmUpgradeLog::max('id') ?: 0;
  228. case 'point_logs':
  229. return \App\Module\Point\Models\PointLogModel::max('id') ?: 0;
  230. default:
  231. // 回退到直接查询
  232. $result = \Illuminate\Support\Facades\DB::table($tableName)->max('id');
  233. return $result ? (int)$result : 0;
  234. }
  235. } catch (\Exception $e) {
  236. return 0;
  237. }
  238. }
  239. /**
  240. * 从user_logs表获取最后处理的ID
  241. *
  242. * @param string $sourceTable
  243. * @param string $sourceType
  244. * @return int
  245. */
  246. private function getLastProcessedIdFromUserLogs(string $sourceTable, string $sourceType): int
  247. {
  248. try {
  249. // 对于农场收集器,需要查询多个表
  250. if ($sourceType === 'farm') {
  251. $lastLog = \App\Module\Game\Models\UserLog::where('source_type', $sourceType)
  252. ->whereIn('source_table', ['farm_harvest_logs', 'farm_upgrade_logs'])
  253. ->orderBy('source_id', 'desc')
  254. ->first();
  255. } else {
  256. $lastLog = \App\Module\Game\Models\UserLog::where('source_table', $sourceTable)
  257. ->where('source_type', $sourceType)
  258. ->orderBy('source_id', 'desc')
  259. ->first();
  260. }
  261. return $lastLog ? $lastLog->source_id : 0;
  262. } catch (\Exception $e) {
  263. return 0;
  264. }
  265. }
  266. /**
  267. * 从user_logs表获取最后处理的时间戳
  268. *
  269. * @param string $sourceTable
  270. * @param string $sourceType
  271. * @return int
  272. */
  273. private function getLastProcessedTimestampFromUserLogs(string $sourceTable, string $sourceType): int
  274. {
  275. try {
  276. $lastLog = \App\Module\Game\Models\UserLog::where('source_table', $sourceTable)
  277. ->where('source_type', $sourceType)
  278. ->orderBy('created_at', 'desc')
  279. ->first();
  280. if (!$lastLog) {
  281. return 0;
  282. }
  283. // 返回user_logs记录的创建时间戳
  284. return strtotime($lastLog->created_at);
  285. } catch (\Exception $e) {
  286. return 0;
  287. }
  288. }
  289. /**
  290. * 显示收集器信息
  291. *
  292. * @param UserLogCollectorManager $manager
  293. * @return void
  294. */
  295. private function showCollectorsInfo(UserLogCollectorManager $manager): void
  296. {
  297. $this->info("📋 注册的收集器信息:");
  298. $this->line("");
  299. $collectorsInfo = $manager->getCollectorsInfo();
  300. foreach ($collectorsInfo as $info) {
  301. $this->line("收集器: <comment>{$info['name']}</comment>");
  302. $this->line(" 类名: {$info['class']}");
  303. $this->line(" 源表: <info>{$info['source_table']}</info>");
  304. $this->line(" 类型: <info>{$info['source_type']}</info>");
  305. $this->line("");
  306. }
  307. }
  308. /**
  309. * 显示统计信息
  310. *
  311. * @param UserLogCollectorManager $manager
  312. * @return void
  313. */
  314. private function showStats(UserLogCollectorManager $manager): void
  315. {
  316. $collectorsInfo = $manager->getCollectorsInfo();
  317. $this->line("");
  318. $this->line("收集器数量: " . count($collectorsInfo));
  319. // 动态显示所有收集器
  320. foreach ($collectorsInfo as $name => $info) {
  321. $icon = $this->getCollectorIcon($info['source_type']);
  322. $description = $this->getCollectorNameDescription($name);
  323. $this->line("- {$name}: {$icon} {$description}");
  324. }
  325. $this->line("");
  326. }
  327. /**
  328. * 获取收集器图标
  329. *
  330. * @param string $sourceType
  331. * @return string
  332. */
  333. private function getCollectorIcon(string $sourceType): string
  334. {
  335. $icons = [
  336. 'fund' => '💰',
  337. 'item' => '📦',
  338. 'farm' => '🌾',
  339. 'point' => '⭐',
  340. 'pet' => '🐾',
  341. 'system' => '⚙️',
  342. ];
  343. return $icons[$sourceType] ?? '📄';
  344. }
  345. /**
  346. * 获取收集器描述
  347. *
  348. * @param string $sourceType
  349. * @return string
  350. */
  351. private function getCollectorDescription(string $sourceType): string
  352. {
  353. $descriptions = [
  354. 'fund' => '资金日志收集器',
  355. 'item' => '物品日志收集器',
  356. 'farm' => '农场日志收集器',
  357. 'point' => '积分日志收集器',
  358. 'pet' => '宠物日志收集器',
  359. 'system' => '系统日志收集器',
  360. ];
  361. return $descriptions[$sourceType] ?? '未知类型收集器';
  362. }
  363. /**
  364. * 获取收集器名称描述(基于收集器名称而非源类型)
  365. *
  366. * @param string $collectorName
  367. * @return string
  368. */
  369. private function getCollectorNameDescription(string $collectorName): string
  370. {
  371. $descriptions = [
  372. 'fund' => '资金日志收集器',
  373. 'item' => '物品日志收集器',
  374. 'farm_harvest' => '农场收获日志收集器',
  375. 'farm_upgrade' => '农场升级日志收集器',
  376. 'point' => '积分日志收集器',
  377. 'pet' => '宠物日志收集器',
  378. 'system' => '系统日志收集器',
  379. ];
  380. return $descriptions[$collectorName] ?? '未知收集器';
  381. }
  382. /**
  383. * 获取表的记录总数
  384. *
  385. * @param string $tableName
  386. * @return int
  387. */
  388. private function getTableRecordCount(string $tableName): int
  389. {
  390. try {
  391. // 根据表名使用对应的模型
  392. switch ($tableName) {
  393. case 'fund_logs':
  394. return \App\Module\Fund\Models\FundLogModel::count();
  395. case 'item_transaction_logs':
  396. return \App\Module\GameItems\Models\ItemTransactionLog::count();
  397. case 'farm_harvest_logs':
  398. return \App\Module\Farm\Models\FarmHarvestLog::count();
  399. case 'farm_upgrade_logs':
  400. return \App\Module\Farm\Models\FarmUpgradeLog::count();
  401. case 'point_logs':
  402. return \App\Module\Point\Models\PointLogModel::count();
  403. default:
  404. // 回退到直接查询
  405. return \Illuminate\Support\Facades\DB::table($tableName)->count();
  406. }
  407. } catch (\Exception $e) {
  408. return 0;
  409. }
  410. }
  411. /**
  412. * 显示进度条
  413. *
  414. * @param float $percent
  415. * @return void
  416. */
  417. private function displayProgressBar(float $percent): void
  418. {
  419. $barLength = 20;
  420. $filledLength = (int)round(($percent / 100) * $barLength);
  421. $emptyLength = $barLength - $filledLength;
  422. $bar = str_repeat('█', $filledLength) . str_repeat('░', $emptyLength);
  423. $this->line(" 📊 [{$bar}] {$percent}%");
  424. }
  425. /**
  426. * 执行时间线收集
  427. * 改为让每个收集器独立处理,避免全局时间戳的复杂性
  428. *
  429. * @param UserLogCollectorManager $manager
  430. * @param int $limit
  431. * @param bool $detail
  432. * @return array
  433. */
  434. private function executeTimelineCollection(UserLogCollectorManager $manager, int $limit, bool $detail): array
  435. {
  436. $startTime = microtime(true);
  437. if ($detail) {
  438. $this->line("📊 执行各收集器的日志收集...");
  439. }
  440. // 直接执行所有收集器,传递限制参数
  441. $results = $manager->collectAll($limit);
  442. if ($results['total_processed'] == 0) {
  443. return [
  444. 'processed_count' => 0,
  445. 'execution_time' => round((microtime(true) - $startTime) * 1000, 2),
  446. 'status' => 'success',
  447. 'message' => '没有新记录需要处理',
  448. 'timestamp' => now()->toDateTimeString()
  449. ];
  450. }
  451. if ($detail) {
  452. $this->line("📝 开始处理各收集器...");
  453. foreach ($results['collectors'] as $collectorName => $result) {
  454. $this->line(" {$collectorName}: 处理了 {$result['processed_count']} 条记录");
  455. }
  456. }
  457. $endTime = microtime(true);
  458. return [
  459. 'processed_count' => $results['total_processed'],
  460. 'execution_time' => round(($endTime - $startTime) * 1000, 2),
  461. 'status' => 'success',
  462. 'timestamp' => now()->toDateTimeString(),
  463. 'details' => $results['collectors']
  464. ];
  465. }
  466. /**
  467. * 从所有收集器获取按时间线排序的记录
  468. *
  469. * @param UserLogCollectorManager $manager
  470. * @param int $lastTimestamp
  471. * @param int $limit
  472. * @return array
  473. */
  474. private function getAllRecordsByTimeline(UserLogCollectorManager $manager, int $lastTimestamp, int $limit): array
  475. {
  476. $allRecords = [];
  477. $collectorsInfo = $manager->getCollectorsInfo();
  478. foreach ($collectorsInfo as $name => $info) {
  479. $collector = $manager->getCollector($name);
  480. if (!$collector) continue;
  481. try {
  482. $records = $collector->getNewRecordsByTimePublic($lastTimestamp);
  483. foreach ($records as $record) {
  484. $timestamp = $collector->getRecordTimestampPublic($record);
  485. $allRecords[] = [
  486. 'id' => $record->id,
  487. 'timestamp' => $timestamp,
  488. 'collector' => $collector,
  489. 'record' => $record,
  490. 'source_type' => $info['source_type']
  491. ];
  492. }
  493. } catch (\Exception $e) {
  494. \Illuminate\Support\Facades\Log::error("获取收集器记录失败", [
  495. 'collector' => $name,
  496. 'error' => $e->getMessage()
  497. ]);
  498. }
  499. }
  500. // 限制记录数量
  501. if (count($allRecords) > $limit) {
  502. // 先按时间排序,然后取前N条
  503. usort($allRecords, function($a, $b) {
  504. $timeA = $a['timestamp'];
  505. $timeB = $b['timestamp'];
  506. if ($timeA == $timeB) {
  507. return $a['id'] <=> $b['id'];
  508. }
  509. return $timeA <=> $timeB;
  510. });
  511. $allRecords = array_slice($allRecords, 0, $limit);
  512. }
  513. return $allRecords;
  514. }
  515. /**
  516. * 显示时间线进度
  517. *
  518. * @return void
  519. */
  520. private function showTimelineProgress(): void
  521. {
  522. $lastTimestamp = $this->getGlobalLastProcessedTimestamp();
  523. $this->line("📈 时间线处理进度:");
  524. $this->line(" 🕐 最后处理时间: <comment>" . ($lastTimestamp > 0 ? date('Y-m-d H:i:s', $lastTimestamp) : '未开始') . "</comment>");
  525. $this->line("");
  526. }
  527. /**
  528. * 显示时间线收集结果
  529. *
  530. * @param array $result
  531. * @return void
  532. */
  533. private function displayTimelineResult(array $result): void
  534. {
  535. $this->line("");
  536. if ($result['status'] === 'success') {
  537. $this->info("✅ 时间线收集完成!");
  538. $this->line("📊 <comment>处理统计</comment>:");
  539. $this->line(" 📝 处理记录数: <info>{$result['processed_count']}</info>");
  540. $this->line(" ⏱️ 执行时间: <info>{$result['execution_time']}ms</info>");
  541. $this->line(" 🕐 完成时间: <info>{$result['timestamp']}</info>");
  542. if (isset($result['last_timestamp'])) {
  543. $this->line(" 🎯 最新的处理时间: <info>" . date('Y-m-d H:i:s', $result['last_timestamp']) . "</info>");
  544. }
  545. if ($result['processed_count'] > 0) {
  546. $avgTime = round($result['execution_time'] / $result['processed_count'], 2);
  547. $this->line(" 📈 平均处理时间: <info>{$avgTime}ms/条</info>");
  548. }
  549. if (isset($result['message'])) {
  550. $this->line(" 💡 <comment>{$result['message']}</comment>");
  551. }
  552. } else {
  553. $this->error("❌ 时间线收集失败!");
  554. if (isset($result['error'])) {
  555. $this->line("🚨 <comment>错误信息</comment>:");
  556. $this->line(" {$result['error']}");
  557. }
  558. }
  559. $this->line("");
  560. }
  561. /**
  562. * 获取全局最后处理时间戳
  563. * 从各个收集器获取最后处理的原始记录时间戳,取最小值
  564. *
  565. * @return int
  566. */
  567. private function getGlobalLastProcessedTimestamp(): int
  568. {
  569. try {
  570. $manager = new \App\Module\Game\Logics\UserLogCollectorManager();
  571. $collectorsInfo = $manager->getCollectorsInfo();
  572. $minTimestamp = PHP_INT_MAX;
  573. $hasValidTimestamp = false;
  574. foreach ($collectorsInfo as $name => $info) {
  575. $collector = $manager->getCollector($name);
  576. if (!$collector) continue;
  577. // 获取该收集器最后处理的时间戳
  578. $lastProcessedTimestamp = $this->getLastProcessedTimestampFromUserLogs($info['source_table'], $info['source_type']);
  579. if ($lastProcessedTimestamp > 0) {
  580. $minTimestamp = min($minTimestamp, $lastProcessedTimestamp);
  581. $hasValidTimestamp = true;
  582. }
  583. }
  584. return $hasValidTimestamp ? $minTimestamp : 0;
  585. } catch (\Exception $e) {
  586. return 0;
  587. }
  588. }
  589. /**
  590. * 更新全局最后处理时间戳
  591. * 不再需要手动更新,因为进度通过user_logs表自动追踪
  592. *
  593. * @param int $timestamp
  594. * @return void
  595. */
  596. private function updateGlobalLastProcessedTimestamp(int $timestamp): void
  597. {
  598. // 不再需要手动更新,进度通过user_logs表自动追踪
  599. // 这个方法保留是为了兼容性
  600. }
  601. /**
  602. * 显示用户日志表统计
  603. *
  604. * @return void
  605. */
  606. private function showUserLogStats(): void
  607. {
  608. try {
  609. // 使用模型查询,避免表名前缀问题
  610. $totalUserLogs = \App\Module\Game\Models\UserLog::count();
  611. $todayUserLogs = \App\Module\Game\Models\UserLog::whereDate('created_at', now()->toDateString())->count();
  612. $this->line("📋 <comment>用户日志表统计</comment>:");
  613. $this->line(" 📝 总日志数: <info>{$totalUserLogs}</info>");
  614. $this->line(" 📅 今日新增: <info>{$todayUserLogs}</info>");
  615. // 按来源类型统计
  616. $sourceStats = \App\Module\Game\Models\UserLog::select('source_type', \Illuminate\Support\Facades\DB::raw('count(*) as count'))
  617. ->groupBy('source_type')
  618. ->get();
  619. if ($sourceStats->isNotEmpty()) {
  620. $this->line(" 📊 按来源类型统计:");
  621. foreach ($sourceStats as $stat) {
  622. $this->line(" {$stat->source_type}: <info>{$stat->count}</info>");
  623. }
  624. }
  625. } catch (\Exception $e) {
  626. $this->line(" ⚠️ 无法获取用户日志统计信息: " . $e->getMessage());
  627. }
  628. }
  629. /**
  630. * 显示单个收集器结果
  631. *
  632. * @param array $result
  633. * @return void
  634. */
  635. private function displaySingleResult(array $result): void
  636. {
  637. $this->line("");
  638. if ($result['status'] === 'success') {
  639. $this->info("✅ 收集完成!");
  640. $this->line("📊 <comment>处理统计</comment>:");
  641. $this->line(" 📝 处理记录数: <info>{$result['processed_count']}</info>");
  642. $this->line(" ⏱️ 执行时间: <info>{$result['execution_time']}ms</info>");
  643. $this->line(" 🕐 完成时间: <info>{$result['timestamp']}</info>");
  644. if ($result['processed_count'] > 0) {
  645. $avgTime = round($result['execution_time'] / $result['processed_count'], 2);
  646. $this->line(" 📈 平均处理时间: <info>{$avgTime}ms/条</info>");
  647. }
  648. } else {
  649. $this->error("❌ 收集失败!");
  650. $this->line("🚨 <comment>错误信息</comment>:");
  651. $this->line(" {$result['error']}");
  652. }
  653. $this->line("");
  654. }
  655. /**
  656. * 显示所有收集器结果
  657. *
  658. * @param array $results
  659. * @return void
  660. */
  661. private function displayAllResults(array $results): void
  662. {
  663. $this->line("");
  664. $this->info("🎉 所有收集器执行完成!");
  665. $this->line("");
  666. // 显示总体统计
  667. $this->line("📊 <comment>总体统计</comment>:");
  668. $this->line(" 📝 总处理记录数: <info>{$results['total_processed']}</info>");
  669. $this->line(" ⏱️ 总执行时间: <info>{$results['total_execution_time']}ms</info>");
  670. $this->line(" 🕐 完成时间: <info>{$results['timestamp']}</info>");
  671. if ($results['total_processed'] > 0) {
  672. $avgTime = round($results['total_execution_time'] / $results['total_processed'], 2);
  673. $this->line(" 📈 平均处理时间: <info>{$avgTime}ms/条</info>");
  674. }
  675. $this->line("");
  676. // 显示各收集器详情
  677. $this->line("📋 <comment>各收集器详情</comment>:");
  678. $successCount = 0;
  679. $failureCount = 0;
  680. foreach ($results['collectors'] as $name => $result) {
  681. if ($result['status'] === 'success') {
  682. $status = '<info>✅ 成功</info>';
  683. $successCount++;
  684. } else {
  685. $status = '<error>❌ 失败</error>';
  686. $failureCount++;
  687. }
  688. $this->line(" 🔧 <comment>{$name}</comment>: {$status}");
  689. $this->line(" 📝 处理记录: <info>{$result['processed_count']}</info> 条");
  690. $this->line(" ⏱️ 执行时间: <info>{$result['execution_time']}</info> ms");
  691. if ($result['status'] === 'error') {
  692. $this->line(" 🚨 错误信息: <error>{$result['error']}</error>");
  693. } elseif ($result['processed_count'] > 0) {
  694. $avgTime = round($result['execution_time'] / $result['processed_count'], 2);
  695. $this->line(" 📈 平均时间: <info>{$avgTime}</info> ms/条");
  696. }
  697. $this->line("");
  698. }
  699. // 显示执行摘要
  700. $totalCollectors = $successCount + $failureCount;
  701. $this->line("📈 <comment>执行摘要</comment>:");
  702. $this->line(" 🎯 成功收集器: <info>{$successCount}/{$totalCollectors}</info>");
  703. if ($failureCount > 0) {
  704. $this->line(" ⚠️ 失败收集器: <error>{$failureCount}/{$totalCollectors}</error>");
  705. }
  706. $this->line("");
  707. }
  708. /**
  709. * 检查是否允许自动收集日志
  710. *
  711. * @return bool
  712. */
  713. private function isAutoCollectEnabled(): bool
  714. {
  715. return GameConfigService::isAutoCollectEnabled();
  716. }
  717. }