# @geekmidas/telescope 中文文档

规范地址：https://npmcn.com/package/%40geekmidas/telescope/

版本：9\.6\.1
npm 元数据更新时间：2026-11-16T09:29:59.204Z
中文译文更新时间：2026-11-16T09:36:35.875Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40geekmidas/telescope
原文对照：https://npmcn.com/package/%40geekmidas/telescope/?lang=original
项目主页：https://github.com/geekmidas/toolbox#readme
源码仓库：https://github.com/geekmidas/toolbox

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.7 MB，395 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：hono ^4\.0\.0，pino ^9\.0\.0，kysely \>=0\.28\.2 \<0\.30\.0，@middy/core ^5\.0\.0 \|\| ^6\.0\.0，@geekmidas/logger ^9\.6\.1，@types/aws-lambda ^8\.10\.0，@opentelemetry/api ^1\.9\.0，@opentelemetry/sdk-logs \>=0\.57\.0 \<1，@opentelemetry/sdk-node \>=0\.57\.0 \<1，pino-abstract-transport ^2\.0\.0 \|\| ^3\.0\.0，@opentelemetry/resources ^1\.30\.0 \|\| ^2\.0\.0，@opentelemetry/sdk-trace-base ^1\.30\.0 \|\| ^2\.0\.0，@opentelemetry/sdk-trace-node ^1\.30\.0 \|\| ^2\.0\.0，@opentelemetry/instrumentation-pino \>=0\.44\.0 \<1，@opentelemetry/semantic-conventions ^1\.28\.0，@opentelemetry/exporter-logs-otlp-http \>=0\.57\.0 \<1，@opentelemetry/exporter-trace-otlp-http \>=0\.57\.0 \<1，@opentelemetry/auto-instrumentations-node \>=0\.56\.0 \<1
- 首次发布：2025-12-29T19:42:49.881Z
- 最新版本发布：2026-11-16T09:29:58.867Z
- 近 30 天下载量：13723（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：205（近 12 个月 205 个）

## 中文简介

Laravel 望远镜式调试和监测网络应用程序

## 安装

```sh
npm install @geekmidas/telescope
```

也可以使用：`pnpm add @geekmidas/telescope`、`yarn add @geekmidas/telescope`、`bun add @geekmidas/telescope`

## README

# @geekmidas/望远镜

Laravel望远镜式调试和监控网络应用. 实时抓取和检查 HTTP 请求、 例外和日志 .

**框架不可知核心** 配有Hono的适配器,AWS的Lambda和更多.

## 安装

```bash
pnpm add @geekmidas/telescope
```

## 快速启动

### 和浩诺

```typescript
import { Hono } from 'hono';
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { createMiddleware, createUI } from '@geekmidas/telescope/server/hono';

const telescope = new Telescope({
  storage: new InMemoryStorage(),
});

const app = new Hono();

// Add middleware to capture requests
app.use('*', createMiddleware(telescope));

// Mount the dashboard
app.route('/__telescope', createUI(telescope));

// Your routes
app.get('/users', (c) => c.json({ users: [] }));

export default app;
```

访问 `http://localhost:3000/__telescope` 查看仪表板.

### 框架不可知核心

核心内容 `Telescope` 类是框架不可知的。 您可以直接用于手动录制 :

```typescript
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';

const telescope = new Telescope({
  storage: new InMemoryStorage(),
});

// Record a request manually
await telescope.recordRequest({
  method: 'POST',
  path: '/api/users',
  url: 'http://localhost:3000/api/users',
  headers: { 'content-type': 'application/json' },
  body: { name: 'John' },
  query: {},
  status: 201,
  responseHeaders: {},
  responseBody: { id: '123' },
  duration: 45.2,
});

// Log messages
await telescope.log('info', 'User created', { userId: '123' });

// Record exceptions
try {
  throw new Error('Something went wrong');
} catch (error) {
  await telescope.exception(error);
}
```

## 特征

-   **请求记录**: 以标题、正文、查询参数和响应来抓取 HTTP 请求
-   **例外追踪**: 记录有堆栈痕迹和源上下文的例外
-   **日志聚合**: 收集上下文的应用程序日志
-   **实时更新**: WebSocket 驱动的活盘
-   **存储不可知**: Dev 使用内存, 生产数据库
-   **霍诺融合**: 一等中继器和路由安装
-   **Lambda一体化组织**: AWS Lambda 自动擦拭的包装和中继中间软件

