# nest-ai-log-analyzer **Repository Path**: hanxiaohui521/nest-ai-log-analyzer ## Basic Information - **Project Name**: nest-ai-log-analyzer - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-13 - **Last Updated**: 2026-06-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # nest-ai-log-analyzer [![npm version](https://img.shields.io/npm/v/nest-ai-log-analyzer)](https://npmjs.com/package/nest-ai-log-analyzer) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Node](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](package.json) [![NestJS](https://img.shields.io/badge/NestJS-%3E%3D10-ea2845)](package.json) > **[English](README.en.md)** | 简体中文 **NestJS AI 错误诊断插件** — 自动捕获异常、解析堆栈、定位源码、调用大模型生成修复方案。 > 一行接入,报错时自动调用 AI 分析根因并给出修复代码片段。 --- ## 特性 - 🎯 **全局异常捕获** — 注册一个 Module 即接入所有异常 - 🔍 **堆栈解析** — 解析 V8/Node.js 堆栈轨迹,定位到文件+行号 - 📖 **源码上下文** — 自动读取报错位置附近的代码 - 🤖 **AI 分析引擎** — 支持 OpenAI / Ollama / OpenAI 兼容 API - 🛡️ **生产安全** — 生产环境自动阻止代码外发到外部 API - 🔐 **敏感信息过滤** — 发送前自动脱敏 `Authorization`、`password`、`API Key` - 📊 **彩色报告** — 终端格式化输出根因、建议、修复代码 - 📁 **文件日志** — 分析结果自动写入 JSON Lines 文件 - 📈 **错误统计** — 按类型和指纹聚合,支持 Top-N 查询 - 🔔 **Webhook 通知** — 严重错误推送到飞书/钉钉/企微/自定义 - 🧠 **Ollama 模型检测** — 自动检测可用模型列表,智能选择最优模型 - ⚡ **去重机制** — 相同错误 5 分钟内不重复分析 - 🌐 **HTTP 端点** — 通过路由获取最近分析结果、错误统计、模型列表 - 🧩 **纯函数核心** — Parser、Analyzer 等模块可独立使用 - 📝 **自定义 Prompt** — 注入自己的 system prompt 模板 - 🗜️ **简洁 Prompt 模式** — 紧凑提示词节省 token(不含源码上下文) - 🐳 **Docker 一键启动** — `docker compose up` 运行完整示例 - 🔄 **Source Map 支持** — 自动解析编译后代码到原始 TS 源码 - 🗄️ **Redis 共享去重** — PM2 集群 / 多 pods 部署跨进程去重 - 🐛 **Issue 自动创建** — 严重错误自动在 GitHub / GitLab / Gitee / GitCode 创建 Issue - 📊 **Web Dashboard** — 内置历史记录 / 趋势图表 / 分页查询 - 📦 **CJS + ESM 双构建** — 同时支持 CommonJS 和 ES Module --- ## 安装 ```bash npm install nest-ai-log-analyzer ``` 要求:**Node.js >= 18**,**NestJS >= 10** --- ## 快速开始 ### 方式一:docker-compose(推荐,体验完整功能) ```bash # 一键启动 Ollama + 示例 NestJS 应用 docker compose up # 访问测试端点 curl http://localhost:3000/hello curl http://localhost:3000/type-error # 触发 AI 分析 ``` > 首次启动自动拉取 `deepseek-coder:1.3b` 模型,约 1-2 分钟。 ### 方式二:集成到你的 NestJS 项目 #### 1. 注册模块 ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { AiLogAnalyzerModule } from 'nest-ai-log-analyzer'; @Module({ imports: [ AiLogAnalyzerModule.forRoot({ config: { ai: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY, }, }, }), ], }) export class AppModule {} ``` #### 2. 完成 ✅ 所有未捕获异常会自动触发 AI 分析。当你访问一个会报错的路由时,控制台输出类似: ``` ════════════════════════════════════════════ 🔍 AI Error Analysis Report ════════════════════════════════════════════ Root Cause: TypeError: Cannot read properties of null (reading 'items') → src/orders/orders.service.ts:45:22 getOrderItems() → The variable `order` is null because the database query returned no results for the given ID, but the code assumes it's always non-null. Confidence: 92% 💡 Fix Suggestion: Add a null check before accessing order.items. Use optional chaining or an early return when order is null. 📝 Fix Code: │ async getOrder(id: string) { │ const order = await this.db.find(id); │ if (!order) throw new NotFoundException(`Order #${id} not found`); │ return order.items.map(i => i.productName); │ } ════════════════════════════════════════════ ``` --- ## 配置选项 ### AiLogAnalyzerConfig ```typescript interface AiLogAnalyzerConfig { ai: { provider: 'openai' | 'ollama' | 'openai-compat'; apiKey?: string; // OpenAI / 兼容 API 需要 baseUrl?: string; // 自定义端点 model?: string; // 默认: openai→gpt-4o-mini, ollama→deepseek-coder:1.3b temperature?: number; // 默认 0.1 maxTokens?: number; // 默认 2048 customPrompt?: string; // 自定义 system prompt 模板 }; behavior?: { enabled?: boolean; // 默认 true includeSourceCode?: boolean; // 默认 true includeEnvironment?: boolean; // 默认 false — 是否注入环境信息 environmentVars?: string[]; // 自定义环境变量白名单 compactPrompt?: boolean; // 默认 false — 紧凑提示词,不含源码上下文 maxSourceLines?: number; // 默认 20 deduplicate?: boolean; // 默认 true dedupBackend?: 'memory' | 'redis'; // 默认 'memory' dedupTtlMs?: number; // 默认 300000 (5分钟) severityThreshold?: 'low' | 'medium' | 'high' | 'critical'; // 默认 'medium' logLevel?: 'debug' | 'info' | 'warn' | 'error'; // 默认 'info' exposeEndpoint?: boolean; // 默认 false — 开启 HTTP 端点 endpointPrefix?: string; // 默认 '__ai-log-analyzer' }; reporter?: { console?: boolean; // 默认 true logFile?: string; // 输出到文件(可选)— 自动启用 FileReporter silent?: boolean; // 默认 false }; notifier?: { webhookUrl: string; // Webhook 地址(必填) platform?: 'generic' | 'feishu' | 'dingtalk' | 'wecom'; // 默认 'generic' minSeverity?: 'low' | 'medium' | 'high' | 'critical'; // 默认 'high' timeout?: number; // 请求超时毫秒,默认 5000 }; issueReporter?: { platform: 'github' | 'gitlab' | 'gitee' | 'gitcode'; // 代码托管平台 repo: string; // 仓库地址,格式 owner/repo token?: string; // API Token(默认从 GITHUB_TOKEN / GITLAB_TOKEN / GITEE_TOKEN / GITCODE_TOKEN 环境变量读取) minSeverity?: 'low' | 'medium' | 'high' | 'critical'; // 默认 'high' labels?: string[]; // 默认 ['bug', 'ai-analyzed'] assignees?: string[]; // Issue 负责人 baseUrl?: string; // 自定义 API 地址(用于自托管实例) timeout?: number; // 请求超时毫秒,默认 5000 }; } ``` ### 配置示例 ```typescript // Ollama 本地模型(推荐生产环境) AiLogAnalyzerModule.forRoot({ config: { ai: { provider: 'ollama', model: 'deepseek-coder:1.3b', // 或 deepseek-coder:7b baseUrl: 'http://localhost:11434', }, behavior: { includeSourceCode: true, deduplicate: true, severityThreshold: 'high', // 只分析 high 及以上级别 }, }, }); ``` ```typescript // OpenAI 兼容 API(如 DeepSeek、智谱等) AiLogAnalyzerModule.forRoot({ config: { ai: { provider: 'openai-compat', baseUrl: 'https://api.deepseek.com/v1', apiKey: process.env.DEEPSEEK_API_KEY, model: 'deepseek-chat', }, }, }); ``` ```typescript // 多平台 Issue 自动创建 AiLogAnalyzerModule.forRoot({ config: { ai: { provider: 'ollama' }, issueReporter: { platform: 'github', // 可选: github / gitlab / gitee / gitcode repo: 'my-org/my-repo', token: process.env.GH_TOKEN, // 或 GITLAB_TOKEN / GITEE_TOKEN / GITCODE_TOKEN minSeverity: 'high', labels: ['bug', 'ai-analyzed'], baseUrl: 'https://gitlab.mycompany.com/api/v4', // 自托管实例 }, }, }); ``` ### 异步配置 (forRootAsync) 适用于从 ConfigModule 获取配置: ```typescript AiLogAnalyzerModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => ({ config: { ai: { provider: config.get('AI_PROVIDER'), apiKey: config.get('AI_API_KEY'), }, }, }), }); ``` --- ## Provider 对比 | Provider | 数据本地 | 需要 API Key | 生产可用 | 推荐场景 | | --------------- | :--------: | :----------: | :--------: | --------------------- | | **Ollama** | ✅ | ❌ | ✅ | 本地开发 / 私有化部署 | | **OpenAI** | ❌ | ✅ | ❌\* | 开发调试 | | **OpenAI 兼容** | 取决于部署 | 取决于服务 | 取决于部署 | 使用国内大模型 API | > \* 生产环境使用 OpenAI 会自动抛出 `ConfigError`,防止代码泄露。 --- ## 安全规则 | 规则 | 说明 | | -------------------- | ---------------------------------------------------------------------------------- | | **生产环境禁止外发** | `NODE_ENV=production` 时,OpenAI 等外部 provider 会抛错 | | **敏感信息脱敏** | 发送前自动过滤 `Authorization`、`Bearer`、`Token`、`password`、`API Key`、`sk-xxx` | | **本地优先** | 推荐生产环境使用 Ollama 等本地模型 | | **用户确认** | 使用外部 API 时控制台会输出警告日志 | --- ## 架构 ``` ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │ NestJS App │────▶│ GlobalFilter │────▶│ Exception │ │ (Controller)│ │ (catch all) │ │ Handler │ └─────────────┘ └──────────────┘ └──────┬──────┘ │ ┌───────────────────────────┤ ▼ ▼ ┌───────────────┐ ┌────────────────┐ │ StackParser │ │ SourceReader │ │ (parse stack) │ │ (read source) │ └───────┬───────┘ └───────┬────────┘ ▼ ▼ ┌───────────────────────────────────────┐ │ AI Analyzer │ │ ┌─────────┐ ┌──────────┐ │ │ │ OpenAI │ │ Ollama │ │ │ └─────────┘ └──────────┘ │ └───────────────┬───────────────────────┘ ▼ ┌───────────────────────────────────────┐ │ Reporters (复合) │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ Console │ │ File (JSON │ │ │ │ (彩色终端) │ │ Lines) │ │ │ └──────────────┘ └──────────────┘ │ └───────────────┬───────────────────────┘ │ ┌───────────────────┼───────────────────┐ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │ AnalysisStore │ │ ErrorStats │ │ WebhookNotifier │ │ (内存存储) │ │ Reporter │ │ 飞书/钉钉/企微 │ │ │ │ (错误统计) │ │ /通用 Webhook │ │ HTTP 端点: │ │ │ │ │ │ /last-error │ │ /stats │ │ (推送到群机器人) │ │ /ollama-models│ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────────┘ ``` --- ## API 参考 ### 核心导出 | 导出 | 类型 | 说明 | | ------------------------------- | -------- | ------------------------------- | | `AiLogAnalyzerModule` | class | NestJS Module | | `parseStack(stack)` | function | 解析 Error.stack → StackFrame[] | | `filterUserFrames(frames)` | function | 过滤掉原生/内置帧 | | `filterProjectFrames(frames)` | function | 按项目路径过滤帧 | | `readSourceSnippet(path, line)` | function | 读取源码上下文 | | `readSourceFromFrame(frame)` | function | 从 StackFrame 读取源码 | | `ConsoleReporter` | class | 控制台报告器 | | `FileReporter` | class | 文件报告器 (JSON Lines) | | `ErrorStatsReporter` | class | 错误统计报告器 | | `OpenAiAnalyzer` | class | OpenAI 分析器 | | `OllamaAnalyzer` | class | Ollama 分析器,含 `listModels()` 模型检测 | | `WebhookNotifier` | class | Webhook 通知器(飞书/钉钉/企微/通用) | | `PlatformIssueNotifier` | class | 多平台 Issue 通知器(GitHub / GitLab / Gitee / GitCode) | | `GitHubIssueNotifier` | class | GitHub Issue 通知器(旧版,`PlatformIssueNotifier` 的别名) | | `AnalysisStore` | class | 分析结果内存存储(含分页 / 趋势) | | `AnalysisController` | class | HTTP 端点控制器(历史 / 统计 / 仪表盘) | | `MemoryDedupCache` | class | 内存去重缓存 | | `RedisDedupCache` | class | Redis 共享去重缓存 | | `createDedupCache` | function | 去重缓存工厂函数 | | `readSourceSnippetAsync` | function | 异步读取源码(支持 Source Map) | | `resolveSourceMapFrame` | function | Source Map 帧解析 | | `formatWebhookMessage` | function | 格式化 Webhook 消息体 | | `formatGitHubIssueBody` | function | 格式化 GitHub Issue 正文 | | `buildCompactPrompt` | function | 紧凑版 AI 提示词(不含源码) | ### 类型导出 | 导出 | 说明 | | --------------------- | ------------- | | `AiLogAnalyzerConfig` | 用户配置接口 | | `ResolvedConfig` | 解析后的完整配置 | | `StackFrame` | 堆栈帧类型 | | `SourceSnippet` | 源码片段类型 | | `IAiAnalyzer` | AI 分析器接口 | | `AnalysisContext` | 分析上下文 | | `AnalysisResult` | 分析结果 | | `IReporter` | 报告器接口 | | `ErrorStatEntry` | 错误统计条目 | | `WebhookPlatform` | Webhook 平台类型枚举 | | `IDedupCache` | 去重缓存接口 | | `RedisLikeClient` | Redis 客户端类型 | | `IIssueNotifier` | Issue 通知器接口 | | `IssuePlatform` | Issue 平台类型:`'github' | 'gitlab' | 'gitee' | 'gitcode'` | ### DI 令牌 | 令牌 | 注入值 | 说明 | | ------------------------------- | --------------------------- | ------------------------------ | | `AI_REDIS_CLIENT` | `RedisLikeClient` | Redis 去重需要的客户端实例 | | `AI_ISSUE_NOTIFIER` | `PlatformIssueNotifier` | 多平台 Issue 通知器实例 | ### 错误类 | 类 | 错误码 | | --------------- | --------------------------------------------------------- | | `ParserError` | `PARSE_FAILED`, `FILE_NOT_FOUND` | | `AnalyzerError` | `API_ERROR`, `INVALID_RESPONSE`, `PROVIDER_NOT_SUPPORTED` | | `ConfigError` | `INVALID_CONFIG`, `MISSING_API_KEY`, `PRODUCTION_BLOCKED`, `PROVIDER_NOT_SUPPORTED` | --- ## 开发 ```bash # 安装 npm install # 类型检查 npm run typecheck # → tsc --noEmit ✅ # 测试(440 测试用例,覆盖率 99.49%) npm test # 或 npx vitest run --coverage # 构建(CJS + ESM 双构建) npm run build # 格式化 npm run format # API 文档 npm run docs # → docs/api/ ``` ### 项目结构 ``` ├── .gitee/workflows/ # Gitee Go CI/CD 流水线 ├── src/ │ ├── config/ # 配置接口 + Zod 校验 │ ├── parser/ # 堆栈解析 + 源码读取(含 Source Map) │ ├── analyzer/ # AI 分析器(OpenAI / Ollama / 提示词) │ │ └── prompts/ # 提示词模板 + 脱敏工具 │ ├── reporter/ # 输出报告(控制台 / 文件 / 错误统计) │ ├── notifier/ # 通知器(Webhook / 多平台 Issue / 格式化) │ ├── filter/ # 全局异常过滤器 + 编排器 + 去重缓存 │ ├── startup/ # 启动检查(Ollama 连接检测) │ ├── module/ # NestJS Module + HTTP 端点 + 内存存储 │ ├── errors.ts # 自定义错误类 │ └── index.ts # 公共导出 ├── scripts/ # 发版脚本(publish.ps1 / publish.bat) ├── examples/nest-app/ # 完整示例项目 ├── docker-compose.yml # 一键启动 Ollama + 示例应用 ├── test/ # 单元测试 + 集成测试 + Fixtures ├── dist/ # 构建产物(cjs/ + esm/) └── docs/api/ # API 文档(Typedoc 生成) ``` --- ## License MIT