All files / services log.controller.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import Router from '@koa/router';
import { logService, LogLevel } from '../services/log.service';
import { requestLogger } from '../services/requestLogger';
import { Context } from 'koa';
 
const router = new Router();
 
// 获取请求日志列表
router.get('/logs', async (ctx: Context) => {
  const { level, path, status, startTime, endTime, limit = 100, offset = 0 } = ctx.query;
 
  const filter: any = {};
 
  if (level && Object.values(LogLevel).includes(level as LogLevel)) {
    filter.level = level;
  }
  if (path) {
    filter.path = path as string;
  }
  if (status) {
    filter.status = parseInt(status as string, 10);
  }
  if (startTime) {
    filter.startTime = new Date(startTime as string);
  }
  if (endTime) {
    filter.endTime = new Date(endTime as string);
  }
 
  const logs = logService.getLogs(filter);
  const total = logs.length;
  const paginatedLogs = logs.slice(Number(offset), Number(offset) + Number(limit));
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      logs: paginatedLogs,
      total,
      limit: Number(limit),
      offset: Number(offset)
    }
  };
});
 
// 获取错误日志
router.get('/logs/errors', async (ctx: Context) => {
  const { limit = 50 } = ctx.query;
  const errors = logService.getRecentErrors(Number(limit));
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      errors,
      count: errors.length
    }
  };
});
 
// 获取错误分析
router.get('/logs/errors/analyze', async (ctx: Context) => {
  const analyses = logService.analyzeErrors();
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      analyses,
      total: analyses.length
    }
  };
});
 
// 获取最新错误详情
router.get('/logs/errors/latest', async (ctx: Context) => {
  const errors = logService.getRecentErrors(1);
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      error: errors.length > 0 ? errors[0] : null
    }
  };
});
 
// 自动分析单条错误并提供修复建议
router.post('/logs/auto-fix', async (ctx: Context) => {
  const { error, path, method } = ctx.request.body as any;
 
  if (!error) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: '缺少错误信息',
      data: null
    };
    return;
  }
 
  // 创建临时日志对象用于分析
  const tempLog = {
    error,
    path: path || 'unknown',
    timestamp: new Date()
  } as any;
 
  const suggestions = logService.autoAnalyzeError(tempLog);
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      error,
      suggestions,
      path,
      method
    }
  };
});
 
// 执行自动修复(模拟)
router.post('/logs/fix/:errorId', async (ctx: Context) => {
  const { errorId } = ctx.params;
 
  // 这里可以根据errorId执行不同的修复操作
  // 目前是模拟实现
  const fixResults: Record<string, any> = {
    'DB_CONNECTION': {
      success: true,
      action: 'restart_database_connection',
      message: '已重新初始化数据库连接池'
    },
    'JSON_PARSE': {
      success: true,
      action: 'validate_request_body',
      message: '已添加请求体验证中间件'
    },
    'VALIDATION': {
      success: true,
      action: 'sanitize_parameters',
      message: '已添加参数清理逻辑'
    },
    'FILE_NOT_FOUND': {
      success: true,
      action: 'create_default_file',
      message: '已创建默认文件'
    },
    'PERMISSION': {
      success: true,
      action: 'refresh_token',
      message: '已刷新用户权限'
    },
    'TIMEOUT': {
      success: true,
      action: 'increase_timeout',
      message: '已增加超时时间'
    }
  };
 
  const result = fixResults[errorId] || {
    success: false,
    action: 'unknown',
    message: '未知的错误类型,无法自动修复'
  };
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});
 
// 获取统计数据
router.get('/logs/stats', async (ctx: Context) => {
  const stats = logService.getStats();
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: stats
  };
});
 
// 清除日志
router.delete('/logs', async (ctx: Context) => {
  const { olderThanHours } = ctx.query;
 
  const removed = logService.clearLogs(
    olderThanHours ? parseInt(olderThanHours as string, 10) : undefined
  );
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      removed,
      remaining: logService.getLogs().length
    }
  };
});
 
// 测试接口 - 故意产生错误用于测试
router.post('/logs/test-error', async (ctx: Context) => {
  const { type = 'TEST' } = ctx.request.body as any;
 
  if (type === 'DB_CONNECTION') {
    throw new Error('ECONNREFUSED: Connection refused');
  } else if (type === 'JSON_PARSE') {
    throw new Error('JSON.parse: Unexpected token at position 0');
  } else if (type === 'VALIDATION') {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: 'validation failed: field "name" is required'
    };
    return;
  } else if (type === 'FILE_NOT_FOUND') {
    throw new Error('ENOENT: no such file or directory \'uploads/test.txt\'');
  } else if (type === 'PERMISSION') {
    throw new Error('EACCES: permission denied');
  } else if (type === 'TIMEOUT') {
    throw new Error('ETIMEDOUT: connection timeout after 30000ms');
  }
 
  ctx.body = {
    code: 0,
    message: '测试错误已记录'
  };
});
 
export default router;