@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-keyresponseHeaders.set-cookie
请求/答复机构:
body.password, (中文(简体) ),body.token, (中文(简体) ),body.accessToken, (中文(简体) ),body.refreshTokenbody.apiKey, (中文(简体) ),body.secret, (中文(简体) ),body.creditCard, (中文(简体) ),body.cardNumber, (中文(简体) ),body.cvv, (中文(简体) ),body.ssnbody.*.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',
},
},
};
最佳做法
-
生产中禁用: 使用环境变量来禁用生产中的望远镜
const telescope = new Telescope({ storage: new InMemoryStorage(), enabled: process.env.NODE_ENV === 'development', }); -
忽略健康检查: 排除吵闹的终点
ignorePatterns: ['/health', '/ready', '/metrics'] -
限制正文大小: 防止具有大有效载荷的内存问题
maxBodySize: 32 * 1024 // 32KB -
自动打印: 启用长期 Dev 会话的自动清理
pruneAfterHours: 4 -
在 Stage 中使用数据库存储:用于在中转环境中调试问题
const storage = process.env.NODE_ENV === 'production' ? null // Disabled : process.env.NODE_ENV === 'staging' ? new KyselyStorage(db) : new InMemoryStorage();
许可证
麻省理工学院