observability-setup

为微服务设置端到端可观测性:用于“添加追踪”、“设置监控”、“配置 OpenTelemetry”、“构建 Grafana 仪表板”、“分布式追踪”、“结构化日志记录”、“指标收集”或“调试生产问题”等场景。涵盖 OpenTelemetry 插桩、收集器配置、Grafana LGTM 堆栈部署、仪表板配置以及告警规则设置。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "observability-setup":https://skillpi.com/zh/skills/deepskill-390849435b2842bd3869668d686580f2888bba2d45d919b2eb5bc9eb718f33f7。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为微服务设置端到端可观测性:用于“添加追踪”、“设置监控”、“配置 OpenTelemetry”、“构建 Grafana 仪表板”、“分布式追踪”、“结构化日志记录”、“指标收集”或“调试生产问题”等场景。涵盖 OpenTelemetry 插桩、收集器配置、Grafana LGTM 堆栈部署、仪表板配置以及告警规则设置。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: observability-setup
description: >-
  Set up end-to-end observability for microservices. Use when someone asks to
  "add tracing", "set up monitoring", "configure OpenTelemetry", "build Grafana
  dashboards", "distributed tracing", "structured logging", "metrics collection",
  or "debug production issues". Covers OpenTelemetry instrumentation, collector
  configuration, Grafana LGTM stack deployment, dashboard provisioning, and
  alert rules.
license: Apache-2.0
compatibility: "Node.js 18+, Python 3.9+, Go 1.21+. Grafana LGTM stack via Docker."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: devops
  tags: ["observability", "opentelemetry", "grafana", "tracing", "monitoring"]

Observability Setup

Overview

This skill helps AI agents implement the three pillars of observability — traces, metrics, and structured logs — across microservice architectures. It uses OpenTelemetry as the instrumentation standard and Grafana's LGTM stack (Loki, Grafana, Tempo, Mimir) as the backend, though patterns apply to any OTel-compatible backend.

Instructions

OpenTelemetry Instrumentation (Node.js)

  1. Install packages:

    npm install @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node \
      @opentelemetry/exporter-trace-otlp-http @opentelemetry/exporter-metrics-otlp-http
  2. Create src/instrumentation.ts — this file must be loaded BEFORE any other imports:

    import { NodeSDK } from '@opentelemetry/sdk-node';
    import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
    import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
    import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
    import { PeriodicExportingMetricReader } from '@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 + '/v1/traces' }),
      metricReader: new PeriodicExportingMetricReader({
        exporter: new OTLPMetricExporter({ url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT + '/v1/metrics' }),
        exportIntervalMillis: 15000,
      }),
      instrumentations: [getNodeAutoInstrumentations()],
    });
    sdk.start();
  3. Add to start script: node --require ./src/instrumentation.ts src/index.ts

  4. Add custom spans for business-critical operations:

    import { trace } from '@opentelemetry/api';
    const tracer = trace.getTracer('payment-service');
    
    async function processPayment(order) {
      return tracer.startActiveSpan('process-payment', async (span) => {
        span.setAttribute('order.id', order.id);
        span.setAttribute('payment.amount_cents', order.totalCents);
        try {
          const result = await paymentGateway.charge(order);
          span.setAttribute('payment.status', result.status);
          return result;
        } catch (error) {
          span.recordException(error);
          span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
          throw error;
        } finally {
          span.end();
        }
      });
    }

OpenTelemetry Instrumentation (Python)

  1. Install: pip install opentelemetry-distro opentelemetry-exporter-otlp

  2. Run: opentelemetry-instrument --service_name notification-service python app.py

  3. For structured logs with trace context:

    import structlog
    from opentelemetry import trace
    
    def add_trace_context(logger, method_name, event_dict):
        span = trace.get_current_span()
        ctx = span.get_span_context()
        if ctx.is_valid:
            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_trace_context, structlog.dev.ConsoleRenderer()])

Structured Logging with Trace Correlation

Every log line must include trace_id and span_id. Use JSON format:

{"level":"error","msg":"payment failed","trace_id":"abc123...","span_id":"def456...","service":"payment-service","error":"timeout","timestamp":"2025-01-15T10:30:00Z"}

For Node.js, use pino with a custom mixin:

const pino = require('pino');
const { trace } = require('@opentelemetry/api');

const logger = pino({
  mixin() {
    const span = trace.getActiveSpan();
    if (span) {
      const ctx = span.spanContext();
      return { trace_id: ctx.traceId, span_id: ctx.spanId };
    }
    return {};
  }
});

OTel Collector Configuration

receivers:
  otlp:
    protocols:
      grpc: { endpoint: "0.0.0.0:4317" }
      http: { endpoint: "0.0.0.0:4318" }

