Community程式設計與開發github.com

可觀測性與儀器化

將程式碼的行為變得可見且可診斷。當你需要加入日誌、指標、追蹤或警報時使用。當你將任何功能部署到生產環境,並需要證據證明其正常運作時使用。當生產環境問題被回報,但你無法從現有資料判斷發生什麼事時使用。

可觀測性與儀器化 是什麼?

這個技能的核心是將可觀測性嵌入開發流程,而非事後補救。它強調在開發功能的同時撰寫儀器化程式碼(如日誌、指標、分散式追蹤),以便在生產環境中能從外部回答「系統在做什麼、為什麼這麼做」的問題。技能支援所有主流平台(如 Node.js、Python 等),並以 OpenTelemetry 作為跨平台標準。 主要流程包括:先定義值班工程師會問的 2‑4 個問題,再選擇適當的信號類型(結構化日誌回答「為何」、指標回答「發生頻率/速度」、追蹤回答「時間花在哪」)。技能也涵蓋如何正確設定警示(應基於使用者症狀而非根本原因)、撰寫最少必要內容的 runbook,以及最終驗證儀器化本身是否正確。此外,它還指出常見的合理化藉口與危險信號,幫助團隊避免落入「更多日誌等於更好可觀測性」或「把使用者 ID 當作指標標籤」等陷阱。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/alfathafp/portofolio-web-design/tree/HEAD/.agents/skills/observability-and-instrumentation

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

可觀測性與儀器化 是做什麼的?

概述

無法觀測的程式碼就是無法運維的程式碼。可觀測性是從外部透過程式碼發出的遙測資料來回答「系統在做什麼以及為什麼」的能力。儀器化不是上線後才補上的附加功能——它應該與功能本身同時編寫,就像測試一樣。如果一個功能上線時沒有遙測資料,那麼第一個使用者回報的錯誤就變成了考古學,而非簡單的查詢。

使用時機

  • 建置任何將會在生產環境中執行的功能
  • 新增新的服務、端點、背景任務或外部整合
  • 生產事故花了太長時間診斷(「我們無法判斷發生什麼事」)
  • 設定或審查警示規則
  • 審查涉及 I/O、重試、佇列或跨服務呼叫的 PR

不適用於:

  • 正在發生的故障診斷——請使用 debugging-and-error-recovery 技能(可觀測性是讓該技能下次變快的原因)
  • 針對已知緩慢進行分析與最佳化——請使用 performance-optimization 技能
  • 上線日的監控檢查清單與回滾觸發器——請參閱 shipping-and-launch 技能;本技能涵蓋的是為它們提供資料的儀器化

流程

1. 在儀器化之前先定義「正常工作」

沒有問題的遙測資料就是雜訊。在加入任何儀器化之前,寫下值班工程師會針對此功能提出的 2–4 個問題:

功能:結帳付款重試
值班工程師會問的問題:
1. 第一次嘗試成功與重試後成功的付款比例各是多少?
2. 當付款永久失敗時,原因是什麼(提供者錯誤?逾時?驗證失敗?)
3. 付款提供者是否比平常慢?
→ 下面的每個訊號都必須幫助回答其中一個問題。

如果你無法明確說出問題,表示你還未準備好進行儀器化——你會記錄所有東西,卻什麼也學不到。

2. 為每個問題選擇正確的訊號

訊號回答的問題成本特性範例
結構化日誌「這個特定案例發生了什麼?」每次事件;隨流量成長payment_failed 附帶提供者錯誤碼
指標「總體來說,頻率/速度如何?」每個數列固定;查詢成本低提供者呼叫的 p99 延遲
追蹤「時間在跨服務中花在哪裡?」每個請求;通常取樣一個慢速結帳,按跳躍點分解

經驗法則:指標告訴你有問題,追蹤告訴你在哪裡,日誌告訴你為什麼。

3. 結構化日誌

記錄事件,而非散文。每一行日誌都是一個帶有穩定事件名稱和機器可讀欄位的 JSON 物件:

// 不好的做法:字串內插——無法查詢、不一致
logger.info(`Payment ${id} failed for user ${userId} after ${n} retries`);

// 好的做法:穩定的事件名稱 + 結構化欄位
logger.warn({
  event: 'payment_failed',
  paymentId: id,
  provider: 'stripe',
  errorCode: err.code,
  attempt: n,
}, 'payment failed');

日誌等級——一致使用:

