К основному содержанию
скилл CX Codex

logfire-infrastructure — скилл для Claude Code

Скилл настраивает OpenTelemetry Collector так, чтобы метрики хостов, контейнеров, Kubernetes и баз данных уходили в Pydantic Logfire без правок в коде приложения.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pydantic/skills --skill logfire-infrastructure -a claude-code
Открыть на GitHub

Что делает logfire-infrastructure

Скилл ведёт агента по четырём шагам: авторизация и выбор проекта через whoami, определение того, что вообще нужно мониторить, настройка конфигурации Collector и проверка, что данные дошли. Внутри — справочник с готовыми конфигами под каждый источник: хост, Docker, Kubernetes, серверы баз данных, очередей и кешей, метрики AWS и GCP. Для каждого источника указаны имя ресивера и подводные камни вроде прав на сокет Docker, версии API, host.docker.internal против localhost, разрешений IAM и выбора между образами ADOT и Contrib.

Механизм здесь один — OpenTelemetry Collector. Logfire принимает стандартный OTLP, поэтому код приложения трогать не нужно. Это инструмент для инфраструктуры, а не для трейсов и логов самого приложения: для спанов, логов и AI-агентов есть отдельный скилл logfire-instrumentation, и в полной настройке оба часто работают вместе.

Перед запуском или перезапуском Collector скилл требует прогнать валидацию конфига — otelcol-contrib validate --config=collector-config.yaml или otelcol validate для ядра. Опечатка в имени ресивера или сбитый отступ иначе проявятся не ошибкой, а тихо отвалившимся пайплайном. Если бинарника нет в PATH, скилл предлагает заглянуть в запущенный контейнер или взять команду из entrypoint образа, systemd-юнита либо Helm-чарта. Проверка тоже не формальность: агент обязан запросить именно тот host.name, контейнер или кластер, который настроил, а не радоваться любым данным на странице.

Какие задачи решает

  • снять метрики CPU, памяти и диска с хоста или виртуалки
  • подключить мониторинг запущенных Docker-контейнеров
  • собрать метрики кластера Kubernetes в один бэкенд
  • наблюдать за Postgres, Redis, MongoDB или Kafka без правок в приложении
  • забрать метрики AWS или GCP в Logfire

Примеры запросов агенту

  • Настрой мониторинг моего хоста и отправь метрики в Logfire
  • Подключи метрики Docker-контейнеров из docker-compose.yml к Logfire
  • Собери метрики кластера Kubernetes через OpenTelemetry Collector

Как установить logfire-infrastructure

1Через Skills CLI (Vercel)

npx skills add pydantic/skills --skill logfire-infrastructure -a claude-code

2Вручную: положить файлы

~/.claude/skills/logfire-infrastructure/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/logfire-infrastructure/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о logfire-infrastructure

Как установить logfire-infrastructure в Claude Code?

Выполните npx skills add pydantic/skills --skill logfire-infrastructure -a claude-code. Скилл окажется в ~/.claude/skills/logfire-infrastructure/SKILL.md.

Что делает logfire-infrastructure?

Проводит агента через авторизацию в Logfire, определение источников инфраструктуры, настройку OpenTelemetry Collector и проверку, что метрики дошли до нужной страницы. Код приложения при этом не меняется.

Чем этот скилл отличается от logfire-instrumentation?

Этот работает только с инфраструктурой: хосты, контейнеры, кластеры, серверы баз данных и облачные метрики. Трейсы, логи и спаны AI-агентов в самом приложении — задача logfire-instrumentation.

Исходный текст

SKILL.md · MIT
---
name: logfire-infrastructure
description: Monitor hosts, Docker containers, Kubernetes clusters, database/queue/cache servers, and cloud-provider metrics with Pydantic Logfire — no application code required. Use this skill whenever the user asks to "monitor my host/server/VM", "monitor my Docker containers", "monitor my Kubernetes cluster", "send infrastructure metrics to Logfire", "watch my database/Postgres/Redis/MongoDB/Kafka", "collect cloud metrics" (AWS/GCP), or mentions the OpenTelemetry Collector in the context of Logfire. This is infrastructure only — for instrumenting APPLICATION CODE (traces, logs, AI/agent spans) use the logfire-instrumentation skill instead.
---

# Monitor Infrastructure with Logfire

