observability-knowledge

可观测性知识库:覆盖三大支柱(日志、指标、追踪)、结构化日志实践、分布式追踪方法、指标收集(RED/USE)思路,以及可观测性审计与制定 SLI/SLO/SLA 所需的信息。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

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

用 AI 助手安装

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

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

来源与配置

github.com

配置方式待核实

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

安装实测待补充

可观测性知识库:覆盖三大支柱(日志、指标、追踪)、结构化日志实践、分布式追踪方法、指标收集(RED/USE)思路,以及可观测性审计与制定 SLI/SLO/SLA 所需的信息。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: observability-knowledge
description: Observability knowledge base. Provides three pillars (logs, metrics, traces), structured logging, distributed tracing, metrics collection (RED/USE), SLI/SLO/SLA definitions for observability audits and generation.

Observability Knowledge Base

Quick reference for the three pillars of observability, instrumentation patterns, and SLI/SLO/SLA definitions in PHP applications.

Three Pillars Overview

┌─────────────────────────────────────────────────────────────────────────────┐
│                      THREE PILLARS OF OBSERVABILITY                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐          │
│   │      LOGS        │  │     METRICS      │  │     TRACES       │          │
│   │                  │  │                  │  │                  │          │
│   │  What happened   │  │  How much/many   │  │  How requests    │          │
│   │  (discrete       │  │  (aggregated     │  │  flow through    │          │
│   │   events)        │  │   measurements)  │  │  services)       │          │
│   │                  │  │                  │  │                  │          │
│   │  • Errors        │  │  • Counters      │  │  • Spans         │          │
│   │  • Audit trail   │  │  • Gauges        │  │  • Context       │          │
│   │  • Debug info    │  │  • Histograms    │  │  • Latency       │          │
│   │                  │  │                  │  │                  │          │
│   │  JSON structured │  │  Prometheus      │  │  OpenTelemetry   │          │
│   │  Monolog         │  │  StatsD          │  │  Jaeger/Zipkin   │          │
│   └────────┬─────────┘  └────────┬─────────┘  └────────┬─────────┘          │
│            │                     │                      │                    │
│            └─────────────────────┼──────────────────────┘                    │
│                                  │                                           │
│                        ┌─────────▼─────────┐                                │
│                        │  CORRELATION ID   │                                │
│                        │  (links all three │                                │
│                        │   pillars)        │                                │
│                        └───────────────────┘                                │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Structured Logging

JSON Log Format

Field Type Description Required
timestamp ISO 8601 When event occurred Yes
level string RFC 5424 log level Yes
message string Human-readable description Yes
channel string Logger channel name Yes
context object Structured event data No
correlation_id string Request/trace identifier Yes
service string Service/app name Yes
environment string prod/staging/dev Yes

Log Levels (RFC 5424)

Level Code When to Use
EMERGENCY 0 System is unusable
ALERT 1 Immediate action required
CRITICAL 2 Critical conditions (component failure)
ERROR 3 Runtime errors (not requiring immediate action)
WARNING 4 Exceptional but handled conditions
NOTICE 5 Normal but significant events
INFO 6 Informational messages (request processed)
DEBUG 7 Detailed debug information

Monolog Context Processor

<?php

declare(strict_types=1);

namespace Infrastructure\Logging;

use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;

final readonly class CorrelationIdProcessor implements ProcessorInterface
{
    public function __construct(
        private CorrelationIdHolder $holder,
    ) {}

    public function __invoke(LogRecord $record): LogRecord
    {
        return $record->with(
            extra: array_merge($record->extra, [
                'correlation_id' => $this->holder->get(),
                'service' => $_ENV['APP_SERVICE_NAME'] ?? 'unknown',
                'environment' => $_ENV['APP_ENV'] ?? 'unknown',
            ]),
        );
    }
}

Correlation ID Holder

<?php

declare(strict_types=1);

namespace Infrastructure\Logging;

final class CorrelationIdHolder
{
    private ?string $correlationId = null;

    public function set(string $correlationId): void
    {
        $this->correlationId = $correlationId;
    }

    public function get(): string
    {
        if ($this->correlationId === null) {
            $this->correlationId = uuid_create(UUID_TYPE_RANDOM);
        }

        return $this->correlationId;
    }
}

Distributed Tracing

OpenTelemetry Concepts

Concept Description
Trace End-to-end journey of a request across services
Span Single unit of work within a trace (has start/end time)
SpanContext Trace ID + Span ID + flags, propagated across boundaries
Attributes Key-value metadata on spans
Events Timestamped annotations within a span
Links Connections between spans in different traces
Baggage Cross-cutting key-value pairs propagated with context

W3C Trace Context Header

traceparent: {version}-{trace-id}-{parent-id}-{trace-flags}
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01

tracestate: vendor1=value1,vendor2=value2
Part Length Description
version 2 hex Always 00
trace-id 32 hex Globally unique trace identifier
parent-id 16 hex ID of parent span
trace-flags 2 hex 01 = sampled