等級意義值班行動
error不變性被破壞;可能需有人處理調查
warn降級但已處理(重試成功、使用備用方案)觀察趨勢
info重要的商業事件(訂單成立、任務完成)無
debug診斷細節生產環境預設關閉

關聯 ID 是強制的。 在系統邊界產生(或接受)一個請求 ID,並將其附加到每一行日誌、每個 span 以及每個對外呼叫。沒有它,你無法從交錯的日誌中重建單一請求:

// Express:每個請求的子 logger,ID 向下游傳播
app.use((req, res, next) => {
  req.id = req.headers['x-request-id'] ?? crypto.randomUUID();
  req.log = logger.child({ requestId: req.id });
  res.setHeader('x-request-id', req.id);
  next();
});

當多個入口點寫入同一個日誌時,請標記入口點名稱。 關聯 ID 識別一次執行,但無法說明是哪個程式碼路徑啟動了它。同一個任務被排程器、重播端點和手動 CLI 執行觸發時,會在相同的日誌儲存庫中產生可互換的行,因此要歸因於哪一行就退化成刪去法——交叉比對排程器的歷史記錄、行程表、部署日誌——而這個論點只有在那些外部記錄恰好還存在時才成立。在執行開始的地方標記入口點,與關聯 ID 相鄰,並以相同方式傳播兩者:

// 每個入口點的一個輔助函式:執行本身的 logger 攜帶這兩個欄位。
// 使用 `entryPoint`,而非 `source`——ECS 保留 `source.*` 供網路欄位使用。
export const runLog = (entryPoint: 'scheduler' | 'replay_endpoint' | 'cli', runId: string) =>
  logger.child({ entryPoint, requestId: runId });

// scheduler 的 tick        -> runLog('scheduler', crypto.randomUUID())
// POST /jobs/:id/replay -> runLog('replay_endpoint', req.id)
// CLI 呼叫               -> runLog('cli', process.env.RUN_ID ?? crypto.randomUUID())

這兩個欄位必須跨越與關聯 ID 相同的邊界——佇列中繼資料、HTTP 標頭——否則工人程式會重新推斷入口點並猜測。一個僅與入口點相關聯的欄位只是線索,而非歸因:任何可以觸發該任務的東西都可以重現它。

絕不要在日誌中記錄機密、令牌、密碼或完整的個人識別資訊。 這是來自 security-and-hardening 技能的嚴格規則——遙測管道是經典的資料外洩路徑。使用允許清單欄位;不要記錄整個請求主體。

4. 指標

對於請求驅動的服務,在每個端點和每個外部依賴上使用 RED:Rate(請求/秒)、Errors(錯誤率)、Duration(延遲直方圖,而非平均值)。對於資源(佇列、池、主機),使用 USE:Utilization(使用率)、Saturation(飽和度)、Errors(錯誤率)。

與追蹤一樣,供應商中立的途徑是 OpenTelemetry 指標 API(與步驟 5 相同的 SDK 和上下文)。下面的範例使用 Prometheus 的 prom-client——一種常見的後端選擇,並非唯一選擇;RED/USE 和基數規則無論哪種方式都完全相同。

import { Histogram } from 'prom-client';

const httpDuration = new Histogram({
  name: 'http_request_duration_seconds',
  help: 'HTTP request duration',
  labelNames: ['method', 'route', 'status_class'],  // '2xx',而非 '200'
  buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
});

基數是失敗模式。 每個獨特的標籤組合都是一個獨立的時間序列。標籤必須來自小型、固定的集合(路由模板、狀態類別、提供者名稱)。永遠不要將使用者 ID、原始 URL、錯誤訊息或其他無界值用作標籤——那些屬於日誌和追蹤的範疇。

可作為標籤:    route="/api/tasks/:id"   status_class="5xx"   provider="stripe"
絕不可作為標籤:  user_id, email, request_id, 完整 URL, 錯誤訊息文字

永遠不追蹤平均值,只追蹤百分位數:平均值會隱藏那 1% 體驗極差的使用者。使用直方圖並讀取 p50/p95/p99。

5. 分散式追蹤

使用 OpenTelemetry——它是供應商中立的標準,自動儀器化涵蓋了 HTTP、gRPC 和常見的資料庫客戶端,幾乎不需要程式碼:

// tracing.ts——必須在任何其他匯入之前匯入
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