Do **not** use this skill for application-level traces, logs, or AI/agent spans — that's `logfire-instrumentation`. The two compose: a full setup often runs both.

## How This Works

The OpenTelemetry Collector ships host, container, cluster, and infrastructure-service metrics to Logfire with **no application code changes** — Logfire is a fully compliant OTel backend and ingests standard OTLP traces, logs, and metrics from it (one narrow exception noted in the [collector reference](./references/collector/host-and-infra-metrics.md)), so the Collector is the entire mechanism. This is optional and is an advanced tool: if the user only wants their app's own traces, `logfire-instrumentation`'s language SDKs are enough on their own.

## Step 1: Authenticate and Select the Exact Project

Do not open, read, or run any infrastructure config file (`docker-compose.yml`, a Kubernetes manifest, or similar) until `whoami` confirms you're authenticated to the right project — nothing about this step requires knowing what's being monitored. Auth is also the one step that can block on a human (browser sign-in), so starting it first means that wait begins on turn one, not after Step 2's detection work.

Use [Authenticate and Select the Exact Project](https://pydantic.dev/.well-known/agent-skills/logfire-instrumentation/references/auth.md) to derive the CLI target from the supplied Logfire URL and run its target-aware `whoami` check with a verified CLI path — for JS/TS projects without `uv`, use the external-prefix npm fallback instead of plain `npx`, which can execute a repository-local binary. Skip to Step 2 if that already reports the right project and resolved `--region` or `--base-url` target; otherwise, continue through the full authentication and project-selection sequence there, including its safe handoff for the write credential created by `projects use`.


## Step 2: Identify What to Monitor

Detect the infrastructure actually in play, don't assume:

- **Host/VM**: monitoring the machine itself (CPU, memory, disk, network, load).
- **Docker**: read `docker-compose.yml` / `Dockerfile`s for running containers.
- **Kubernetes**: look for manifests, a `kubeconfig`, or `kubectl` context.
- **Database/queue/cache servers**: read `docker-compose.yml` / `pyproject.toml` / `package.json` for Postgres, MySQL, Redis, MongoDB, Kafka, RabbitMQ, Nginx, Apache, Elasticsearch, or Memcached.
- **Cloud provider**: GCP or AWS metrics (Cloud Monitoring, CloudWatch, ECS), when the user names the provider or the app clearly runs there.

More than one can apply at once — a single Collector can run multiple receivers in parallel pipelines.

## Step 3: Configure the Collector

Follow the [collector reference](./references/collector/host-and-infra-metrics.md) for the receiver(s) identified in Step 2 — it covers the shared exporter setup, then a dedicated section per source: host metrics, Docker, Kubernetes, database/queue/cache servers, and cloud-provider metrics, each with the exact receiver name, a working config, and the caveats that actually bite (Docker socket permissions, API version pinning, `host.docker.internal` vs `localhost`, IAM permissions, ADOT vs. Contrib collector images).

Set the same service & resource metadata conventions the [collector reference](./references/collector/host-and-infra-metrics.md) describes — `host.name`, `service.name`, `service.instance.id` — so data groups correctly across the Hosts, Kubernetes, and Metrics pages.

Before starting or restarting the Collector, validate the config file — a receiver typo or bad indentation should surface as a validation error, not a Collector that starts, logs nothing useful, and silently drops the pipeline:

```bash
otelcol-contrib validate --config=collector-config.yaml
# or, for the core (non-Contrib) distribution: otelcol validate --config=...
```

If neither binary is on `PATH`, inspect the running Collector container (for example with `kubectl exec`) or use the deployment-specific validation command from the image entrypoint, systemd unit, or Helm chart. `docker compose config` or `kubectl get pod <name> -o yaml` can show the command when it is explicitly configured.

## Step 4: Verify

Wiring a receiver isn't done when the Collector starts cleanly — confirm the data actually reached the right page for the right host/container/cluster, not just that something arrived. **Never report a metric as "arrived" without having queried for it in this same session** — a plausible-sounding summary that wasn't checked is worse than saying you couldn't verify.

1. **Restart the Collector** after any config change (having validated it, above).
2. **Query for the exact resource you configured, not just any data on the page.** If a Logfire MCP server or API is connected in this session, query for the specific `host.name` / container / cluster you set in Step 3 within the last few minutes — a query that returns zero rows for that exact identifier means it didn't land, even if the page shows data from something else. Otherwise, open the specific product page — **Hosts**, **Docker**, or **Kubernetes** — or the **Metrics** explorer for database/queue/cache/cloud sources, and look for that same exact identifier.
3. **If nothing appears**, check in order: the exporter endpoint/region and write token, that the receiver is in an active pipeline (not defined but never referenced under `service.pipelines`), and that resource attributes (`host.name`, `service.name`) are set — the [reference's own Verify section](./references/collector/host-and-infra-metrics.md) has the full troubleshooting path.
4. **Fix and re-check** until the specific source is visible, not just "some" data.

Close with a final report built from what you just confirmed — org/project/region from `whoami`, which receiver(s) are active, and the exact host/container/cluster identifier you verified — not a template. **Include a direct link to the relevant view** (`/hosts`, `/docker`, `/kubernetes`, or `/metrics`, based on the source) using the project's URL from `whoami`, so the user can see their own source arrive without having to ask where to look. A report with a placeholder in it means a step above was skipped, not finished.

## References

- [Host, Docker, Kubernetes, database/queue/cache, and cloud-provider metrics via the OTel Collector](./references/collector/host-and-infra-metrics.md) — receiver configs, IAM/permission caveats, and its own verify loop.

© pydantic · MIT · pydantic/skills

Похожие скиллы

Все скиллы по теме «DevOps и инфраструктура» →
wizard Matt Pocock Скилл создаёт интерактивный bash-скрипт для ручных шагов: настройки сервисов, секретов CI и разовых миграций. 553 369установок hyperframes-cli heygen-com Управляет проектами HyperFrames через терминал: собирает таймлайн, проверяет контраст кадров, запускает предпросмотр и рендерит видео локально или в облаке. CX Codex +1 1 300 000установок setup-pre-commit Matt Pocock Скилл настраивает pre-commit для JavaScript-репозитория: Husky запускает форматирование, проверку типов и тесты перед коммитом. 489 289установок using-git-worktrees Jesse Vincent Готовит изолированное рабочее дерево перед доработкой или выполнением плана. Проверяет текущий репозиторий, выбирает нативные средства платформы либо Git. CX Codex 217 153установок finishing-a-development-branch Jesse Vincent Скилл проверяет тесты и помогает выбрать, как завершить работу в ветке: слить её, открыть Pull Request или оставить как есть. CX Codex 214 439установок orca-cli stablyai Скилл даёт агенту доступ к worktree, терминалам, артефактам и встроенному браузеру Orca через CLI. Пригодится, когда работа идёт в окружении Orca. CX Codex +1 353 600установок

Из того же набора17

logfire-query Выполняет SQL-запросы к телеметрии Logfire прямо через агента. Скилл нужен для поиска медленных спанов, группировки исключений и расчёта метрик. CX Codex +1 1 900установок logfire-ui Открывает экраны Logfire, трейсы и живой просмотр в браузере без предварительных запросов к телеметрии. CX Codex +1 1 600установок logfire-setup Разбирает широкий запрос «настрой мне Logfire» и отправляет агента к нужному специалисту: инструментация приложения, инфраструктура, evals, фронтенд, Gateway. CX Codex +1 555установок logfire-evals Прогоняет офлайн-оценки Python и Node.js, разбирает отчёты в Logfire и перенаправляет существующие наборы Braintrust. CX Codex +1 554установок migrating-langchain-to-pydantic-ai Скилл для переноса Python-приложений с LangChain, LangGraph и Deep Agents на Pydantic AI. Пригодится, когда нужно сохранить поведение, а не форму фреймворка. CX Codex +1 314установок migrating-openai-agents-sdk-to-pydantic-ai Инструкция для постепенного перевода Python-приложений с OpenAI Agents SDK на Pydantic AI и Harness. Помогает сохранить публичный контракт вызовов, хендоффы и стриминг. CX Codex +1 308установок migrating-vercel-ai-sdk-and-eve-to-pydantic-ai Переводит приложения на TypeScript Vercel AI SDK или Eve на Python с Pydantic AI. Полезен, когда нужно сохранить поведение, а не API исходника. CX Codex +1 306установок migrating-google-adk-to-pydantic-ai Помогает переносить Python-приложения с Google ADK на Pydantic AI, сохраняя поведение вызовов, инструментов, состояния и рабочих процессов. CX Codex +1 305установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой