All files / src/server/routes logs.ts

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

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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import type express from 'express'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import { configLogger, mcpLogger, pluginLogger } from '@dalidev/core'
import { sseTracker } from './sse-diagnostics'
 
// SSE连接管理
interface SSEConnection {
  res: any
  id: string
  filters?: {
    search?: string
    level?: string
    category?: string
  }
}
 
const sseConnections = new Map<string, SSEConnection>()
let logWatcher: fs.FSWatcher | null = null
 
// 从多个位置获取MCP日志文件
function getAllLogFiles(): Array<{ name: string, path: string, size: number, mtime: Date }> {
  const allLogFiles: Array<{ name: string, path: string, size: number, mtime: Date }> = []
 
  // 候选日志目录
  const logDirs = [
    path.join(os.homedir(), '.dalidev', 'logs'),
  ]
 
  logDirs.forEach((logDir) => {
    try {
      if (fs.existsSync(logDir)) {
        const files = fs.readdirSync(logDir)
        files
          .forEach((file) => {
            try {
              const filePath = path.join(logDir, file)
              const stats = fs.statSync(filePath)
              allLogFiles.push({
                name: file,
                path: filePath,
                size: stats.size,
                mtime: stats.mtime,
              })
            }
            catch {
              // 忽略单个文件错误
            }
          })
      }
    }
    catch {
      // 忽略目录访问错误
    }
  })
 
  // 去重(相同名称的文件,保留最新的)
  const fileMap = new Map<string, { name: string, path: string, size: number, mtime: Date }>()
  allLogFiles.forEach((file) => {
    const existing = fileMap.get(file.name)
    if (!existing || existing.mtime < file.mtime) {
      fileMap.set(file.name, file)
    }
  })
 
  return Array.from(fileMap.values()).sort((a, b) => b.mtime.getTime() - a.mtime.getTime())
}
 
// 查找日志文件的完整路径
function findLogFile(filename: string): string | null {
  // 候选日志目录
  const logDirs = [
    pluginLogger.getLogDirectory(), // 插件日志目录
  ]
 
  for (const logDir of logDirs) {
    try {
      const filePath = path.join(logDir, filename)
      if (fs.existsSync(filePath)) {
        return filePath
      }
    }
    catch {
      // 忽略目录访问错误
    }
  }
 
  return null
}
 
