Prechádzať zdrojové kódy

梳理日志收集系统,移除废弃代码

- 删除未使用的UserLogScheduleService和CollectUserLogJob
- 更新文档,移除对废弃组件的引用
- 保留所有有实际用途的组件
- 系统功能验证正常
AI Assistant 6 mesiacov pred
rodič
commit
56e02903ab

+ 106 - 119
app/Module/Game/Docs/UserLog.md

@@ -46,7 +46,6 @@
 
 #### 2. 管理层 (Management)
 - **UserLogCollectorManager**: 收集器管理器,统一调度所有收集器
-- **UserLogScheduleService**: 调度服务,提供同步和异步执行
 - **UserLogService**: 对外服务接口
 
 #### 3. 数据层 (Data)
@@ -181,61 +180,48 @@ if (!empty($userLogs)) {
 
 ## 配置系统
 
-### 主配置文件 (config/game_user_log.php)
+### 数据库配置
 
-```php
-return [
-    // 全局开关
-    'enabled' => env('GAME_USER_LOG_ENABLED', true),
+用户日志系统的配置已迁移到数据库,存储在 `kku_game_configs` 表中,支持运行时动态修改。
 
-    // 收集器配置
-    'collectors' => [
-        'max_records_per_run' => 1000,  // 单次最大处理数
-        'collection_interval' => 2,     // 收集间隔(秒)
-
-        // 各模块开关
-        'fund' => ['enabled' => true],
-        'item' => ['enabled' => true],
-        'farm' => ['enabled' => true],
-        'point' => ['enabled' => true],
-    ],
+#### 配置项说明
 
-    // 性能配置
-    'performance' => [
-        'batch_size' => 100,           // 批量处理大小
-        'use_queue' => true,           // 是否使用队列
-        'cache_ttl' => 86400,          // 缓存TTL
-    ],
-
-    // 清理配置
-    'cleanup' => [
-        'retention_days' => 30,        // 保留天数
-        'auto_cleanup' => true,        // 自动清理
-    ],
-];
-```
+| 配置键 | 名称 | 类型 | 默认值 | 说明 |
+|--------|------|------|--------|------|
+| `user_log.enabled` | 用户日志系统启用 | 布尔值 | true | 控制整个用户日志系统是否启用 |
+| `user_log.auto_collect_enabled` | 自动收集日志启用 | 布尔值 | true | 控制是否允许自动收集用户日志 |
+| `user_log.max_records_per_run` | 单次最大处理记录数 | 整数 | 1000 | 每次收集日志时的最大处理记录数 |
+| `user_log.collection_interval` | 收集间隔 | 整数 | 2 | 日志收集的间隔时间(秒) |
+| `user_log.retention_days` | 日志保留天数 | 整数 | 30 | 用户日志的保留天数 |
+| `user_log.auto_cleanup` | 自动清理启用 | 布尔值 | true | 是否启用自动清理过期日志 |
 
-### 环境变量配置
+#### 配置访问方式
 
-```bash
-# 用户日志系统配置
-GAME_USER_LOG_ENABLED=true
-GAME_USER_LOG_MAX_RECORDS=1000
-GAME_USER_LOG_INTERVAL=2
-GAME_USER_LOG_RETENTION_DAYS=30
+```php
+use App\Module\Game\Services\GameConfigService;
 
-# 各模块开关
-GAME_USER_LOG_FUND_ENABLED=true
-GAME_USER_LOG_ITEM_ENABLED=true
-GAME_USER_LOG_FARM_ENABLED=true
-GAME_USER_LOG_POINT_ENABLED=true
+// 获取完整的用户日志配置
+$config = GameConfigService::getUserLogConfig();
 
-# 性能配置
-GAME_USER_LOG_BATCH_SIZE=100
-GAME_USER_LOG_USE_QUEUE=true
-GAME_USER_LOG_CACHE_TTL=86400
+// 配置结构示例
+[
+    'enabled' => true,
+    'auto_collect_enabled' => true,
+    'max_records_per_run' => 1000,
+    'collection_interval' => 2,
+    'retention_days' => 30,
+    'auto_cleanup' => true,
+]
 ```
 
+#### 后台管理
+
+可以通过后台管理界面修改配置:
+- 访问路径:`/admin/game-system-configs`
+- 支持在线修改配置值
+- 支持重置为默认值
+- 自动缓存管理
+
 ## 数据库设计
 
 ### 用户日志表 (kku_user_logs)
@@ -375,7 +361,7 @@ php artisan game:collect-user-logs --statistics
 
 ### Laravel 调度器配置
 
-在 `routes/console.php` 中添加:
+如需启用自动日志收集,可在 `routes/console.php` 中添加:
 
 ```php
 use Illuminate\Support\Facades\Schedule;
@@ -387,6 +373,8 @@ Schedule::command('game:collect-user-logs --limit=100')->everyMinute();
 Schedule::command('game:clean-expired-user-logs')->dailyAt('02:00');
 ```
 
+**注意**:默认情况下计划任务已被注释,需要根据实际需求启用。系统通过数据库配置 `user_log.auto_collect_enabled` 控制是否允许自动收集。
+
 ### Crontab 配置
 
 如果需要更高频率的收集,可以直接配置 crontab:
@@ -397,83 +385,57 @@ Schedule::command('game:clean-expired-user-logs')->dailyAt('02:00');
 * * * * * sleep 30; cd /path/to/project && php artisan game:collect-user-logs --limit=50 >/dev/null 2>&1
 ```
 
-### 队列处理器配置
+### 执行方式
 
-如果启用了队列处理,需要运行队列处理器
+日志收集系统采用同步执行方式,通过命令行工具直接执行
 
 ```bash
-# 启动队列处理器
-php artisan queue:work --queue=default --timeout=60
+# 手动执行日志收集
+php artisan game:collect-user-logs
 
-# 使用 Supervisor 管理队列处理器
-[program:laravel-queue-worker]
-process_name=%(program_name)s_%(process_num)02d
-command=php /path/to/project/artisan queue:work --queue=default --timeout=60
-directory=/path/to/project
-autostart=true
-autorestart=true
-user=www-data
-numprocs=2
+# 通过计划任务定时执行
+# 在 routes/console.php 中配置调度任务
 ```
 
 ## 监控和告警
 
 ### 健康检查
 
-系统提供完整的健康检查功能:
+系统提供基本的健康检查功能:
 
-```php
-// 通过服务调用
-$health = UserLogScheduleService::healthCheck();
+```bash
+# 检查收集器状态
+php artisan game:collect-user-logs --info
 
-// 返回结果示例
-[
-    'status' => 'healthy',
-    'checks' => [
-        'collectors_registered' => [
-            'status' => 'pass',
-            'count' => 4,
-            'details' => ['fund', 'item', 'farm', 'point']
-        ],
-        'recent_logs' => [
-            'status' => 'info',
-            'count' => 156,
-            'message' => '最近10分钟生成了 156 条日志'
-        ],
-        'database' => [
-            'status' => 'pass',
-            'message' => '数据库连接正常'
-        ]
-    ],
-    'timestamp' => '2025-06-13 11:16:04'
-]
+# 查看统计信息
+php artisan game:collect-user-logs --statistics
 ```
 
+通过命令行工具可以检查:
+- 收集器注册状态
+- 日志收集统计
+- 系统运行状态
+
 ### 性能监控
 
 #### 收集统计
-```php
-// 获取收集统计信息
-$stats = UserLogScheduleService::getCollectionStats(7); // 最近7天
+```bash
+# 查看收集统计信息
+php artisan game:collect-user-logs --statistics
 
-// 返回结果
-[
-    'period' => '7天',
-    'start_date' => '2025-06-06',
-    'end_date' => '2025-06-13',
-    'total_logs' => 45678,
-    'daily_stats' => [
-        '2025-06-06' => 6543,
-        '2025-06-07' => 7234,
-        // ...
-    ],
-    'source_type_stats' => [
-        'fund' => 18765,
-        'item' => 12456,
-        'farm' => 8765,
-        'point' => 5692
-    ]
-]
+# 输出示例
+📊 收集器统计信息:
+收集器数量: 5
+- fund: ⚙️ 资金日志收集器
+- item: ⚙️ 物品日志收集器
+- farm_harvest: 🌾 农场收获日志收集器
+- farm_upgrade: 🌾 农场升级日志收集器
+- point: ⭐ 积分日志收集器
+
+📋 用户日志表统计:
+  📝 总日志数: 119163
+  🕐 最新日志时间: 2025-06-22 23:35:56
+  🕐 最旧日志时间: 2025-06-21 16:30:12
 ```
 
 #### 执行时间监控
@@ -631,17 +593,15 @@ private function registerCollectors(): void
 
 #### 3. 添加配置
 
-在 `config/game_user_log.php` 中添加配置
+在数据库中添加配置项
 
-```php
-'collectors' => [
-    // ...
-    'custom' => [
-        'enabled' => env('GAME_USER_LOG_CUSTOM_ENABLED', true),
-    ],
-],
+```sql
+INSERT INTO `kku_game_configs` (`key`, `name`, `description`, `group`, `type`, `value`, `default_value`, `sort_order`, `remark`) VALUES
+('user_log.custom_enabled', '自定义收集器启用', '控制自定义收集器是否启用', 'user_log', 1, '1', '1', 70, '');
 ```
 
+或通过后台管理界面添加配置项。
+
 ### 自定义消息模板
 
 #### 1. 配置模板
@@ -728,12 +688,39 @@ Cache::remember("collector_progress:{$this->sourceType}", 300, function () {
 
 #### 2. 配置缓存
 ```php
-// 缓存配置信息
-$config = Cache::remember('game_user_log_config', 3600, function () {
-    return config('game_user_log');
-});
+// 配置自动缓存,通过GameConfigService访问
+$config = GameConfigService::getUserLogConfig();
+
+// 手动清除配置缓存(如果需要)
+GameConfigLogic::clearCache('user_log.enabled');
 ```
 
+## 系统清理说明
+
+### 已移除的废弃组件
+
+为了保持系统整洁,以下组件已被移除:
+
+#### 1. 废弃的配置文件
+- `config/game_user_log.php` - 配置已迁移到数据库
+
+#### 2. 废弃的服务类
+- `UserLogScheduleService` - 未被实际使用,功能已由命令行工具替代
+- `CollectUserLogJob` - 异步队列任务,未被实际使用
+
+#### 3. 废弃的protobuf类
+- `Request_RequestUserLogData` - 已被新命名空间替代
+- `Request_RequestUserClearLog` - 已被新命名空间替代
+
+### 迁移说明
+
+如果您的代码中引用了上述废弃组件,请按以下方式迁移:
+
+1. **配置访问**:使用 `GameConfigService::getUserLogConfig()` 替代文件配置
+2. **日志收集**:直接使用 `CollectUserLogsCommand` 或 `UserLogCollectorManager`
+3. **异步处理**:如需异步处理,可以自行实现队列任务调用 `UserLogCollectorManager`
+4. **protobuf类**:使用新的命名空间下的类
+
 ## 故障排除
 
 ### 常见问题

+ 0 - 152
app/Module/Game/Jobs/CollectUserLogJob.php

@@ -1,152 +0,0 @@
-<?php
-
-namespace App\Module\Game\Jobs;
-
-use App\Module\Game\Logics\UserLogCollectorManager;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Log;
-
-/**
- * 用户日志收集任务
- *
- * 通过计划任务定时收集各模块的原始日志,转换为用户友好的日志消息
- */
-class CollectUserLogJob implements ShouldQueue
-{
-    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
-
-    /**
-     * 任务最大尝试次数
-     *
-     * @var int
-     */
-    public $tries = 3;
-
-    /**
-     * 任务超时时间(秒)
-     *
-     * @var int
-     */
-    public $timeout = 60;
-
-    /**
-     * 指定收集器名称
-     *
-     * @var string|null
-     */
-    protected ?string $collectorName;
-
-    /**
-     * 创建新的任务实例
-     *
-     * @param string|null $collectorName 收集器名称,null表示执行所有收集器
-     */
-    public function __construct(?string $collectorName = null)
-    {
-        $this->collectorName = $collectorName;
-    }
-
-    /**
-     * 执行任务
-     *
-     * @return void
-     */
-    public function handle(): void
-    {
-        try {
-            $manager = new UserLogCollectorManager();
-
-            if ($this->collectorName) {
-                // 执行指定收集器
-                $result = $manager->collectByName($this->collectorName);
-
-                Log::info('用户日志收集任务执行完成', [
-                    'collector' => $this->collectorName,
-                    'processed_count' => $result['processed_count'],
-                    'execution_time' => $result['execution_time'],
-                    'status' => $result['status']
-                ]);
-
-                if ($result['status'] === 'error') {
-                    throw new \Exception("收集器 {$this->collectorName} 执行失败: {$result['error']}");
-                }
-            } else {
-                // 执行所有收集器
-                $results = $manager->collectAll();
-
-                Log::info('用户日志收集任务执行完成', [
-                    'total_processed' => $results['total_processed'],
-                    'total_execution_time' => $results['total_execution_time'],
-                    'collectors_count' => count($results['collectors'])
-                ]);
-
-                // 检查是否有失败的收集器
-                $failedCollectors = [];
-                foreach ($results['collectors'] as $name => $result) {
-                    if ($result['status'] === 'error') {
-                        $failedCollectors[] = $name;
-                    }
-                }
-
-                if (!empty($failedCollectors)) {
-                    throw new \Exception('部分收集器执行失败: ' . implode(', ', $failedCollectors));
-                }
-            }
-
-        } catch (\Exception $e) {
-            Log::error('用户日志收集任务异常', [
-                'collector' => $this->collectorName,
-                'error' => $e->getMessage(),
-                'attempt' => $this->attempts()
-            ]);
-
-            // 重新抛出异常以触发重试机制
-            throw $e;
-        }
-    }
-
-    /**
-     * 任务失败时的处理
-     *
-     * @param \Throwable $exception
-     * @return void
-     */
-    public function failed(\Throwable $exception): void
-    {
-        Log::error('用户日志收集任务最终失败', [
-            'collector' => $this->collectorName,
-            'error' => $exception->getMessage(),
-            'attempts' => $this->attempts()
-        ]);
-
-        // 可以在这里实现失败后的补偿机制
-        // 比如发送告警通知或记录到特殊日志文件
-    }
-
-    /**
-     * 静态方法:调度日志收集任务
-     *
-     * @param string|null $collectorName 收集器名称,null表示执行所有收集器
-     * @return void
-     */
-    public static function dispatchCollection(?string $collectorName = null): void
-    {
-        try {
-            self::dispatch($collectorName);
-
-            Log::info('调度用户日志收集任务', [
-                'collector' => $collectorName ?? 'all'
-            ]);
-
-        } catch (\Exception $e) {
-            Log::error('调度用户日志收集任务失败', [
-                'collector' => $collectorName,
-                'error' => $e->getMessage()
-            ]);
-        }
-    }
-}

+ 0 - 252
app/Module/Game/Services/UserLogScheduleService.php

@@ -1,252 +0,0 @@
-<?php
-
-namespace App\Module\Game\Services;
-
-use App\Module\Game\Jobs\CollectUserLogJob;
-use App\Module\Game\Logics\UserLogCollectorManager;
-use Illuminate\Support\Facades\Log;
-
-/**
- * 用户日志调度服务
- *
- * 负责管理用户日志收集的调度任务
- */
-class UserLogScheduleService
-{
-    /**
-     * 执行日志收集(同步方式)
-     *
-     * @param string|null $collectorName 收集器名称,null表示执行所有收集器
-     * @return array 执行结果
-     */
-    public static function collectNow(?string $collectorName = null): array
-    {
-        try {
-            $manager = new UserLogCollectorManager();
-
-            if ($collectorName) {
-                return $manager->collectByName($collectorName);
-            } else {
-                return $manager->collectAll();
-            }
-
-        } catch (\Exception $e) {
-            Log::error('同步执行日志收集失败', [
-                'collector' => $collectorName,
-                'error' => $e->getMessage()
-            ]);
-
-            return [
-                'status' => 'error',
-                'error' => $e->getMessage(),
-                'timestamp' => now()->toDateTimeString()
-            ];
-        }
-    }
-
-    /**
-     * 调度日志收集任务(异步方式)
-     *
-     * @param string|null $collectorName 收集器名称,null表示执行所有收集器
-     * @return void
-     */
-    public static function scheduleCollection(?string $collectorName = null): void
-    {
-        CollectUserLogJob::dispatchCollection($collectorName);
-    }
-
-    /**
-     * 获取收集器信息
-     *
-     * @return array
-     */
-    public static function getCollectorsInfo(): array
-    {
-        try {
-            $manager = new UserLogCollectorManager();
-            return $manager->getCollectorsInfo();
-
-        } catch (\Exception $e) {
-            Log::error('获取收集器信息失败', [
-                'error' => $e->getMessage()
-            ]);
-            return [];
-        }
-    }
-
-    /**
-     * 重置收集器进度
-     *
-     * @param string|null $collectorName 收集器名称,null表示重置所有收集器
-     * @return bool
-     */
-    public static function resetCollector(?string $collectorName = null): bool
-    {
-        try {
-            $manager = new UserLogCollectorManager();
-
-            if ($collectorName) {
-                $manager->resetCollector($collectorName);
-            } else {
-                $manager->resetAllCollectors();
-            }
-
-            return true;
-
-        } catch (\Exception $e) {
-            Log::error('重置收集器进度失败', [
-                'collector' => $collectorName,
-                'error' => $e->getMessage()
-            ]);
-            return false;
-        }
-    }
-
-    /**
-     * 检查收集器状态
-     *
-     * @return array
-     */
-    public static function checkCollectorsStatus(): array
-    {
-        try {
-            $manager = new UserLogCollectorManager();
-            $collectorsInfo = $manager->getCollectorsInfo();
-            $status = [];
-
-            foreach ($collectorsInfo as $name => $info) {
-                $cacheKey = "user_log_collector:last_processed_id:{$info['source_table']}";
-                $lastProcessedId = \Illuminate\Support\Facades\Cache::get($cacheKey, 0);
-                
-                $status[$name] = [
-                    'name' => $name,
-                    'source_table' => $info['source_table'],
-                    'source_type' => $info['source_type'],
-                    'last_processed_id' => $lastProcessedId,
-                    'last_check_time' => now()->toDateTimeString(),
-                ];
-            }
-
-            return $status;
-
-        } catch (\Exception $e) {
-            Log::error('检查收集器状态失败', [
-                'error' => $e->getMessage()
-            ]);
-            return [];
-        }
-    }
-
-    /**
-     * 获取收集统计信息
-     *
-     * @param int $days 统计天数
-     * @return array
-     */
-    public static function getCollectionStats(int $days = 7): array
-    {
-        try {
-            $stats = [
-                'period' => "{$days}天",
-                'start_date' => now()->subDays($days)->toDateString(),
-                'end_date' => now()->toDateString(),
-                'total_logs' => 0,
-                'daily_stats' => [],
-                'source_type_stats' => [],
-            ];
-
-            // 获取总日志数
-            $totalLogs = \App\Module\Game\Models\UserLog::where('created_at', '>=', now()->subDays($days))
-                ->count();
-            $stats['total_logs'] = $totalLogs;
-
-            // 获取每日统计
-            $dailyStats = \App\Module\Game\Models\UserLog::where('created_at', '>=', now()->subDays($days))
-                ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
-                ->groupBy('date')
-                ->orderBy('date')
-                ->get()
-                ->pluck('count', 'date')
-                ->toArray();
-            $stats['daily_stats'] = $dailyStats;
-
-            // 获取来源类型统计
-            $sourceTypeStats = \App\Module\Game\Models\UserLog::where('created_at', '>=', now()->subDays($days))
-                ->selectRaw('source_type, COUNT(*) as count')
-                ->whereNotNull('source_type')
-                ->groupBy('source_type')
-                ->get()
-                ->pluck('count', 'source_type')
-                ->toArray();
-            $stats['source_type_stats'] = $sourceTypeStats;
-
-            return $stats;
-
-        } catch (\Exception $e) {
-            Log::error('获取收集统计信息失败', [
-                'error' => $e->getMessage()
-            ]);
-            return [];
-        }
-    }
-
-    /**
-     * 健康检查
-     *
-     * @return array
-     */
-    public static function healthCheck(): array
-    {
-        try {
-            $health = [
-                'status' => 'healthy',
-                'checks' => [],
-                'timestamp' => now()->toDateTimeString(),
-            ];
-
-            // 检查收集器是否正常注册
-            $manager = new UserLogCollectorManager();
-            $collectorsInfo = $manager->getCollectorsInfo();
-            
-            $health['checks']['collectors_registered'] = [
-                'status' => !empty($collectorsInfo) ? 'pass' : 'fail',
-                'count' => count($collectorsInfo),
-                'details' => array_keys($collectorsInfo),
-            ];
-
-            // 检查最近是否有日志生成
-            $recentLogsCount = \App\Module\Game\Models\UserLog::where('created_at', '>=', now()->subMinutes(10))
-                ->count();
-            
-            $health['checks']['recent_logs'] = [
-                'status' => 'info',
-                'count' => $recentLogsCount,
-                'message' => "最近10分钟生成了 {$recentLogsCount} 条日志",
-            ];
-
-            // 检查数据库连接
-            try {
-                \App\Module\Game\Models\UserLog::count();
-                $health['checks']['database'] = [
-                    'status' => 'pass',
-                    'message' => '数据库连接正常',
-                ];
-            } catch (\Exception $e) {
-                $health['checks']['database'] = [
-                    'status' => 'fail',
-                    'message' => '数据库连接失败: ' . $e->getMessage(),
-                ];
-                $health['status'] = 'unhealthy';
-            }
-
-            return $health;
-
-        } catch (\Exception $e) {
-            return [
-                'status' => 'unhealthy',
-                'error' => $e->getMessage(),
-                'timestamp' => now()->toDateTimeString(),
-            ];
-        }
-    }
-}

+ 2 - 0
routes/console.php

@@ -24,6 +24,8 @@ Artisan::command('inspire', function () {
 // 每2秒收集用户日志(需要配置cron每分钟执行30次)
 //\Illuminate\Support\Facades\Schedule::command('game:collect-user-logs')->everyTwoSeconds()->onOneServer();
 
+
+
 // mex 匹配
 // \Illuminate\Support\Facades\Schedule::command('mex:user-sell-item-match')->everyMinute()->onOneServer();
 // \Illuminate\Support\Facades\Schedule::command('mex:user-buy-item-match')->everyFiveMinutes()->onOneServer();