CleanExpiredLogsCommand.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Module\Farm\Commands;
  3. use App\Module\Farm\Logics\HarvestLogLogic;
  4. use App\Module\Farm\Logics\UpgradeLogLogic;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\Log;
  7. /**
  8. * 清理过期日志命令
  9. */
  10. class CleanExpiredLogsCommand extends Command
  11. {
  12. /**
  13. * 命令名称
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'farm:clean-expired-logs {--days=90 : 保留天数}';
  18. /**
  19. * 命令描述
  20. *
  21. * @var string
  22. */
  23. protected $description = '清理过期的日志记录';
  24. /**
  25. * 执行命令
  26. *
  27. * @return int
  28. */
  29. public function handle()
  30. {
  31. $days = $this->option('days');
  32. $this->info("开始清理 {$days} 天前的日志记录...");
  33. try {
  34. // 清理收获记录
  35. $harvestLogLogic = new HarvestLogLogic();
  36. $harvestCount = $harvestLogLogic->cleanupOldLogs($days);
  37. $this->info("清理了 {$harvestCount} 条收获记录");
  38. // 清理升级记录
  39. $upgradeLogLogic = new UpgradeLogLogic();
  40. $upgradeCount = $upgradeLogLogic->cleanupOldLogs($days);
  41. $this->info("清理了 {$upgradeCount} 条升级记录");
  42. $totalCount = $harvestCount + $upgradeCount ;
  43. $this->info("共清理了 {$totalCount} 条日志记录");
  44. Log::info('日志清理成功', [
  45. 'days' => $days,
  46. 'harvest_count' => $harvestCount,
  47. 'upgrade_count' => $upgradeCount,
  48. 'total_count' => $totalCount
  49. ]);
  50. return 0;
  51. } catch (\Exception $e) {
  52. $this->error('日志清理失败: ' . $e->getMessage());
  53. Log::error('日志清理失败', [
  54. 'days' => $days,
  55. 'error' => $e->getMessage(),
  56. 'trace' => $e->getTraceAsString()
  57. ]);
  58. return 1;
  59. }
  60. }
  61. }