agentleFS
SwastikPandey1024SwastikPandey1024/agentic-engineering-os/.agents/skills/observability/SKILL.md

observability

Skill1 starsChanged 3 months agoMITView on GitHub

OpenTelemetry instrumentation, structured JSON logging, correlation IDs, Prometheus metrics, and specialized AI/LLM system telemetry.

87 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use gitops, background-jobs and 9 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • kcns008Skill

    gitops

    GitOps Agent (Flow) — manages ArgoCD applications, Helm charts, Kustomize overlays, deployment strategies (canary, blue-green, rolling), multi-cluster GitOps, and drift detection for Kubernetes and OpenShift clusters.

    Also in 4 projects that use this

  • YepAPISkill

    background-jobs

    Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

    Also in 4 projects that use this

  • Mushfiqur-Rahman-RobinSkill

    rag-systems

    Best practices for building Retrieval-Augmented Generation systems — chunking, embedding, hybrid retrieval, reranking, indexing, caching, evaluation, observability — plus a catalog of RAG patterns and when each applies.

    Also in 3 projects that use this

  • YepAPISkill

    data-pipelines

    ETL patterns, cron scheduling, queue-based processing, and batch jobs with Inngest/BullMQ.

    Also in 4 projects that use this

  • wpankSkill

    caching

    Caching strategies, invalidation, eviction policies, HTTP caching, distributed caching, and anti-patterns. Use when designing cache layers, choosing eviction policies, debugging stale data, or optimizing read-heavy workloads.

    Also in 5 projects that use this

  • MicrosoftSkill

    data-modeling

    Use when the app needs to store or read data — records, a database, entities, CRUD, lists, "save/remember X", or per-user data with row-level security. This app's data layer is Rayfin's: you declare entities as TypeScript classes with decorators in rayfin/data/, register them in the schema, and read/write them through the typed rayfin-client. Covers: defining an @entity, field decorators, registering it, per-entity access with @role, owner-only row-level security, and the client query/mutation API. Triggers: data, database, model, entity, schema, table, record, CRUD, create, read, update, delete, list, store, save, persist, per-user, row-level security, RLS, access control, ownership.

    Also in 6 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 70 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill when:

    line 10
  2. Distinctive:

    Data Privacy Guardrails: Ensure NO secrets, tokens, PII (Personally Identifiable Information), or raw passwords can be written to logs.

    line 23

“Common” is measured: kept by at least 6 in 10 of the 70 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Observability Skill

1. When Should I Use This?

Use this skill when:

  • Adding structured JSON logging, correlation IDs (X-Request-ID), or distributed tracing to APIs and background services.
  • Integrating OpenTelemetry (OTel) metrics, traces, and span instrumentation.
  • Tracking AI / LLM pipeline performance: prompt tokens, completion tokens, latency, retrieval count, cache hits/misses, tool calls, and model errors.
  • Setting up health probes (/health, /ready), Prometheus metrics endpoints (/metrics), and error tracking.

2. What Should I Inspect First?

  1. Service Framework: FastAPI, Flask, Express/Node, or background worker.
  2. Current Logging Setup: Inspect logging.basicConfig or custom logger modules.
  3. Telemetry Target: Console JSON stdout, Prometheus exporter, OpenTelemetry Collector, Sentry, or Datadog.
  4. Data Privacy Guardrails: Ensure NO secrets, tokens, PII (Personally Identifiable Information), or raw passwords can be written to logs.

3. What Workflow Should I Follow?

Install OpenTelemetry / Structured Logging Tooling
                     ↓
Configure JSON Formatter with Correlation / Request ID Middleware
                     ↓
Instrument HTTP & Database Spans (FastAPI, SQLAlchemy, HTTPX)
                     ↓
Implement AI / LLM Telemetry Wrapper (Tokens, Latency, Retrieval Count)
                     ↓
Expose /metrics (Prometheus) & /health Endpoints
                     ↓
Verify with Synthetic Load & Log Inspection

Structured JSON Logging & Request ID Middleware (FastAPI)

# app/core/logging.py
import json
import logging
import time
import uuid
from contextvars import ContextVar
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware

request_id_ctx: ContextVar[str] = ContextVar("request_id", default="system")

class JSONFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        log_entry = {
            "timestamp": self.formatTime(record),
            "level": record.levelname,
            "request_id": request_id_ctx.get(),
            "logger": record.name,
            "message": record.getMessage(),
        }
        if record.exc_info:
            log_entry["exception"] = self.formatException(record.exc_info)
        return json.dumps(log_entry)

def setup_logging():
    handler = logging.StreamHandler()
    handler.setFormatter(JSONFormatter())
    logging.root.handlers = [handler]
    logging.root.setLevel(logging.INFO)

class RequestIDMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        req_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
        token = request_id_ctx.set(req_id)
        start_time = time.perf_counter()
        
        response: Response = await call_next(request)
        duration_ms = (time.perf_counter() - start_time) * 1000
        
        response.headers["X-Request-ID"] = req_id
        logging.getLogger("api.access").info(
            f"{request.method} {request.url.path} {response.status_code} - {duration_ms:.2f}ms"
        )
        request_id_ctx.reset(token)
        return response

Specialized AI / LLM Telemetry Tracker

# app/core/telemetry.py
import logging
import time
from dataclasses import dataclass, asdict

logger = logging.getLogger("telemetry.ai")

@dataclass
class LLMTelemetryEvent:
    provider: str            # 'ollama', 'openai', 'anthropic'
    model: str               # 'llama3.2', 'gpt-4o'
    operation: str           # 'rag_chat', 'ocr_summary'
    latency_ms: float
    prompt_tokens: int
    completion_tokens: int
    total_tokens: int
    retrieval_chunks: int
    cache_hit: bool
    status: str              # 'success', 'error'
    error_message: str | None = None

def track_llm_invocation(event: LLMTelemetryEvent):
    # Emit structured metric event to log stream
    logger.info(f"AI_TELEMETRY: {json.dumps(asdict(event))}")

4. What Decisions Should I Make?

Observability PillarStandard Recommendation
LogsStructured JSON emitted to stdout (captured seamlessly by Docker, Render, Kubernetes).
TracesOpenTelemetry standard spans with context propagation (traceparent header).
MetricsPrometheus format (/metrics) tracking request count, error rates, p95 latency, and token consumption.
Log LevelsINFO in production; DEBUG in local development; ERROR with full stack traces for unhandled 500s.

5. What Should I Avoid?

  • NEVER log secrets, passwords, or bearer tokens: Redact authorization headers.
  • NEVER log entire document payloads or sensitive user PII: Log metadata (e.g. doc_id, length_chars, page_count), not raw personal files.
  • NEVER use synchronous network logging inside the request hot path: Stream logs to stdout and let background log forwarders handle network transport.

6. How Should I Verify Success?

# 1. Run server and trigger test request
curl -i -H "X-Request-ID: test-trace-123" http://localhost:8000/api/v1/health

# 2. Verify response contains X-Request-ID header
# 3. Verify console emits valid JSON log with request_id = "test-trace-123"

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.