## 配置

```typescript
const telescope = new Telescope({
  // Required: Storage backend
  storage: new InMemoryStorage(),

  // Optional: Enable/disable telescope (default: true)
  enabled: true,

  // Optional: Dashboard path (default: '/__telescope')
  path: '/__telescope',

  // Optional: Record request/response bodies (default: true)
  recordBody: true,

  // Optional: Max body size to record in bytes (default: 64KB)
  maxBodySize: 64 * 1024,

  // Optional: URL patterns to ignore
  ignorePatterns: ['/health', '/metrics', '/__telescope/*'],

  // Optional: Auto-prune entries older than X hours
  pruneAfterHours: 24,

  // Optional: Redact sensitive data (see Redaction section)
  redact: true,
});
```

## 敏感数据编辑

望远镜可以自动编辑来自记录的请求、答复和日志的敏感数据 `@pinojs/redact`。 。 。 .

### 启用编辑

```typescript
const telescope = new Telescope({
  storage: new InMemoryStorage(),

  // Enable with default paths
  redact: true,
});
```

### 默认已编辑路径

何时 `redact: true`,这些路径自动被编辑 :

**标题 :**

-   `headers.authorization`, (中文(简体) ), `headers.cookie`, (中文(简体) ), `headers.x-api-key`
-   `responseHeaders.set-cookie`

**请求/答复机构:**

-   `body.password`, (中文(简体) ), `body.token`, (中文(简体) ), `body.accessToken`, (中文(简体) ), `body.refreshToken`
-   `body.apiKey`, (中文(简体) ), `body.secret`, (中文(简体) ), `body.creditCard`, (中文(简体) ), `body.cardNumber`, (中文(简体) ), `body.cvv`, (中文(简体) ), `body.ssn`
-   `body.*.password`, (中文(简体) ), `body.*.token`, (中文(简体) ), `body.*.secret` (笔记字段)
-   相同的图案 `responseBody.*`

**查询参数:**

-   `query.token`, (中文(简体) ), `query.api_key`, (中文(简体) ), `query.apiKey`, (中文(简体) ), `query.access_token`, (中文(简体) ), `query.secret`

**日志背景 :**

-   `context.password`, (中文(简体) ), `context.token`, (中文(简体) ), `context.secret`, (中文(简体) ), `context.apiKey`

### 添加自定义路径

提供添加路径的数组( 与默认合并) :

```typescript
const telescope = new Telescope({
  storage: new InMemoryStorage(),

  // Add custom paths to defaults
  redact: ['user.ssn', 'payment.cardNumber', 'data.*.privateKey'],
});
```

### 全控

使用对象来完全控制编辑 :

```typescript
const telescope = new Telescope({
  storage: new InMemoryStorage(),

  redact: {
    paths: ['headers.authorization', 'body.password'],
    censor: '***HIDDEN***', // Custom replacement (default: '[REDACTED]')
  },
});
```

### 路径语法

路径使用带有通配符支持的点标记 :

| 图案 | 匹配 |
| --- | --- |
| `headers.authorization` | 精确路径 |
| `body.password` | 精确的嵌入路径 |
| `body.*.password` | 有正文中密码字段的任何对象 |
| `*.secret` | 任何级别的秘密领域 |

### 程序访问

```typescript
import { createRedactor, DEFAULT_REDACT_PATHS } from '@geekmidas/telescope';

// Create a standalone redactor
const redactor = createRedactor(true);
const safeData = redactor({ headers: { authorization: 'Bearer secret' } });
// safeData.headers.authorization === '[REDACTED]'

// Access default paths
console.log(DEFAULT_REDACT_PATHS);
```

## 存储后端

### 在记忆中

最好的开发和测试。 数据在重新启动时丢失 .

```typescript
// From main package
import { InMemoryStorage } from '@geekmidas/telescope';
// Or direct import
import { InMemoryStorage } from '@geekmidas/telescope/storage/memory';

const storage = new InMemoryStorage({
  maxEntries: 1000, // Max entries per type (default: 1000)
});
```

### 凯斯利·斯多拉奇(英语:Cysely Storage (Coming Soon))

用于具有数据库持久性的生产.