OpenTelemetry PHP SDK Setup

<?php

declare(strict_types=1);

namespace Infrastructure\Telemetry;

use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;

final readonly class TracingService
{
    private TracerInterface $tracer;

    public function __construct(string $serviceName = 'my-app')
    {
        $this->tracer = Globals::tracerProvider()->getTracer($serviceName);
    }

    public function traceOperation(string $operationName, callable $operation, array $attributes = []): mixed
    {
        $span = $this->tracer
            ->spanBuilder($operationName)
            ->setSpanKind(SpanKind::KIND_INTERNAL)
            ->startSpan();

        $scope = $span->activate();

        try {
            foreach ($attributes as $key => $value) {
                $span->setAttribute($key, $value);
            }

            $result = $operation();
            $span->setStatus(StatusCode::STATUS_OK);

            return $result;
        } catch (\Throwable $e) {
            $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
            $span->recordException($e);

            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }

    public function traceHttpClient(string $method, string $url, callable $request): mixed
    {
        $span = $this->tracer
            ->spanBuilder(sprintf('%s %s', $method, $url))
            ->setSpanKind(SpanKind::KIND_CLIENT)
            ->setAttribute('http.method', $method)
            ->setAttribute('http.url', $url)
            ->startSpan();

        $scope = $span->activate();

        try {
            $result = $request();
            $span->setStatus(StatusCode::STATUS_OK);

            return $result;
        } catch (\Throwable $e) {
            $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());

            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }
}

Metrics

RED Method (Request-Driven Services)

Metric What Unit Example
Rate Requests per second req/s HTTP requests per second by endpoint
Errors Failed requests per second err/s 5xx responses per second
Duration Latency distribution ms Response time p50, p95, p99

USE Method (Resource-Oriented)

Metric What Example
Utilization % time resource is busy CPU usage, disk I/O
Saturation Queued work Request queue length
Errors Error count Disk errors, connection failures

Golden Signals (Google SRE)

Signal Description RED Equivalent
Latency Time to service a request Duration
Traffic Demand on the system Rate
Errors Rate of failed requests Errors
Saturation How full the system is (USE method)

Prometheus PHP Client

<?php

declare(strict_types=1);

namespace Infrastructure\Metrics;

use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
use Prometheus\Storage\Redis;

final class PrometheusMetricsCollector
{
    private readonly CollectorRegistry $registry;

    public function __construct(\Redis $redis)
    {
        $adapter = Redis::fromExistingConnection($redis);
        $this->registry = new CollectorRegistry($adapter);
    }

    public function incrementRequestCount(string $method, string $route, int $statusCode): void
    {
        $counter = $this->registry->getOrRegisterCounter(
            'app',
            'http_requests_total',
            'Total HTTP requests',
            ['method', 'route', 'status_code'],
        );

        $counter->inc([$method, $route, (string) $statusCode]);
    }

    public function observeRequestDuration(string $method, string $route, float $durationSeconds): void
    {
        $histogram = $this->registry->getOrRegisterHistogram(
            'app',
            'http_request_duration_seconds',
            'HTTP request duration in seconds',
            ['method', 'route'],
            [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
        );

        $histogram->observe($durationSeconds, [$method, $route]);
    }

    public function setActiveConnections(int $count): void
    {
        $gauge = $this->registry->getOrRegisterGauge(
            'app',
            'active_connections',
            'Current active connections',
            [],
        );

        $gauge->set($count, []);
    }

    public function renderMetrics(): string
    {
        $renderer = new RenderTextFormat();

        return $renderer->render($this->registry->getMetricFamilySamples());
    }
}

SLI / SLO / SLA

Concept Definition Example
SLI (Service Level Indicator) Measurable metric of service behavior Request latency p99 < 200ms
SLO (Service Level Objective) Target value for an SLI 99.9% of requests within 200ms
SLA (Service Level Agreement) Contract with consequences 99.5% uptime or credit issued

Common SLIs

SLI Type Formula Target (SLO)
Availability successful_requests / total_requests 99.9% (three nines)
Latency requests < threshold / total_requests 99% < 200ms, 99.9% < 1s
Error Rate error_requests / total_requests < 0.1%
Throughput requests / time_window > 1000 req/s
Freshness time_since_last_update < 5 minutes

Error Budget

Error Budget = 1 - SLO

Example: SLO = 99.9%
Error Budget = 0.1% = ~43 minutes/month downtime allowed

Budget remaining = Error Budget - Actual Errors
If budget exhausted → freeze deployments, focus on reliability

Quick Reference Tables

Observability Tool Selection

Need Tool/Library PHP Integration
Structured logging Monolog monolog/monolog
Log aggregation ELK Stack, Loki Monolog handlers
Metrics collection Prometheus promphp/prometheus_client_php
Metrics visualization Grafana Prometheus data source
Distributed tracing Jaeger, Zipkin OpenTelemetry PHP SDK
APM Datadog, New Relic PHP extensions/agents
Error tracking Sentry sentry/sentry-php
Health checks Custom endpoint PSR-15 middleware

Alerting Thresholds

Alert Condition Severity
High error rate > 1% of requests 5xx Critical
High latency p99 > 2s for 5 min Warning
Service down Health check fails 3x Critical
Disk usage > 85% used Warning
Queue backlog > 10k unprocessed Warning
Memory usage > 90% for 10 min Critical

Common Violations Quick Reference

Violation Where to Look Severity
No structured logging (plain text) Logger config, log output Warning
Missing correlation IDs Middleware, log processors Critical
No metrics endpoint Routes, health controllers Warning
Untraced external calls HTTP clients, adapters Warning
Swallowed exceptions without logging Catch blocks Critical
No health check endpoint Routes, controllers Warning
Missing request/response logging Middleware Warning
No alerting rules defined Monitoring config Warning

Detection Patterns

# Logging setup
Grep: "Monolog|LoggerInterface|PsrLogLoggerInterface" --glob "**/*.php"
Grep: "monolog" --glob "**/composer.json"
Grep: "structured|json_formatter|JsonFormatter" --glob "**/*.php"

# Correlation IDs
Grep: "correlation.id|correlationId|X-Correlation-ID|X-Request-ID" --glob "**/*.php"

# Metrics
Grep: "Prometheus|CollectorRegistry|Counter|Histogram|Gauge" --glob "**/*.php"
Grep: "prometheus|promphp" --glob "**/composer.json"
Grep: "/metrics|metricsEndpoint" --glob "**/*.php"

# Tracing
Grep: "OpenTelemetry|Tracer|Span|SpanBuilder" --glob "**/*.php"
Grep: "open-telemetry|opentelemetry" --glob "**/composer.json"
Grep: "traceparent|tracestate|W3C" --glob "**/*.php"

# Health checks
Grep: "health|healthcheck|readiness|liveness" --glob "**/*.php"
Grep: "/health|/ready|/live" --glob "**/routes*.php"

# Error tracking
Grep: "Sentry|sentry|Bugsnag|Rollbar" --glob "**/*.php"
Grep: "sentry/sentry" --glob "**/composer.json"

# Log levels and context
Grep: "->error\(|->critical\(|->warning\(|->info\(" --glob "**/*.php"
Grep: "LogLevel::" --glob "**/*.php"

References

For detailed information, load these reference files:

  • references/logging-patterns.md — Structured logging, Monolog setup, context processors, log aggregation patterns
  • references/metrics-patterns.md — Counter/Gauge/Histogram types, Prometheus PHP client, RED metrics, alerting rules
  • references/tracing-patterns.md — OpenTelemetry PHP SDK, span creation, context propagation, sampling strategies

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

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

场景价值78/100

亮点

  • 提供可观测性三大支柱的完整知识体系,涵盖日志、指标、追踪的核心概念与 PHP 实现
  • 包含 SLI/SLO/SLA 定义及错误预算计算,适用于 SRE 和系统审计场景
  • 提供工具选型表和检测模式,具备实际工程指导价值
触发精准72/100

待提升项

  • 缺少显式触发词列表 原报告严重程度:轻微

    description 描述了功能范围,但未提供明确的触发关键词列表,可能影响边缘场景的触发准确性。

    改进建议:在 frontmatter 或文档开头添加 triggers 字段,列出如 'observability', 'logging', 'metrics', 'tracing', 'SLI', 'SLO' 等关键词。

亮点

  • description 清晰覆盖核心功能边界,自然语言触发词完整
结构规范75/100

待提升项

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

    文档未明确说明适用场景和使用时机,用户可能难以判断何时调用此 Skill。

    改进建议:在开头添加 'When to Use' 章节,说明适用于系统审计、监控方案设计、故障排查等场景。

  • 缺少端到端完整示例 原报告严重程度:轻微

    虽有代码片段,但缺乏一个完整的端到端示例展示如何集成三大支柱。

    改进建议:添加一个完整的 PHP 应用示例,展示从请求入口到日志、指标、追踪的完整链路。

亮点

  • 文档结构清晰,分章节合理,包含大量实用表格和代码示例
  • frontmatter 完整,单文件长度适中,符合规范
执行可靠70/100

待提升项

  • 异常处理覆盖不足 原报告严重程度:轻微

    代码示例中未处理关键依赖失败情况(如 Redis 连接失败、TracerProvider 未初始化)。

    改进建议:在 PrometheusMetricsCollector 和 TracingService 中添加依赖检查和异常处理逻辑。

亮点

  • 工具来源明确(Monolog、OpenTelemetry、Prometheus),参数使用正确
  • 代码语法规范,符合 PHP 最佳实践
证据可验 (前四项均值)74/100

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

正文静态检测

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

正文未命中当前规则。

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

权限与使用前检查

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

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

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

安全评级与访问范围

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

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