# All files / services log.service.ts

0% Statements 0/222
0% Branches 0/1
0% Functions 0/1
0% Lines 0/222

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354

     import fs from 'fs';
    import path from 'path';

    // 日志级别枚举
    export enum LogLevel {
      DEBUG = 'DEBUG',
      INFO = 'INFO',
      WARN = 'WARN',
      ERROR = 'ERROR',
    }

    // 请求日志结构
    export interface RequestLog {
      requestId: string;
      timestamp: Date;
      method: string;
      path: string;
      query: string;
      status: number;
      responseTime: number;
      responseSize: number;
      level: LogLevel;
      error?: string;
      stack?: string;
      headers: Record<string, string>;
      ip: string;
      userAgent: string;
      body?: any;
    }

    // 错误分析结果
    export interface ErrorAnalysis {
      errorType: string;
      errorMessage: string;
      count: number;
      lastOccurrence: Date;
      paths: string[];
      solutions: string[];
    }

    // 日志服务类
    export class LogService {
      private logs: RequestLog[] = [];
      private maxLogs: number = 10000;
      private logFilePath: string;
      private errorPatterns: Map<string, RegExp> = new Map();
      private errorSolutions: Map<string, string[]> = new Map();

      constructor() {
        this.logFilePath = path.join(process.cwd(), 'logs', 'requests.json');

        // 确保日志目录存在
        const logDir = path.dirname(this.logFilePath);
        if (!fs.existsSync(logDir)) {
          fs.mkdirSync(logDir, { recursive: true });
        }

        // 初始化错误模式和解决方案
        this.initializeErrorPatterns();

        // 从文件加载历史日志
        this.loadLogs();
      }

      // 初始化常见错误模式
      private initializeErrorPatterns(): void {
        // 数据库连接错误
        this.errorPatterns.set('DB_CONNECTION', /ECONNREFUSED|ER_ACCESS_DENIED_ERROR|Connection refused/);
        this.errorSolutions.set('DB_CONNECTION', [
          '检查MySQL服务是否启动',
          '检查数据库连接配置是否正确',
          '确认数据库用户权限'
        ]);

        // JSON解析错误
        this.errorPatterns.set('JSON_PARSE', /JSON\.parse|SyntaxError|Unexpected token/);
        this.errorSolutions.set('JSON_PARSE', [
          '检查请求body格式是否为有效JSON',
          '确认Content-Type为application/json'
        ]);

        // 参数验证错误
        this.errorPatterns.set('VALIDATION', /validation|is required|invalid parameter/);
        this.errorSolutions.set('VALIDATION', [
          '检查请求参数是否完整',
          '验证参数类型是否正确'
        ]);

        // 文件不存在错误
        this.errorPatterns.set('FILE_NOT_FOUND', /ENOENT|no such file|not found/);
        this.errorSolutions.set('FILE_NOT_FOUND', [
          '检查文件路径是否正确',
          '确认文件是否已上传'
        ]);

        // 权限错误
        this.errorPatterns.set('PERMISSION', /EACCES|permission denied|Unauthorized/);
        this.errorSolutions.set('PERMISSION', [
          '检查用户权限设置',
          '确认登录状态是否有效'
        ]);

        // 超时错误
        this.errorPatterns.set('TIMEOUT', /ETIMEDOUT|timeout|TIMEOUT/);
        this.errorSolutions.set('TIMEOUT', [
          '检查网络连接是否稳定',
          '增加请求超时时间',
          '重试请求'
        ]);
      }

      // 加载历史日志
      private loadLogs(): void {
        try {
          if (fs.existsSync(this.logFilePath)) {
            const data = fs.readFileSync(this.logFilePath, 'utf-8');
            const logs = JSON.parse(data);
            this.logs = logs.map((log: any) => ({
              ...log,
              timestamp: new Date(log.timestamp)
            }));
            console.log(`📋 已加载 ${this.logs.length} 条历史日志`);
          }
        } catch (error) {
          console.error('加载日志文件失败:', error);
        }
      }

      // 保存日志到文件
      private saveLogs(): void {
        try {
          // 只保存最近的日志
          const logsToSave = this.logs.slice(-this.maxLogs);
          fs.writeFileSync(this.logFilePath, JSON.stringify(logsToSave, null, 2));
        } catch (error) {
          console.error('保存日志文件失败:', error);
        }
      }

      // 记录请求日志
      logRequest(log: RequestLog): void {
        log.timestamp = new Date();

        // 添加到内存日志
        this.logs.push(log);

        // 超过最大数量时移除旧日志
        if (this.logs.length > this.maxLogs) {
          this.logs = this.logs.slice(-this.maxLogs);
        }

        // 异步保存到文件
        setTimeout(() => this.saveLogs(), 100);

        // 控制台输出
        const levelEmoji = {
          [LogLevel.DEBUG]: '🔍',
          [LogLevel.INFO]: '📝',
          [LogLevel.WARN]: '⚠️',
          [LogLevel.ERROR]: '❌'
        };

        console.log(
          `${levelEmoji[log.level]} [${log.level}] ${log.method} ${log.path} - ${log.status} (${log.responseTime}ms)`
        );

        // 错误日志额外输出错误信息
        if (log.error) {
          console.error(`   Error: ${log.error}`);
        }
      }

      // 获取所有日志
      getLogs(filter?: {
        level?: LogLevel;
        path?: string;
        status?: number;
        startTime?: Date;
        endTime?: Date;
      }): RequestLog[] {
        let result = [...this.logs];

        if (filter) {
          if (filter.level) {
            result = result.filter(log => log.level === filter.level);
          }
          if (filter.path) {
            result = result.filter(log => log.path.includes(filter.path));
          }
          if (filter.status) {
            result = result.filter(log => log.status === filter.status);
          }
          if (filter.startTime) {
            result = result.filter(log => log.timestamp >= filter.startTime);
          }
          if (filter.endTime) {
            result = result.filter(log => log.timestamp <= filter.endTime);
          }
        }

        return result;
      }

      // 获取错误日志
      getErrorLogs(): RequestLog[] {
        return this.logs.filter(log => log.level === LogLevel.ERROR);
      }

      // 获取最近N条错误日志
      getRecentErrors(count: number = 10): RequestLog[] {
        return this.logs
          .filter(log => log.level === LogLevel.ERROR)
          .slice(-count)
          .reverse();
      }

      // 分析错误模式
      analyzeErrors(): ErrorAnalysis[] {
        const errorLogs = this.getErrorLogs();
        const analyses: Map<string, ErrorLogGroup> = new Map();

        interface ErrorLogGroup {
          errorType: string;
          errorMessage: string;
          count: number;
          lastOccurrence: Date;
          paths: Set<string>;
        }

        for (const log of errorLogs) {
          if (!log.error) continue;

          // 匹配错误类型
          let matchedType = 'UNKNOWN';
          let matchedMessage = log.error;

          for (const [type, pattern] of this.errorPatterns) {
            if (pattern.test(log.error)) {
              matchedType = type;
              break;
            }
          }

          const key = `${matchedType}:${log.error.substring(0, 100)}`;

          if (!analyses.has(key)) {
            analyses.set(key, {
              errorType: matchedType,
              errorMessage: log.error,
              count: 0,
              lastOccurrence: log.timestamp,
              paths: new Set()
            });
          }

          const group = analyses.get(key)!;
          group.count++;
          group.lastOccurrence = log.timestamp;
          group.paths.add(log.path);
        }

        // 转换为结果数组
        return Array.from(analyses.values()).map(group => ({
          errorType: group.errorType,
          errorMessage: group.errorMessage,
          count: group.count,
          lastOccurrence: group.lastOccurrence,
          paths: Array.from(group.paths),
          solutions: this.errorSolutions.get(group.errorType) || ['请查看错误日志获取更多信息']
        }));
      }

      // 自动分析并提供修复建议
      autoAnalyzeError(errorLog: RequestLog): string[] {
        if (!errorLog.error) return ['没有错误信息'];

        const suggestions: string[] = [];

        // 检查是否匹配已知错误模式
        for (const [type, pattern] of this.errorPatterns) {
          if (pattern.test(errorLog.error)) {
            const solutions = this.errorSolutions.get(type);
            if (solutions) {
              suggestions.push(...solutions);
            }
          }
        }

        // 如果没有匹配的模式，提供通用建议
        if (suggestions.length === 0) {
          suggestions.push('检查错误日志了解详细信息');
          suggestions.push('查看相关代码逻辑');
          suggestions.push('尝试重新请求');
        }

        return suggestions;
      }

      // 清除旧日志
      clearLogs(olderThanHours?: number): number {
        const now = new Date();
        let initialCount = this.logs.length;

        if (olderThanHours) {
          const cutoffTime = new Date(now.getTime() - olderThanHours * 60 * 60 * 1000);
          this.logs = this.logs.filter(log => log.timestamp >= cutoffTime);
        } else {
          this.logs = [];
        }

        const removed = initialCount - this.logs.length;
        this.saveLogs();

        return removed;
      }

      // 获取统计数据
      getStats(): {
        total: number;
        errors: number;
        warnings: number;
        averageResponseTime: number;
        topPaths: Array<{ path: string; count: number }>;
      } {
        const stats = {
          total: this.logs.length,
          errors: this.logs.filter(l => l.level === LogLevel.ERROR).length,
          warnings: this.logs.filter(l => l.level === LogLevel.WARN).length,
          averageResponseTime: 0,
          topPaths: [] as Array<{ path: string; count: number }>
        };

        if (this.logs.length > 0) {
          const totalResponseTime = this.logs.reduce((sum, log) => sum + log.responseTime, 0);
          stats.averageResponseTime = Math.round(totalResponseTime / this.logs.length);
        }

        // 统计最常访问的路径
        const pathCounts = new Map<string, number>();
        for (const log of this.logs) {
          pathCounts.set(log.path, (pathCounts.get(log.path) || 0) + 1);
        }

        stats.topPaths = Array.from(pathCounts.entries())
          .map(([path, count]) => ({ path, count }))
          .sort((a, b) => b.count - a.count)
          .slice(0, 10);

        return stats;
      }
    }

    // 导出单例
    export const logService = new LogService();