@geekmidas/telescope

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS构建来源已验证近 30 天下载 1.4万

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

中文使用文档
文档目录32 节
  1. 安装
  2. 快速启动
  3. 和浩诺
  4. 框架不可知核心
  5. 特征
  6. 配置
  7. 敏感数据编辑
  8. 启用编辑
  9. 默认已编辑路径
  10. 添加自定义路径
  11. 全控
  12. 路径语法
  13. 程序访问
  14. 存储后端
  15. 在记忆中
  16. 凯斯利·斯多拉奇(英语:Cysely Storage (Coming Soon))
  17. 自定义存储
  18. API 密码
  19. 望远镜类( 核心)
  20. Hono 适应器
  21. Lambda 适应器
  22. 伐木机集成
  23. 发光板 API
  24. 查询参数
  25. 网络安全套
  26. 类型
  27. 请求条目
  28. 例外条目
  29. 日志条目
  30. 与 gkm dev 合并
  31. 最佳做法
  32. 许可证

@geekmidas/望远镜

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

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

安装

pnpm add @geekmidas/telescope

快速启动

和浩诺

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 类是框架不可知的。 您可以直接用于手动录制 :

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 自动擦拭的包装和中继中间软件

配置

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。 。 。 .

启用编辑

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

添加自定义路径

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

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

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

全控

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

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任何级别的秘密领域

程序访问

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);

存储后端

在记忆中

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

// 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))

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

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

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

自定义存储

执行 TelescopeStorage 接口 :

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)

按程序记录请求条目.

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?)

程序记录日志条目 .

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

telescope.exception(error, requestId?)

在程序上记录一个例外.

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

telescope.broadcast(event)

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

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

telescope.prune(olderThan)

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

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

telescope.destroy()

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

telescope.destroy();

Hono 适应器

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

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

createMiddleware(telescope)

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

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

createUI(telescope)

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

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

setupWebSocket(app, telescope, upgradeWebSocket)

为实时更新设置 WebSocket 路由.

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

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

getRequestId(c)

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

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数字 :

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

wrapLambdaHandler(telescope, handler, options?)

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

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引用,将事件记录为请求机构.

选项

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 直接分类 :

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 中间软件

用于中端软件框架:

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 和望远镜发送日志 :

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 接口包起来,并将日志转发到望远镜 :

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 用于实时更新 :

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;
  }
};

类型

请求条目

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[];
}

例外条目

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

日志条目

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

与 gkm dev 合并

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

gkm dev --port 3000

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

配置在 gkm.config.ts数字 :

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

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

最佳做法

  1. 生产中禁用: 使用环境变量来禁用生产中的望远镜

    const telescope = new Telescope({
      storage: new InMemoryStorage(),
      enabled: process.env.NODE_ENV === 'development',
    });
    
  2. 忽略健康检查: 排除吵闹的终点

    ignorePatterns: ['/health', '/ready', '/metrics']
    
  3. 限制正文大小: 防止具有大有效载荷的内存问题

    maxBodySize: 32 * 1024 // 32KB
    
  4. 自动打印: 启用长期 Dev 会话的自动清理

    pruneAfterHours: 4
    
  5. 在 Stage 中使用数据库存储:用于在中转环境中调试问题

    const storage = process.env.NODE_ENV === 'production'
      ? null // Disabled
      : process.env.NODE_ENV === 'staging'
        ? new KyselyStorage(db)
        : new InMemoryStorage();
    

许可证

麻省理工学院

版本与发布记录

@geekmidas/telescope 共发布 205 个版本,首次发布于 2025/12/30;过去 12 个月发布了 205 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/telescope 的常见问题

@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 和提交记录判断。