const sdk = new NodeSDK({
  serviceName: 'checkout-service',
  instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();

僅在有意義的內部工作單元(例如 applyDiscounts、chargeProvider)周圍新增手動 span,並附加值班人員會用來過濾的屬性。在每個非同步邊界傳播上下文——HTTP 標頭、佇列訊息中繼資料——否則追蹤會在缺口處中斷。預設以低速率進行基於頭部的取樣;如果你的後端支援尾部取樣,則保留 100% 的錯誤。

6. 警示

警報應該基於使用者感受到的症狀,而非原因:

症狀(值得傳呼):           原因(儀表板顯示,而非直接傳呼):
錯誤率 > 1% 持續 5 分鐘    CPU 使用率 85%
p99 延遲 > 2 秒              一個 Pod 重新啟動
佇列年齡 > 10 分鐘          磁碟使用率 70%

基於原因的警示會在沒有問題時觸發,並在你未預測到的故障發生時失效。基於症狀的警示會在使用者受到影響時精確觸發,無論原因是什麼。

每個你建立的警示都應遵守以下規則:

  1. 必須是可操作的。 如果回應是「忽略它,它會自我修復」,就刪除該警示。
  2. 它必須連結到 runbook——即使只有三行:它的含義、要執行的第一個查詢、升級路徑。
  3. 它的閾值和持續時間必須有 SLO 或歷史資料的依據,而非猜測。
  4. 只使用兩個嚴重等級:傳呼(影響使用者,立即行動)和工單(降級,本週內行動)。第三個層級會變成雜訊,讓人們習慣忽略所有警示。

編寫 Runbook

上述規則 2 要求每個警示都連結到一個 runbook。Runbook 的任務是回答三個問題,而無需讀者思考:發生了什麼事、首先檢查什麼、以及如果無法解決該找誰。存放於 docs/runbooks/ 目錄下,以警示名稱命名。

最小的可行 runbook(三行):

# Runbook: High Error Rate on /api/tasks
**含義:** 資料庫連線池可能耗盡,或是一次不好的部署。
**首先檢查:** `SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend';`
  ——如果 count 超過池限制,請參閱步驟 2。(根據你的資料庫替換為等效查詢。)
**升級聯絡人:** #db-oncall 或工程值班輪值。

何時擴展到三行以上: 僅當第一個檢查不足以做出決定時才加入步驟。一個涵蓋最常見三種原因的 5 步驟 runbook 勝過一個涵蓋所有邊緣情況但被略讀的 20 步驟文件。

保持 runbook 最新。 在關閉每次使用該 runbook 的事故時,將其更新作為一部分——過時的 runbook 會建立虛假信心。如果某個步驟錯誤或遺漏,請在將事故標記為已解決之前修復它。

7. 驗證遙測本身

儀器化也是程式碼;它可能出錯。在宣告工作完成之前,觸發路徑並查看實際輸出:

  • 在 staging 環境強制引發錯誤 -> 透過 requestId 在日誌中找到它,確認欄位是結構化的(而非 [object Object])
  • 發送測試流量 -> 確認指標數列出現,並帶有預期的標籤和合理的值
  • 在追蹤 UI 中追蹤一個請求跨越所有服務 -> 沒有中斷的 span
  • 每個新警示觸發一次(暫時調低閾值)-> 確認它到達正確的頻道且 runbook 連結有效

常見的合理化藉口

合理化藉口現實
「等它運作正常後我再加日誌」「之後」變成「第一次事故之後」,這是最昂貴的發現自己兩眼一抹黑的時刻。在建置的同時進行儀器化。
「更多日誌 = 更好的可觀測性」非結構化的雜訊會讓事故處理變慢,而非加快。三個可查詢的事件勝過三百行散文。
「先用 console.log 就好」非結構化的輸出無法被過濾、關聯或發出警示。結構化日誌只花五分鐘多一點的一次性成本。
「出問題時我們看儀表板就好」沒有定義問題就建立的儀表板會顯示所有東西,唯獨不顯示答案。從值班問題開始。
「對所有重要的事情都設警示,以後再調整」吵雜的傳呼機會讓人忽略它。調整永遠不會發生;真正重要的傳呼被錯過了。
「把使用者 ID 當作指標標籤可以讓除錯更簡單」這也會讓你的指標後端崩潰。高基數查詢屬於日誌和追蹤。
「對我們兩個服務來說,追蹤是大材小用」兩個服務已經意味著有跨服務延遲問題,這是日誌無法回答的。自動儀器化讓成本微不足道。

危險信號

  • 一個包含重試、佇列或外部呼叫,但完全沒有新遙測資料的功能 PR
  • 透過字串內插而非結構化欄位建立的日誌行
  • 沒有關聯 ID/請求 ID——每一行日誌都是孤兒
  • 同一個日誌串流由排程器、webhook 和手動執行共同寫入,卻沒有欄位標明是哪個產生的
  • 使用使用者 ID、原始 URL 或錯誤訊息文字作為標籤的指標(基數炸彈)
  • 延遲追蹤使用平均值而無百分位數
  • 警示每天觸發卻被確認而不採取行動
  • 基於原因(CPU、記憶體)的警示傳呼人員,而使用者面對的錯誤率卻未被監控
  • 機密、令牌或完整請求主體出現在日誌中
  • 「在我的機器上可以運作」是生產功能健康與否的唯一證據

驗證

在為一個功能完成儀器化後,請確認:

  • 該功能的值班問題已寫下,且每個訊號都對應到一個問題
  • 所有日誌輸出都是結構化的(JSON),具有穩定的事件名稱,並且每一行都有關聯 ID
  • 每個由多個入口點寫入的日誌儲存庫都攜帶一個入口點欄位,在執行開始時設定,並與關聯 ID 一起傳播,而非在下游推斷
  • 任何日誌行中都沒有機密、令牌或未經處理的 PII(抽查實際輸出)
  • 每個新端點和每個外部依賴都存在 RED 指標,且標籤集合有界
  • 延遲使用直方圖;p95/p99 可查詢
  • 在追蹤 UI 中可以端到端地追蹤單個請求,且沒有中斷的 span
  • 每個新警示都是基於症狀的、帶有 runbook 連結,並且已經測試觸發過一次
  • 在 staging 環境中引起的故障僅透過遙測資料就被定位,無需閱讀原始碼

欲取得此清單的快速一覽版本(包括上線前儀器化閘道),請參閱 ../../references/observability-checklist.md。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

alfathafp/portofolio-web-design

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

alfathafp/portofolio-web-design

Tests in real browsers via Chrome DevTools MCP. Use when building or debugging anything that runs in a browser. Use when you need to inspect the DOM, capture console errors, analyze network requests, profile performance, or verify visual output with real runtime data. Requires the chrome-devtools MCP server to be configured.

alfathafp/portofolio-web-design

Automates CI/CD pipeline setup. Use when setting up or modifying build and deployment pipelines. Use when you need to automate quality gates, configure test runners in CI, or establish deployment strategies.

alfathafp/portofolio-web-design

Conducts multi-axis code review. Use before merging any change. Use when reviewing code written by yourself, another agent, or a human. Use when you need to assess code quality across multiple dimensions before it enters the main branch. Use when asked to review a diff or a pull request, even when the diff is pasted inline.

alfathafp/portofolio-web-design

Simplifies code for clarity. Use when refactoring code for clarity without changing behavior. Use when code works but is harder to read, maintain, or extend than it should be. Use when reviewing code that has accumulated unnecessary complexity.

alfathafp/portofolio-web-design

Establishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.

alfathafp/portofolio-web-design

Optimizes agent context setup. Use when starting a new session, when agent output quality degrades, when switching between tasks, or when you need to configure rules files and context for a project.

alfathafp/portofolio-web-design

Guides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.

alfathafp/portofolio-web-design

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

alfathafp/portofolio-web-design

Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.

alfathafp/portofolio-web-design

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

alfathafp/portofolio-web-design

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

alfathafp/portofolio-web-design

Records decisions and documentation. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase.

alfathafp/portofolio-web-design

Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when you want every assumption cross-examined before proceeding, when stress-testing a plan for hidden failure modes, when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production auth, security-sensitive logic, a high-stakes migration, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later.

alfathafp/portofolio-web-design

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

alfathafp/portofolio-web-design

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

alfathafp/portofolio-web-design

Builds production-quality, accessible, responsive user-facing UIs. Use when building or modifying interfaces and pages, creating components, implementing layouts, meeting WCAG accessibility requirements, managing state, or when the output needs to look and feel production-quality rather than AI-generated.

alfathafp/portofolio-web-design

Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog.

alfathafp/portofolio-web-design

Refines raw ideas into sharp, actionable concepts through structured divergent and convergent thinking. Use when an idea is still vague, when you need to stress-test assumptions before committing to a plan, or when you want to expand options before converging on one. Triggers on "ideate", "refine this idea", or "stress-test my plan".

alfathafp/portofolio-web-design

Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.

相關技能