```typescript
import { KyselyStorage } from '@geekmidas/telescope/storage/kysely';

const storage = new KyselyStorage(db, {
  tablePrefix: 'telescope_', // Table name prefix
});
```

### 自定义存储

执行 `TelescopeStorage` 接口 :

```typescript
import type { TelescopeStorage } from '@geekmidas/telescope';

class MyStorage implements TelescopeStorage {
  async saveRequest(entry: RequestEntry): Promise<void> { /* ... */ }
  async getRequests(options?: QueryOptions): Promise<RequestEntry[]> { /* ... */ }
  async getRequest(id: string): Promise<RequestEntry | null> { /* ... */ }

  async saveException(entry: ExceptionEntry): Promise<void> { /* ... */ }
  async getExceptions(options?: QueryOptions): Promise<ExceptionEntry[]> { /* ... */ }
  async getException(id: string): Promise<ExceptionEntry | null> { /* ... */ }

  async saveLog(entry: LogEntry): Promise<void> { /* ... */ }
  async getLogs(options?: QueryOptions): Promise<LogEntry[]> { /* ... */ }

  async prune(olderThan: Date): Promise<number> { /* ... */ }
  async getStats(): Promise<TelescopeStats> { /* ... */ }
}
```

## API 密码

### 望远镜类( 核心)

#### `telescope.recordRequest(entry)`

按程序记录请求条目.

```typescript
await telescope.recordRequest({
  method: 'GET',
  path: '/api/users',
  url: 'http://localhost:3000/api/users',
  headers: {},
  query: {},
  status: 200,
  responseHeaders: {},
  duration: 25.5,
});
```

#### `telescope.log(level, message, context?, requestId?)`

程序记录日志条目 .

```typescript
await telescope.log('info', 'User logged in', { userId: '123' });
await telescope.log('error', 'Payment failed', { orderId: '456' });
```

#### `telescope.exception(error, requestId?)`

在程序上记录一个例外.

```typescript
try {
  await riskyOperation();
} catch (error) {
  await telescope.exception(error);
  throw error;
}
```

#### `telescope.broadcast(event)`

向所有连接的 WebSocket 客户端发送自定义事件 .

```typescript
telescope.broadcast({
  type: 'custom',
  payload: { message: 'Hello' },
  timestamp: Date.now(),
});
```

#### `telescope.prune(olderThan)`

手动推倒的条目比日期长.

```typescript
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
const deleted = await telescope.prune(oneHourAgo);
console.log(`Pruned ${deleted} entries`);
```

#### `telescope.destroy()`

清理资源(间歇,WebSocket客户端).

```typescript
telescope.destroy();
```

### Hono 适应器

从 `@geekmidas/telescope/server/hono`数字 :

```typescript
import { createMiddleware, createUI, setupWebSocket, getRequestId } from '@geekmidas/telescope/server/hono';
```

#### `createMiddleware(telescope)`

返回捕捉请求和响应的Hono中间软件.

```typescript
app.use('*', createMiddleware(telescope));
```

#### `createUI(telescope)`

返回带有仪表盘 UI 和 API 路由的 Hono 应用程序 .

```typescript
app.route('/__telescope', createUI(telescope));
```

#### `setupWebSocket(app, telescope, upgradeWebSocket)`

为实时更新设置 WebSocket 路由.

```typescript
import { createNodeWebSocket } from '@hono/node-ws';

const { upgradeWebSocket } = createNodeWebSocket({ app });
setupWebSocket(createUI(telescope), telescope, upgradeWebSocket);
```

#### `getRequestId(c)`

从Hono上下文(由中间软件设置)获取请求ID.

```typescript
app.get('/api/data', (c) => {
  const requestId = getRequestId(c);
  // Use requestId for correlated logging
  telescope.log('info', 'Processing request', { data: 'value' }, requestId);
  return c.json({ success: true });
});
```

### Lambda 适应器

从 `@geekmidas/telescope/adapters/lambda`数字 :

```typescript
import { wrapLambdaHandler, LambdaAdapter } from '@geekmidas/telescope/adapters/lambda';
```

#### `wrapLambdaHandler(telescope, handler, options?)`

包裹一个Lambda处理器,在Lambda上下文被冻结之前自动记录请求并冲出遥测.