processors:
  batch:
    timeout: 5s
    send_batch_size: 1000
  memory_limiter:
    limit_mib: 512

exporters:
  otlphttp/tempo:
    endpoint: http://tempo:4318
  prometheusremotewrite:
    endpoint: http://mimir:9009/api/v1/push
  loki:
    endpoint: http://loki:3100/loki/api/v1/push

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [otlphttp/tempo]
    metrics:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [prometheusremotewrite]
    logs:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [loki]

Grafana Dashboard Provisioning

Create dashboards as JSON files in grafana/dashboards/. Key panels:

Service Overview Dashboard:

  • Request rate: sum(rate(http_server_request_duration_seconds_count[5m])) by (service_name)
  • P95 latency: histogram_quantile(0.95, sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le, service_name))
  • Error rate: sum(rate(http_server_request_duration_seconds_count{http_status_code=~"5.."}[5m])) / sum(rate(http_server_request_duration_seconds_count[5m]))

Alert Rules:

  • Error rate > 5 % for 5 min → P2
  • P99 latency > 2s for 5 min → P3
  • Service health check failing for 1 min → P1

Signal Correlation in Grafana

  1. Loki data source: add derived field with regex trace_id=(\w+) linking to Tempo.
  2. Tempo data source: enable "Trace to logs" linking to Loki with filter {service_name="$service"} | trace_id="$traceId".
  3. Metrics → Logs: use exemplars in Mimir to link metric data points to trace IDs.

Examples

Example 1 — Quick OTel setup for Express app

Input: "Add observability to my Express API."

Output: Create src/instrumentation.ts with the Node SDK config above, add the --require flag to the start script, set OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 and OTEL_SERVICE_NAME=api-gateway in .env.

Example 2 — Docker Compose for LGTM stack

Input: "Give me a docker-compose for the observability backend."

Output:

services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib:0.96.0
    volumes: ["./otel-collector-config.yaml:/etc/otelcol/config.yaml"]
    ports: ["4317:4317", "4318:4318"]
  tempo:
    image: grafana/tempo:2.4.0
    command: ["-config.file=/etc/tempo.yaml"]
    volumes: ["./tempo.yaml:/etc/tempo.yaml"]
  loki:
    image: grafana/loki:3.0.0
    ports: ["3100:3100"]
  mimir:
    image: grafana/mimir:2.11.0
    command: ["-config.file=/etc/mimir.yaml"]
    volumes: ["./mimir.yaml:/etc/mimir.yaml"]
  grafana:
    image: grafana/grafana:10.4.0
    ports: ["3000:3000"]
    volumes: ["./grafana/provisioning:/etc/grafana/provisioning", "./grafana/dashboards:/var/lib/grafana/dashboards"]
    environment:
      GF_AUTH_ANONYMOUS_ENABLED: "true"
      GF_AUTH_ANONYMOUS_ORG_ROLE: Admin

Guidelines

  • Instrument before you optimize. You cannot improve what you cannot see.
  • Auto-instrumentation first, custom spans second. Auto-instrumentation covers 80 % of what you need. Add custom spans only for business-critical paths.
  • Always correlate signals. A trace without logs is incomplete. A metric spike without a trace is unactionable.
  • Set resource limits on the collector. Without memory_limiter, a traffic spike can OOM the collector and create a cascading failure.
  • Use service.name consistently. It is the primary grouping key across all three signal types. Mismatched names break correlation.

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供完整的微服务可观测性端到端解决方案
  • 覆盖 OpenTelemetry 插桩、LGTM 栈部署、告警规则等核心场景
  • 适用于生产环境监控与调试高频需求
触发精准95/100

亮点

  • 触发词覆盖全面,包括 tracing、monitoring、OpenTelemetry 等关键术语
  • 边界清晰,无歧义或重叠风险
结构规范90/100

待提升项

  • description 内容重复 原报告严重程度:轻微

    frontmatter 和 skill_body 开头均包含 description 字段,存在冗余

    改进建议:保留一处即可,建议移除 skill_body 开头的重复 description

亮点

  • 文档结构清晰,分步骤指导完整
  • 包含具体代码示例和 Docker Compose 配置
  • frontmatter 元数据完整规范
执行可靠88/100

待提升项

  • 缺少显式 'When to Use' 章节 原报告严重程度:轻微

    内容已涵盖使用场景但未使用标准章节标题

    改进建议:建议添加显式的 'When to Use' 章节以提升可读性

亮点

  • 工具链来源明确(OpenTelemetry、Grafana 官方镜像)
  • 配置参数合理,包含内存限制等防护机制
  • 提供完整的 Docker Compose 部署示例
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 安装或获取外部依赖

    使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。

    主文档提及 · 第 31, 83 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • localhost
  • loki
  • mimir
  • tempo

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。