export function registerLogsRoutes(app: express.Express) {
  // 获取日志文件列表
  app.get('/api/logs/files', (req, res) => {
    try {
      // 获取插件日志文件
      const pluginLogFiles = pluginLogger.getLogFiles()
      const mcpLogFiles = mcpLogger.getLogFiles()
      const configLogFiles = configLogger.getLogFiles()
 
      const pluginFilesInfo = pluginLogFiles.map(file => ({
        name: file.name,
        size: file.size,
        sizeFormatted: formatFileSize(file.size),
        lastModified: file.mtime.toISOString(),
        lastModifiedFormatted: formatDate(file.mtime),
        path: file.path,
      }))
 
      const mcpFilesInfo = mcpLogFiles.map(file => ({
        name: file.name,
        size: file.size,
        sizeFormatted: formatFileSize(file.size),
        lastModified: file.mtime.toISOString(),
        lastModifiedFormatted: formatDate(file.mtime),
        path: file.path,
      }))
 
      const configFilesInfo = configLogFiles.map(file => ({
        name: file.name,
        size: file.size,
        sizeFormatted: formatFileSize(file.size),
        lastModified: file.mtime.toISOString(),
        lastModifiedFormatted: formatDate(file.mtime),
        path: file.path,
      }))
 
      // 去重处理(相同名称的文件)
      const allFiles = [...pluginFilesInfo, ...mcpFilesInfo, ...configFilesInfo]
      const fileMap = new Map()
      allFiles.forEach((file) => {
        const key = file.name
        if (!fileMap.has(key) || fileMap.get(key).lastModified < file.lastModified) {
          fileMap.set(key, file)
        }
      })
 
      const uniqueFiles = Array.from(fileMap.values())
        .sort((a, b) => new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime())
 
      res.json({
        success: true,
        data: {
          logDirectory: pluginLogger.getLogDirectory(),
          currentLogFile: path.basename(pluginLogger.getCurrentLogFilePath()),
          files: uniqueFiles,
          sources: {
            plugin: pluginFilesInfo.length,
            total: uniqueFiles.length,
          },
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '获取日志文件列表失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 读取日志文件内容
  app.get('/api/logs/content/:filename', (req, res) => {
    try {
      const { filename } = req.params
      const { lines = '100', search = '', level = '', category = '', startTime = '', endTime = '' } = req.query as Record<string, string>
 
      // 尝试从多个位置找到日志文件
      const filePath = findLogFile(filename)
 
      if (!filePath || !fs.existsSync(filePath)) {
        return res.status(404).json({
          success: false,
          error: '日志文件不存在',
        })
      }
 
      // 读取文件内容
      const content = fs.readFileSync(filePath, 'utf-8')
      const allLines = content.split('\n').filter(line => line.trim())
 
      // 应用过滤条件
      let filteredLines = allLines
 
      // 搜索过滤
      if (search) {
        const searchLower = search.toLowerCase()
        filteredLines = filteredLines.filter(line =>
          line.toLowerCase().includes(searchLower),
        )
      }
 
      // 日志级别过滤
      if (level) {
        filteredLines = filteredLines.filter(line =>
          line.includes(`[${level.toUpperCase()}]`),
        )
      }
 
      // 日志分类过滤
      if (category) {
        filteredLines = filteredLines.filter(line =>
          line.includes(`[${category}]`),
        )
      }
 
      // 时间范围过滤
      if (startTime || endTime) {
        filteredLines = filteredLines.filter((line) => {
          // 匹配新的中国时区时间格式: 2024-01-01 12:00:00.000+08:00
          const timeMatch = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\+08:00)/)
          if (!timeMatch)
            return false
 
          const lineTime = new Date(timeMatch[1]).getTime()
          const start = startTime ? new Date(startTime).getTime() : 0
          const end = endTime ? new Date(endTime).getTime() : Number.MAX_VALUE
 
          return lineTime >= start && lineTime <= end
        })
      }
 
      // 限制返回行数
      const maxLines = Math.min(Number.parseInt(lines, 10) || 100, 1000) // 最多返回1000行
      const resultLines = filteredLines.slice(-maxLines) // 返回最新的N行
 
      // pluginLogger.info('Server', '读取日志内容', {
      //   filename,
      //   totalLines: allLines.length,
      //   filteredLines: filteredLines.length,
      //   returnedLines: resultLines.length,
      //   filters: { search, level, category, startTime, endTime },
      // })
 
      res.json({
        success: true,
        data: {
          filename,
          totalLines: allLines.length,
          filteredLines: filteredLines.length,
          returnedLines: resultLines.length,
          lines: resultLines,
          filters: { search, level, category, startTime, endTime, lines: maxLines },
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '读取日志内容失败', { error, filename: req.params.filename })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 获取可用的日志分类
  app.get('/api/logs/categories', (req, res) => {
    try {
      // 分析当前日志文件,提取所有分类
      const currentLogFile = pluginLogger.getCurrentLogFilePath()
      const categories = new Set<string>()
 
      if (fs.existsSync(currentLogFile)) {
        const content = fs.readFileSync(currentLogFile, 'utf-8')
        const lines = content.split('\n')
 
        lines.forEach((line) => {
          // 匹配 [级别] [分类] 格式
          const match = line.match(/\[(?:DEBUG|INFO|WARN|ERROR)\]\s+\[([^\]]+)\]/)
          if (match && match[1]) {
            categories.add(match[1])
          }
        })
      }
 
      const categoryList = Array.from(categories).sort()
 
      pluginLogger.debug('Server', '获取日志分类列表', { categoryCount: categoryList.length })
 
      res.json({
        success: true,
        data: {
          categories: categoryList,
          totalCategories: categoryList.length,
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '获取日志分类列表失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 获取日志统计信息
  app.get('/api/logs/stats', (req, res) => {
    try {
      const logFiles = pluginLogger.getLogFiles()
      const totalSize = logFiles.reduce((sum, file) => sum + file.size, 0)
 
      // 分析当前日志文件的级别分布
      const currentLogFile = pluginLogger.getCurrentLogFilePath()
      const levelStats = { DEBUG: 0, INFO: 0, WARN: 0, ERROR: 0 }
 
      if (fs.existsSync(currentLogFile)) {
        const content = fs.readFileSync(currentLogFile, 'utf-8')
        const lines = content.split('\n')
 
        lines.forEach((line) => {
          if (line.includes('[DEBUG]'))
            levelStats.DEBUG++
          else if (line.includes('[INFO]'))
            levelStats.INFO++
          else if (line.includes('[WARN]'))
            levelStats.WARN++
          else if (line.includes('[ERROR]'))
            levelStats.ERROR++
        })
      }
 
      const stats = {
        totalFiles: logFiles.length,
        totalSize,
        totalSizeFormatted: formatFileSize(totalSize),
        currentLogFile: path.basename(currentLogFile),
        levelStats,
        oldestLog: logFiles.length > 0 ? formatDate(logFiles[logFiles.length - 1].mtime) : null,
        newestLog: logFiles.length > 0 ? formatDate(logFiles[0].mtime) : null,
      }
 
      pluginLogger.info('Server', '获取日志统计信息', { stats })
 
      res.json({
        success: true,
        data: stats,
      })
    }
    catch (error) {
      pluginLogger.error('Server', '获取日志统计信息失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 清理旧日志
  app.post('/api/logs/cleanup', (req, res) => {
    try {
      console.log(req.body)
      const { days = 7 } = req.body
      const maxAge = days * 24 * 60 * 60 * 1000 // 转换为毫秒
      const now = Date.now()
 
      const logFiles = pluginLogger.getLogFiles()
      let deletedCount = 0
      let deletedSize = 0
 
      for (const file of logFiles) {
        if (now - file.mtime.getTime() > maxAge) {
          try {
            fs.unlinkSync(file.path)
            deletedCount++
            deletedSize += file.size
            pluginLogger.info('Server', '删除过期日志文件', { filename: file.name, age: now - file.mtime.getTime() })
          }
          catch (deleteError) {
            pluginLogger.warn('Server', '删除日志文件失败', { filename: file.name, error: deleteError })
          }
        }
      }
 
      pluginLogger.info('Server', '清理旧日志完成', {
        deletedCount,
        deletedSizeFormatted: formatFileSize(deletedSize),
        maxAgeDays: days,
      })
 
      res.json({
        success: true,
        data: {
          deletedCount,
          deletedSize,
          deletedSizeFormatted: formatFileSize(deletedSize),
          maxAgeDays: days,
        },
      })
    }
    catch (error) {
      pluginLogger.error('Server', '清理旧日志失败', { error })
      res.status(500).json({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      })
    }
  })
 
  // 删除指定日志文件
  app.post('/api/logs/delete/file/:filename', (req, res) => {
    try {
      const { filename } = req.params
 
      // 查找文件路径
      const filePath = findLogFile(filename)
      if (!filePath) {
        return res.status(404).json({
          success: false,
          message: '找不到指定的日志文件',
        })
      }
 
      // 检查文件是否存在
      if (!fs.existsSync(filePath)) {
        return res.status(404).json({
          success: false,
          message: '日志文件不存在',
        })
      }
 
      // 获取文件信息(删除前)
      const stats = fs.statSync(filePath)
      const fileSize = stats.size
 
      // 删除文件
      fs.unlinkSync(filePath)
 
      pluginLogger.info('Server', '删除日志文件', {
        filename,
        filePath,
        size: fileSize,
        sizeFormatted: formatFileSize(fileSize),
      })
 
      res.json({
        success: true,
        data: {
          filename,
          deleted: true,
        },
        message: '文件删除成功',
      })
    }
    catch (error) {
      pluginLogger.error('Server', '删除日志文件失败', { filename: req.params.filename, error })
      res.status(500).json({
        success: false,
        message: error instanceof Error ? error.message : '删除文件时发生错误',
      })
    }
  })
 
  // SSE实时日志推送
  app.get('/api/logs/stream', (req, res) => {
    console.log(req.query)
    const { search = '', level = '', category = '' } = req.query as Record<string, string>
    const connectionId = `logs-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
 
    // 设置SSE头
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control',
    })
 
    // 注册到统一跟踪器
    sseTracker.addConnection(connectionId, 'logs', res, req)
 
    // 保存连接
    sseConnections.set(connectionId, {
      res,
      id: connectionId,
      filters: { search, level, category },
    })
 
    // 发送连接确认
    res.write(`data: ${JSON.stringify({ type: 'connected', connectionId })}\n\n`)
 
    // 启动文件监听(如果还没有启动)
    if (!logWatcher) {
      startLogWatcher()
    }
 
    pluginLogger.info('Server', 'SSE日志连接建立', { connectionId, filters: { search, level, category } })
 
    // 处理连接关闭
    req.on('close', () => {
      sseConnections.delete(connectionId)
      sseTracker.removeConnection(connectionId)
      pluginLogger.info('Server', 'SSE日志连接关闭', { connectionId })
 
      // 如果没有活动连接,停止文件监听
      if (sseConnections.size === 0 && logWatcher) {
        logWatcher.close()
        logWatcher = null
        pluginLogger.info('Server', '停止日志文件监听')
      }
    })
  })
}
 
// 文件监听器
function startLogWatcher() {
  const currentLogFile = pluginLogger.getCurrentLogFilePath()
 
  if (!fs.existsSync(currentLogFile)) {
    pluginLogger.warn('Server', '日志文件不存在,无法启动监听', { file: currentLogFile })
    return
  }
 
  logWatcher = fs.watch(currentLogFile, (eventType) => {
    if (eventType === 'change') {
      // 读取文件末尾的新内容
      broadcastNewLogLines(currentLogFile)
    }
  })
 
  pluginLogger.info('Server', '启动日志文件监听', { file: currentLogFile })
}
 
// 广播新的日志行
function broadcastNewLogLines(logFile: string) {
  try {
    // 读取文件的最后几行(简单实现,可以优化为增量读取)
    const content = fs.readFileSync(logFile, 'utf-8')
    const lines = content.split('\n').filter(line => line.trim())
    const lastLines = lines.slice(-10) // 获取最后10行
 
    // 向所有连接发送新日志
    sseConnections.forEach((connection) => {
      const filteredLines = filterLogLines(lastLines, connection.filters || {})
 
      if (filteredLines.length > 0) {
        const data = {
          type: 'newLogs',
          lines: filteredLines,
          timestamp: Date.now(),
        }
 
        try {
          connection.res.write(`data: ${JSON.stringify(data)}\n\n`)
        }
        catch (error) {
          // 连接已断开,清理连接
          sseConnections.delete(connection.id)
          pluginLogger.warn('Server', 'SSE连接写入失败,清理连接', { connectionId: connection.id, error })
        }
      }
    })
  }
  catch (error) {
    pluginLogger.error('Server', '广播新日志失败', { error })
  }
}
 
// 过滤日志行
function filterLogLines(lines: string[], filters: { search?: string, level?: string, category?: string }) {
  let filteredLines = lines
 
  // 搜索过滤
  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    filteredLines = filteredLines.filter(line =>
      line.toLowerCase().includes(searchLower),
    )
  }
 
  // 日志级别过滤
  if (filters.level) {
    filteredLines = filteredLines.filter(line =>
      line.includes(`[${filters.level!.toUpperCase()}]`),
    )
  }
 
  // 日志分类过滤
  if (filters.category) {
    filteredLines = filteredLines.filter(line =>
      line.includes(`[${filters.category}]`),
    )
  }
 
  return filteredLines
}
 
// 工具函数
function isValidLogFileName(filename: string): boolean {
  // 只允许 dalidev-mcp|dalidev-plugin 开头的 .log 文件
  return /^dalidev-mcp-\d{4}-\d{2}-\d{2}.*\.log$|^dalidev-plugin-\d{4}-\d{2}-\d{2}.*\.log$/.test(filename)
}
 
function formatFileSize(bytes: number): string {
  if (bytes === 0)
    return '0 B'
 
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
 
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}
 
function formatDate(date: Date): string {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}