CollectUserLogsCommand.php 27 KB

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