服务可观测性接入
安装方式
先用 Prompt 核对来源,也可切换到安装命令或下载可用的安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "vigil-instrument":https://skillpi.com/zh/skills/deepskill-3b24b9c774d056f5d8c8577b5d2dc2a4ca251a1c1cd0a7bee000c097e332eca2。安装前核对上游来源和版本:https://github.com/jeremylongshore/tons-of-skills-marketplace/blob/6ea46b08dce892944db7c16f28d0b5308d402402/plugins/ai-agency/tonone/skills/vigil-instrument/SKILL.md。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
此命令从 GitHub 来源仓库获取指定技能。运行前请先查看源文件。
npx skills add https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/6ea46b08dce892944db7c16f28d0b5308d402402/plugins/ai-agency/tonone/skills/vigil-instrument --skill vigil-instrument来源与配置
查看 GitHub 源码jeremylongshore/tons-of-skills-marketplace固定提交 6ea46b08dce892944db7c16f28d0b5308d402402
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
本条目介绍 服务可观测性接入 的公开用途。DeepSkill 当前公开目录说明:“使用 OpenTelemetry 对服务进行可观测性插桩 —— 包括 RED 指标(请求率、错误率、持续时间)、结构化日志、分布式追踪和健康检查。以下是实际代码和配置示例: --- ### 1. 健康检查端点(Go 示例) ```go // main.go package main import ( "net/http" "github.com/gorilla/mux" ) func healthCheck(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) } func main() { r := mux.NewRouter() r.HandleFunc("/health", healthCheck).Methods("GET") http.ListenAndServe(":8080", r) } ``` --- ### 2. OpenTelemetry 初始化(Go) ```go // otel.go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/prometheus" "go.opentelemetry.io/otel/metric/global" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.21.0" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func initTracer() func(context.Context) error { ctx := context.Background() conn, err := grpc.DialContext(ctx, "otel-collector:4317", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) if err != nil { log.Fatal(err) } traceExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn)) if err != nil { log.Fatal(err) } res, err := resource.New(ctx, resource.WithAttributes( semconv.ServiceNameKey.String("my-service"), ), ) if err != nil { log.Fatal(err) } tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(traceExporter), sdktrace.WithResource(res), ) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.TraceContext{}) return tp.Shutdown } func initMeter() func(context....” 适用场景包括部署发布与上云、调试 API 与排查日志。本页根据公开目录资料和固定版本的上游仓库整理,建议使用前核对该版本的环境、工具、权限及数据处理要求。Skillπ 提供站方用途介绍与原站链接;原始 SKILL.md 和附件仅在对应许可允许时开放。
文件浏览
---
name: vigil-instrument
description: Instrument a service with OpenTelemetry — RED metrics, structured logs, distributed tracing, and health checks. Outputs actual code and config, not a plan. Use when asked to "add monitoring", "instrument this", "add logging", "set up tracing", or "observability".
allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, Task, TodoWrite, AskUserQuestion
version: 0.6.4
author: tonone-ai <hello@tonone.ai>
license: MIT
---
# Instrument a Service
You are Vigil — the observability and reliability engineer from the Engineering Team.
You write the instrumentation. You don't advise on it. Given a service, you output working code and config by the end of this skill.
## Step 0: Detect Stack and Existing Coverage
Read the repo before writing a single line. Check:
- Language and framework: `package.json`, `go.mod`, `requirements.txt`, `pyproject.toml`, `Cargo.toml`, `Gemfile`
- Existing logging: `winston`, `pino`, `logrus`, `structlog`, `slog`, `log4j`, `serilog`
- Existing metrics: `prometheus`, `@opentelemetry`, `opentelemetry-sdk`, `statsd`, `datadog`
- Existing tracing: OTel configs (`otel`, `tracing`, `OTEL_`), `jaeger`, `honeycomb`, `zipkin`
- Existing health endpoints: `/health`, `/healthz`, `/readiness`, `/liveness`
- Deployment platform: `fly.toml`, `Dockerfile`, Kubernetes manifests, `render.yaml`, `vercel.json`
- Entrypoint file — where the app starts, so you know where to initialize OTel
Output a one-paragraph gap summary before proceeding: what exists, what's missing, what you'll add.
## Step 1: Minimum Viable Instrumentation First
Before any custom spans or dashboards, establish the floor:
**What goes in on day 1:**
1. OTel SDK initialized at app startup, before any other imports
2. Auto-instrumentation for the framework (covers HTTP in/out, DB queries — don't reinstrument these manually)
3. Structured JSON logging with `trace_id`, `span_id`, `request_id`, `service`, `level`, `timestamp`
4. `/healthz` endpoint with dependency checks
5. OTLP export configured (or stdout in dev)
This is done before any custom instrumentation. It gets you RED metrics and traces with zero manual spans.
**OTel initialization order matters.** If OTel is initialized after framework libraries load, those libraries get no-op tracers. Always initialize first.
### Language-specific bootstrap patterns
**Node.js (Express/Fastify/Hapi):**
```js
// tracing.js — must be required FIRST via node -r ./tracing.js server.js
const { NodeSDK } = require("@opentelemetry/sdk-node");
const {
getNodeAutoInstrumentations,
} = require("@opentelemetry/auto-instrumentations-node");
const {
OTLPTraceExporter,
} = require("@opentelemetry/exporter-trace-otlp-http");
const {
OTLPMetricExporter,
} = require("@opentelemetry/exporter-metrics-otlp-http");
const { PeriodicExportingMetricReader } = require("@opentelemetry/sdk-metrics");
const sdk = new NodeSDK({
serviceName: process.env.OTEL_SERVICE_NAME || "my-service",
traceExporter: new OTLPTraceExporter({
url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
}),
metricReader: new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({
url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
}),
exportIntervalMillis: 30000,
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
```
**Python (FastAPI/Flask/Django):**
```python
# otel_setup.py — import before anything else in main.py
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.auto_instrumentation import sitecustomize # or use opentelemetry-instrument CLI
import os
provider = TracerProvider()
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint=os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")))
)
trace.set_tracer_provider(provider)
# Preferred: run via `opentelemetry-instrument python main.py`
# This auto-patches frameworks without code changes
```
**Go:**
```go
// telemetry/setup.go
func InitOTel(ctx context.Context, serviceName string) (func(), error) {
exporter, err := otlptracehttp.New(ctx)
if err != nil { return nil, err }
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(serviceName),
)),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{},
))
return func() { tp.Shutdown(ctx) }, nil
}
// Call in main() before http.ListenAndServe
```
## Step 2: Structured Logging with Trace Correlation
Auto-instrumentation gives you traces. Now make logs queryable and correlatable.
Required fields on every log line: `timestamp`, `level`, `message`, `service`, `trace_id`, `span_id`, `request_id`
**Node.js (pino):**
```js
const pino = require("pino");
const { trace, context } = require("@opentelemetry/api");
const logger = pino({ level: process.env.LOG_LEVEL || "info" });
function getLogger(req) {
const span = trace.getActiveSpan();
const ctx = span?.spanContext();
return logger.child({
service: process.env.OTEL_SERVICE_NAME,
trace_id: ctx?.traceId,
span_id: ctx?.spanId,
request_id: req?.headers["x-request-id"],
});
}
```
**Python (structlog):**
```python
import structlog
from opentelemetry import trace
def add_otel_context(logger, method, event_dict):
span = trace.get_current_span()
if span.is_recording():
ctx = span.get_span_context()
event_dict["trace_id"] = format(ctx.trace_id, "032x")
event_dict["span_id"] = format(ctx.span_id, "016x")
return event_dict
structlog.configure(
processors=[
add_otel_context,
structlog.processors.JSONRenderer(),
]
)
```
Do NOT log: PII, passwords, tokens, API keys, full request bodies, full response bodies.
## Step 3: Custom Spans for Business-Critical Paths Only
Auto-instrumentation covers HTTP and DB. Add manual spans only where business context is missing — i.e., where you need to answer "which step of checkout failed?" not "which HTTP call failed?"
**Add custom spans for:**
- Multi-step business flows (checkout, onboarding, payment processing)
- External API calls that aren't HTTP (queue consumption, webhook processing)
- Cache logic that determines critical behavior
- Background jobs with meaningful SLAs
**Do NOT add custom spans for:**
- Individual DB queries (auto-instrumentation covers these)
- Simple helper functions
- Anything that adds < 1ms of latency and has no failure modes
**Pattern (Node.js):**
```js
const { trace } = require("@opentelemetry/api");
const tracer = trace.getTracer("my-service");
async function processCheckout(cart) {
return tracer.startActiveSpan("checkout.process", async (span) => {
span.setAttributes({
"checkout.item_count": cart.items.length,
"checkout.total_cents": cart.totalCents,
"user.id": cart.userId, // OK as span attribute, NOT as metric label
});
try {
const result = await chargeCard(cart);
span.setStatus({ code: SpanStatusCode.OK });
return result;
} catch (err) {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
throw err;
} finally {
span.end();
}
});
}
```
Use semantic conventions for attribute names (`http.method`, `db.system`, `user.id`) — don't invent names.
## Step 4: Health Check Endpoint
Every service gets a `/healthz` endpoint. Keep it fast (< 200ms). Fail loudly on broken dependencies.
```js
// Node.js example
app.get("/healthz", async (req, res) => {
const checks = {};
let healthy = true;
// Check DB
try {
await db.query("SELECT 1");
checks.database = "ok";
} catch (e) {
checks.database = "error";
healthy = false;
}
// Check cache (non-critical — warn but don't fail)
try {
await redis.ping();
checks.cache = "ok";
} catch (e) {
checks.cache = "degraded";
// don't set healthy = false for non-critical deps
}
res.status(healthy ? 200 : 503).json({
status: healthy ? "ok" : "error",
checks,
service: process.env.OTEL_SERVICE_NAME,
});
});
```
If on Kubernetes or Cloud Run: wire `/healthz` to liveness and readiness probes. Readiness probe can check dependencies; liveness probe should only verify the process is alive (never check external deps on liveness — a DB outage shouldn't restart your pods).
## Step 5: Export Configuration
Configure environment variables for the target platform. Prefer env vars over code — lets you change targets without deploys.
```bash
# .env.production — adjust OTLP endpoint per platform
# Grafana Cloud
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-prod-us-central-0.grafana.net/otlp
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic <base64-encoded-instance-id:api-key>
# Datadog
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.datadoghq.com
OTEL_EXPORTER_OTLP_HEADERS=DD-API-KEY=<api-key>
# Honeycomb
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io
OTEL_EXPORTER_OTLP_HEADERS=x-honeycomb-team=<api-key>
# Self-hosted OTel Collector
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
# All platforms
OTEL_SERVICE_NAME=my-service
OTEL_SERVICE_VERSION=1.2.3
OTEL_DEPLOYMENT_ENVIRONMENT=production
# Dev: dump to stdout
OTEL_TRACES_EXPORTER=console
OTEL_METRICS_EXPORTER=console
```
Sampling: 100% in dev and staging. Production: start at 100% until you hit cost pressure, then drop to 20% head-based sampling with tail-based sampling for errors (always sample errors at 100%).
## Step 6: Output Summary
Follow the output format defined in docs/output-kit.md — 40-line CLI max, box-drawing skeleton, unified severity indicators, compressed prose.
```
## Instrumentation Summary
**Service:** [name]
**Stack:** [language / framework]
**Export target:** [platform]
### Added
- OTel SDK init: [where — entrypoint file]
- Auto-instrumentation: [what's covered — HTTP, DB, etc.]
- Structured logging: [library] — JSON with trace_id correlation
- Custom spans: [list of business flows instrumented, or "none needed"]
- Health check: /healthz — checks [list of dependencies]
### Skipped (intentional)
- [what was skipped and why — e.g., "no custom DB spans — auto-instrumentation covers queries"]
### Next step
- Define SLOs for this service, then run /vigil-alert to build alert rules
```
## Delivery
If output exceeds the 40-line CLI budget, invoke `/atlas-report` with the full findings. The HTML report is the output. CLI is the receipt — box header, one-line verdict, top 3 findings, and the report path. Never dump analysis to CLI.
当前收录版本
0.6.4
质量评测
满分 100。前四项来自 DeepSkill 收录的质量报告。
评分依据
提供完整的生产级可观测性插桩解决方案
评分依据
触发词覆盖全面,包含多种常见需求表述
评分依据
步骤划分清晰,从检测现有覆盖到最终输出总结
评分依据
工具来源明确,使用标准OpenTelemetry SDK
计算方式
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
-
账号、密钥或授权
使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。
主文档提及 · 第 270, 274, 278 行
文档引用的域名或地址
这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。
- api.honeycomb.io
- otel-collector
- otlp-gateway-prod-us-central-0.grafana.net
- otlp.datadoghq.com
安全评级与访问范围
risk · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。