```typescript
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { wrapLambdaHandler } from '@geekmidas/telescope/adapters/lambda';

const telescope = new Telescope({ storage: new InMemoryStorage() });

export const handler = wrapLambdaHandler(telescope, async (event, context) => {
  // Your Lambda logic here
  return { statusCode: 200, body: JSON.stringify({ success: true }) };
});
```

支持API Gateway v1(REST API),API Gateway v2(HTTP API),以及ALB事件. 对于非HTTP引用,将事件记录为请求机构.

#### 选项

```typescript
wrapLambdaHandler(telescope, handler, {
  // Auto-flush telemetry before Lambda freezes (default: true)
  autoFlush: true,

  // Detect Lambda resource attributes from environment (default: true)
  detectResource: true,
});
```

#### `LambdaAdapter` 类

更多的控制,请使用 `LambdaAdapter` 直接分类 :

```typescript
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { LambdaAdapter } from '@geekmidas/telescope/adapters/lambda';

const telescope = new Telescope({ storage: new InMemoryStorage() });
const adapter = new LambdaAdapter(telescope);

export const handler = async (event, context) => {
  const requestContext = adapter.extractRequestContext(event);

  try {
    const result = await processEvent(event);

    const responseContext = adapter.extractResponseContext(result, requestContext.startTime);
    await telescope.recordRequest({
      method: requestContext.method,
      path: requestContext.path,
      url: requestContext.url,
      headers: requestContext.headers,
      query: requestContext.query,
      body: requestContext.body,
      ip: requestContext.ip,
      status: responseContext.status,
      responseHeaders: responseContext.headers,
      responseBody: responseContext.body,
      duration: responseContext.duration,
    });

    return result;
  } catch (error) {
    await telescope.exception(error, requestContext.id);
    throw error;
  } finally {
    await adapter.flush();
  }
};
```

#### Middy 中间软件

用于中端软件框架:

```typescript
import middy from '@middy/core';
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { telescopeMiddleware } from '@geekmidas/telescope/adapters/lambda';

const telescope = new Telescope({ storage: new InMemoryStorage() });

export const handler = middy(async (event, context) => {
  return { statusCode: 200, body: JSON.stringify({ success: true }) };
}).use(telescopeMiddleware({ telescope }));
```

### 伐木机集成

望远镜与已存在的日志库相融合,因此不需要更改应用程序代码.

#### 皮诺运输

使用 Pino 的多流向 Stdout 和望远镜发送日志 :

```typescript
import pino from 'pino';
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { createPinoDestination } from '@geekmidas/telescope/logger/pino';

const telescope = new Telescope({ storage: new InMemoryStorage() });

const logger = pino(
  { level: 'debug' },
  pino.multistream([
    { stream: process.stdout },
    { stream: createPinoDestination({ telescope }) }
  ])
);

// Logs go to both console and Telescope
logger.info({ userId: '123' }, 'User logged in');
```

#### 望远镜控制器( ConsoleLogger )

将任何 Logger 接口包起来,并将日志转发到望远镜 :

```typescript
import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
import { TelescopeLogger, createTelescopeLogger } from '@geekmidas/telescope/logger/console';
import { ConsoleLogger } from '@geekmidas/logger/console';

const telescope = new Telescope({ storage: new InMemoryStorage() });

// Option 1: Using the class
const logger = new TelescopeLogger({
  telescope,
  logger: new ConsoleLogger({ app: 'myApp' }),
});

// Option 2: Using the factory function
const logger = createTelescopeLogger(telescope, new ConsoleLogger());

// Logs go to both console and Telescope
logger.info({ action: 'startup' }, 'Application started');

// Create child loggers with context
const authLogger = logger.child({ module: 'auth' });
authLogger.debug({ userId: '123' }, 'User authenticated');

// Bind to a request ID for correlation
const requestLogger = logger.withRequestId('req-abc123');
requestLogger.info('Processing request');
```

## 发光板 API

仪表板UI在配置的路径中服务. 也揭露了一个 REST API:

| 终点 | 说明 |
| --- | --- |
| `GET /api/requests` | 名单请求 |
| `GET /api/requests/:id` | 获取请求的细节 |
| `GET /api/exceptions` | 列表例外 |
| `GET /api/exceptions/:id` | 获取例外细节 |
| `GET /api/logs` | 列表日志 |
| `GET /api/stats` | 获取存储统计 |

### 查询参数

所有列表终点支持 :

-   `limit` - 条目数(默认:50个,最大:100个)
-   `offset` - 偏移(默认:0)
-   `search` - 全文搜索
-   `before` - 日期前条目(ISO字符串)
-   `after` - 日期后条目(ISO字符串)
-   `tags` - 逗号分隔标签过滤器

示例

```
GET /__telescope/api/requests?limit=20&search=POST&after=2024-01-01
```

## 网络安全套

连接到 `/__telescope/ws` 用于实时更新 :

```typescript
const ws = new WebSocket('ws://localhost:3000/__telescope/ws');

ws.onmessage = (event) => {
  const { type, payload, timestamp } = JSON.parse(event.data);

  switch (type) {
    case 'request':
      console.log('New request:', payload);
      break;
    case 'exception':
      console.log('New exception:', payload);
      break;
    case 'log':
      console.log('New log:', payload);
      break;
    case 'connected':
      console.log('Connected, clients:', payload.clientCount);
      break;
  }
};
```

## 类型

### 请求条目

```typescript
interface RequestEntry {
  id: string;
  method: string;
  path: string;
  url: string;
  headers: Record<string, string>;
  body?: unknown;
  query?: Record<string, string>;
  status: number;
  responseHeaders: Record<string, string>;
  responseBody?: unknown;
  duration: number;
  timestamp: Date;
  ip?: string;
  userId?: string;
  tags?: string[];
}
```

### 例外条目

```typescript
interface ExceptionEntry {
  id: string;
  name: string;
  message: string;
  stack: StackFrame[];
  source?: SourceContext;
  requestId?: string;
  timestamp: Date;
  handled: boolean;
  tags?: string[];
}
```

### 日志条目

```typescript
interface LogEntry {
  id: string;
  level: 'debug' | 'info' | 'warn' | 'error';
  message: string;
  context?: Record<string, unknown>;
  requestId?: string;
  timestamp: Date;
}
```

## 与 gkm dev 合并

使用时 `gkm dev`,望远镜自动集成:

```bash
gkm dev --port 3000

# Output:
# API:        http://localhost:3000
# Telescope:  http://localhost:3000/__telescope
```

配置在 `gkm.config.ts`数字 :

```typescript
export default {
  routes: './src/endpoints/**/*.ts',
  envParser: './src/config/env',
  logger: './src/logger',

  dev: {
    telescope: {
      enabled: true,
      path: '/__telescope',
    },
  },
};
```

## 最佳做法

1.  **生产中禁用**: 使用环境变量来禁用生产中的望远镜
    
    ```typescript
    const telescope = new Telescope({
      storage: new InMemoryStorage(),
      enabled: process.env.NODE_ENV === 'development',
    });
    ```
    
2.  **忽略健康检查**: 排除吵闹的终点
    
    ```typescript
    ignorePatterns: ['/health', '/ready', '/metrics']
    ```
    
3.  **限制正文大小**: 防止具有大有效载荷的内存问题
    
    ```typescript
    maxBodySize: 32 * 1024 // 32KB
    ```
    
4.  **自动打印**: 启用长期 Dev 会话的自动清理
    
    ```typescript
    pruneAfterHours: 4
    ```
    
5.  **在 Stage 中使用数据库存储**:用于在中转环境中调试问题
    
    ```typescript
    const storage = process.env.NODE_ENV === 'production'
      ? null // Disabled
      : process.env.NODE_ENV === 'staging'
        ? new KyselyStorage(db)
        : new InMemoryStorage();
    ```
    

## 许可证

麻省理工学院

## 常见问题

### @geekmidas/telescope 是什么？

Laravel 望远镜式调试和监测网络应用程序

### 如何安装 @geekmidas/telescope？

在项目目录运行 npm install @geekmidas/telescope，或使用 pnpm add / yarn add / bun add。

### @geekmidas/telescope 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @geekmidas/telescope 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @geekmidas/telescope 可以商用吗？

@geekmidas/telescope 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @geekmidas/telescope 的下载量有多少？

根据 npm 官方下载统计，@geekmidas/telescope 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,723 次，日均约 457 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @geekmidas/telescope 还在维护吗？

最新版本 9\.6\.1 发布于 2026/11/16（今天）；至今共发布 205 个版本，其中过去 12 个月发布了 205 个；首次发布于 2025/12/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

