<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>模組三：SDK 設計模式 on Tarragon</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/</link><description>Recent content in 模組三：SDK 設計模式 on Tarragon</description><generator>Hugo -- gohugo.io</generator><language>zh-TW</language><copyright>Tarragon (CC BY 4.0)</copyright><lastBuildDate>Fri, 19 Jun 2026 00:00:00 +0000</lastBuildDate><atom:link href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/index.xml" rel="self" type="application/rss+xml"/><item><title>SDK 公開 API 設計</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/public-api/</link><pubDate>Fri, 19 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/public-api/</guid><description>&lt;p>SDK 的公開 API 是應用程式和監控系統之間的契約。六個方法涵蓋 SDK 的完整生命週期：初始化、四類事件上報、資料送出控制和資源釋放。跨平台的 SDK（JS / Flutter / Python）共用相同的方法簽名，讓開發者在不同平台上使用一致的 API。&lt;/p>
&lt;h2 id="六個方法">六個方法&lt;/h2>
&lt;h3 id="init">init&lt;/h3>
&lt;p>SDK 初始化。設定 collector endpoint、app 識別資訊、flush 間隔、buffer 大小。在 app 啟動時呼叫一次。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">Monitor.init({
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl"> endpoint: &amp;#39;https://collector.example.com/v1/events&amp;#39;,
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">3&lt;/span>&lt;span class="cl"> app: &amp;#39;my_app&amp;#39;,
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">4&lt;/span>&lt;span class="cl"> version: &amp;#39;1.2.0&amp;#39;,
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">5&lt;/span>&lt;span class="cl"> flushInterval: 30000, // 毫秒
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">6&lt;/span>&lt;span class="cl"> bufferSize: 100,
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">7&lt;/span>&lt;span class="cl">})&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>init 負責建立 session、記錄 lifecycle.session.start 事件、啟動 flush 計時器。init 之前呼叫其他方法應該拋出明確錯誤（SDK 未初始化），而非靜默忽略。&lt;/p>
&lt;p>&lt;strong>連線驗證策略：lazy&lt;/strong>。init 不驗證 collector 是否可達 — 不發 HTTP 請求、不 ping endpoint。init 的失敗只代表配置錯誤（缺少 endpoint 參數），不代表網路問題。網路問題在第一次 flush 時才浮現，flush 失敗時事件保留在 buffer 等待重試。&lt;/p>
&lt;p>Lazy 策略的理由：SDK 不應阻塞主程式的啟動流程。如果 init 驗證連線，collector 暫時不可用時 app 會啟動失敗 — 監控工具反而變成可用性的瓶頸。短生命週期腳本（&lt;a href="https://tarrragon.github.io/blog/monitoring/05-platform-adaptation/python-platform/" data-link-title="Python 平台適配" data-link-desc="GIL 與 threading、atexit 可靠性、subprocess 監控 — Python SDK 的平台特殊考量">Python 平台適配：短生命週期腳本&lt;/a>）對這一點更敏感 — hook 腳本不能因為 collector 沒啟動就拒絕執行。&lt;/p>
&lt;h3 id="event">event&lt;/h3>
&lt;p>記錄使用者操作事件（&lt;a href="https://tarrragon.github.io/blog/monitoring/01-mental-model/four-event-types/" data-link-title="四類事件的完整定義" data-link-desc="Event / Error / Metric / Lifecycle 四類事件各自的語意、觸發時機和典型用途 — 分類是監控體系的統一語言">四類事件中的 Event 類&lt;/a>）。接受事件名稱和可選的 data 物件。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">Monitor.event(&amp;#39;terminal.connect.start&amp;#39;, { url: &amp;#39;wss://...&amp;#39; })
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl">Monitor.event(&amp;#39;enrollment.qr.scan&amp;#39;)&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>event 方法是非阻塞的 — 事件進入內部 buffer 立即返回，不等待網路送出。應用程式的操作流程不應該被監控 SDK 的網路延遲阻塞。&lt;/p>
&lt;h3 id="error">error&lt;/h3>
&lt;p>記錄錯誤事件。接受 Error/Exception 物件或自訂的錯誤描述。自動附加 stack trace、錯誤類型、觸發位置。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">Monitor.error(exception, { step: &amp;#39;ws_connect&amp;#39; })
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl">Monitor.error(&amp;#39;Auth token missing&amp;#39;, { context: &amp;#39;handshake&amp;#39; })&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>error 方法和自動攔截機制（&lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截&lt;/a>）互補 — 自動攔截處理未捕獲的例外，error 方法處理開發者主動上報的已知錯誤。&lt;/p>
&lt;h3 id="metric">metric&lt;/h3>
&lt;p>記錄數值指標。接受指標名稱和數值。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">Monitor.metric(&amp;#39;connect.duration_ms&amp;#39;, 320)
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl">Monitor.metric(&amp;#39;terminal.fps&amp;#39;, 58.5)&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>metric 方法記錄的是離散的數值快照。聚合計算（平均、百分位、趨勢）在 collector 端完成，SDK 端只負責記錄原始值。&lt;/p>
&lt;h3 id="flush">flush&lt;/h3>
&lt;p>強制送出 buffer 中所有待發事件。正常情況下 SDK 按 flushInterval 定期自動 flush（&lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出&lt;/a>）。flush 方法用於需要確保事件已送出的場景 — 例如 app 即將進入背景或使用者手動觸發 log 上傳。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">await Monitor.flush()&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>flush 是非同步方法 — 需要等待網路請求完成。呼叫端可以 await 確認送出成功，也可以 fire-and-forget。&lt;/p></description><content:encoded><![CDATA[<p>SDK 的公開 API 是應用程式和監控系統之間的契約。六個方法涵蓋 SDK 的完整生命週期：初始化、四類事件上報、資料送出控制和資源釋放。跨平台的 SDK（JS / Flutter / Python）共用相同的方法簽名，讓開發者在不同平台上使用一致的 API。</p>
<h2 id="六個方法">六個方法</h2>
<h3 id="init">init</h3>
<p>SDK 初始化。設定 collector endpoint、app 識別資訊、flush 間隔、buffer 大小。在 app 啟動時呼叫一次。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Monitor.init({
</span></span><span class="line"><span class="ln">2</span><span class="cl">  endpoint: &#39;https://collector.example.com/v1/events&#39;,
</span></span><span class="line"><span class="ln">3</span><span class="cl">  app: &#39;my_app&#39;,
</span></span><span class="line"><span class="ln">4</span><span class="cl">  version: &#39;1.2.0&#39;,
</span></span><span class="line"><span class="ln">5</span><span class="cl">  flushInterval: 30000,   // 毫秒
</span></span><span class="line"><span class="ln">6</span><span class="cl">  bufferSize: 100,
</span></span><span class="line"><span class="ln">7</span><span class="cl">})</span></span></code></pre></div><p>init 負責建立 session、記錄 lifecycle.session.start 事件、啟動 flush 計時器。init 之前呼叫其他方法應該拋出明確錯誤（SDK 未初始化），而非靜默忽略。</p>
<p><strong>連線驗證策略：lazy</strong>。init 不驗證 collector 是否可達 — 不發 HTTP 請求、不 ping endpoint。init 的失敗只代表配置錯誤（缺少 endpoint 參數），不代表網路問題。網路問題在第一次 flush 時才浮現，flush 失敗時事件保留在 buffer 等待重試。</p>
<p>Lazy 策略的理由：SDK 不應阻塞主程式的啟動流程。如果 init 驗證連線，collector 暫時不可用時 app 會啟動失敗 — 監控工具反而變成可用性的瓶頸。短生命週期腳本（<a href="/blog/monitoring/05-platform-adaptation/python-platform/" data-link-title="Python 平台適配" data-link-desc="GIL 與 threading、atexit 可靠性、subprocess 監控 — Python SDK 的平台特殊考量">Python 平台適配：短生命週期腳本</a>）對這一點更敏感 — hook 腳本不能因為 collector 沒啟動就拒絕執行。</p>
<h3 id="event">event</h3>
<p>記錄使用者操作事件（<a href="/blog/monitoring/01-mental-model/four-event-types/" data-link-title="四類事件的完整定義" data-link-desc="Event / Error / Metric / Lifecycle 四類事件各自的語意、觸發時機和典型用途 — 分類是監控體系的統一語言">四類事件中的 Event 類</a>）。接受事件名稱和可選的 data 物件。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Monitor.event(&#39;terminal.connect.start&#39;, { url: &#39;wss://...&#39; })
</span></span><span class="line"><span class="ln">2</span><span class="cl">Monitor.event(&#39;enrollment.qr.scan&#39;)</span></span></code></pre></div><p>event 方法是非阻塞的 — 事件進入內部 buffer 立即返回，不等待網路送出。應用程式的操作流程不應該被監控 SDK 的網路延遲阻塞。</p>
<h3 id="error">error</h3>
<p>記錄錯誤事件。接受 Error/Exception 物件或自訂的錯誤描述。自動附加 stack trace、錯誤類型、觸發位置。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Monitor.error(exception, { step: &#39;ws_connect&#39; })
</span></span><span class="line"><span class="ln">2</span><span class="cl">Monitor.error(&#39;Auth token missing&#39;, { context: &#39;handshake&#39; })</span></span></code></pre></div><p>error 方法和自動攔截機制（<a href="/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截</a>）互補 — 自動攔截處理未捕獲的例外，error 方法處理開發者主動上報的已知錯誤。</p>
<h3 id="metric">metric</h3>
<p>記錄數值指標。接受指標名稱和數值。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Monitor.metric(&#39;connect.duration_ms&#39;, 320)
</span></span><span class="line"><span class="ln">2</span><span class="cl">Monitor.metric(&#39;terminal.fps&#39;, 58.5)</span></span></code></pre></div><p>metric 方法記錄的是離散的數值快照。聚合計算（平均、百分位、趨勢）在 collector 端完成，SDK 端只負責記錄原始值。</p>
<h3 id="flush">flush</h3>
<p>強制送出 buffer 中所有待發事件。正常情況下 SDK 按 flushInterval 定期自動 flush（<a href="/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出</a>）。flush 方法用於需要確保事件已送出的場景 — 例如 app 即將進入背景或使用者手動觸發 log 上傳。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">await Monitor.flush()</span></span></code></pre></div><p>flush 是非同步方法 — 需要等待網路請求完成。呼叫端可以 await 確認送出成功，也可以 fire-and-forget。</p>
<h3 id="close">close</h3>
<p>SDK 資源釋放。停止 flush 計時器、送出 buffer 中剩餘事件、關閉網路連線、記錄 lifecycle.session.end 事件。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">await Monitor.close()</span></span></code></pre></div><p>close 在 app 關閉時呼叫。呼叫後 SDK 進入已關閉狀態，後續的 event/error/metric 呼叫應該被靜默忽略（不拋錯，因為 app 正在關閉）。</p>
<h2 id="api-設計原則">API 設計原則</h2>
<p><strong>方法名稱和四類事件對齊</strong>。event / error / metric 三個方法直接對應三類事件，lifecycle 事件由 init 和 close 自動產生。開發者看到方法名稱就知道對應哪類事件。</p>
<p><strong>所有上報方法非阻塞</strong>。event、error、metric 進 buffer 立即返回。監控 SDK 阻塞應用程式的操作流程是反模式。</p>
<p><strong>init 和 close 成對出現</strong>。init 開始 session，close 結束 session。兩者界定 SDK 的活躍期間。</p>
<p>各平台的 SDK 整合範例（Flutter 的 pubspec.yaml + main.dart init、Python 的 pip install + init code、JS 的 script tag + init）見 monitor repo 各 SDK 的 README。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>自動攔截未捕獲的錯誤 → <a href="/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制</a></li>
<li>Buffer 和 flush 的策略 → <a href="/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出策略</a></li>
<li>SDK 端的資料脫敏 → <a href="/blog/monitoring/03-sdk-design/redaction-helper/" data-link-title="SDK redaction helper" data-link-desc="在事件離開 SDK 前移除敏感資訊 — 預設 redaction rule 處理常見 pattern，自訂 rule 處理業務特定的 secret">SDK redaction helper</a></li>
<li>SDK 的 HTTP POST 行為需要 protocol test → <a href="/blog/testing/03-protocol-integration-test/" data-link-title="模組三：協議整合測試" data-link-desc="對真實服務驗證 WebSocket / gRPC / HTTP 協議契約 — unit test 和 E2E test 之間的一層">testing 模組三 協議整合測試</a></li>
</ul>
]]></content:encoded></item><item><title>自動攔截機制</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/auto-intercept/</link><pubDate>Fri, 19 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/auto-intercept/</guid><description>&lt;p>自動攔截機制讓 SDK 在開發者不寫任何 error 上報程式碼的情況下，自動捕獲未處理的例外並記錄為 error 事件。每個平台有各自的全域錯誤處理器，SDK 在 init 時註冊攔截器，捕獲後轉換為統一的 error 事件格式送出。&lt;/p>
&lt;h2 id="各平台的攔截點">各平台的攔截點&lt;/h2>
&lt;h3 id="javascript--typescript">JavaScript / TypeScript&lt;/h3>
&lt;p>JS 環境有兩個全域錯誤攔截點：&lt;/p>
&lt;p>&lt;code>window.onerror&lt;/code> 捕獲同步程式碼中未處理的例外。回呼函式收到 error message、來源 URL、行號、列號和 Error 物件。&lt;/p>
&lt;p>&lt;code>window.onunhandledrejection&lt;/code> 捕獲未處理的 Promise rejection。回呼函式收到 PromiseRejectionEvent，包含 rejection reason。&lt;/p>
&lt;p>SDK 在 init 時註冊這兩個處理器。註冊前先保存原有的處理器（如果有），攔截後先呼叫原有處理器再執行 SDK 的記錄邏輯 — 避免覆蓋應用程式已有的錯誤處理。&lt;/p>
&lt;p>限制：&lt;code>onerror&lt;/code> 對跨域腳本的錯誤只收到 &lt;code>Script error.&lt;/code> 訊息，沒有 stack trace。需要在 &lt;code>&amp;lt;script&amp;gt;&lt;/code> 標籤加 &lt;code>crossorigin&lt;/code> 屬性，server 端的 CORS header 加 &lt;code>Access-Control-Allow-Origin&lt;/code>。&lt;/p>
&lt;h3 id="flutter">Flutter&lt;/h3>
&lt;p>Flutter 有兩個攔截層：&lt;/p>
&lt;p>&lt;code>FlutterError.onError&lt;/code> 捕獲 widget build / layout / paint 過程中的例外。預設行為是在 console 印出錯誤，SDK 替換為記錄 error 事件後再呼叫預設處理器。&lt;/p>
&lt;p>&lt;code>PlatformDispatcher.instance.onError&lt;/code> 捕獲其他非同步區域的未處理例外（Dart 2.15+）。包含 Isolate 內的未捕獲例外。&lt;/p>
&lt;p>&lt;code>runZonedGuarded&lt;/code> 是另一個選項 — 在指定的 Zone 內捕獲所有未處理例外。SDK 可以用 &lt;code>runZonedGuarded&lt;/code> 包住整個 &lt;code>runApp()&lt;/code>，但這和 &lt;code>PlatformDispatcher.onError&lt;/code> 有重疊，需要避免同一個例外被記錄兩次。&lt;/p>
&lt;p>限制：Flutter 的 release mode 會移除 stack trace 的符號資訊（obfuscation）。需要保留 debug symbols 檔案（&lt;code>.dSYM&lt;/code> / &lt;code>mapping.txt&lt;/code>），在 collector 端做 symbolication。&lt;/p>
&lt;h3 id="python">Python&lt;/h3>
&lt;p>&lt;code>sys.excepthook&lt;/code> 處理主執行緒的未捕獲例外。回呼函式收到 exception type、value 和 traceback。&lt;/p>
&lt;p>&lt;code>threading.excepthook&lt;/code>（Python 3.8+）處理子執行緒的未捕獲例外。&lt;/p>
&lt;p>&lt;code>atexit.register&lt;/code> 用於在 Python 程序退出時 flush 剩餘的 buffer。但 &lt;code>atexit&lt;/code> 在 &lt;code>os._exit()&lt;/code> 或 SIGKILL 時不會執行。&lt;/p>
&lt;p>限制：Python 的 GIL 讓 SDK 的網路操作可能阻塞主執行緒。SDK 的 flush 應該在獨立的 daemon thread 中執行，主執行緒只負責把事件放入 buffer。&lt;/p>
&lt;h2 id="攔截後的統一處理">攔截後的統一處理&lt;/h2>
&lt;p>不同平台的錯誤物件格式不同（JS 的 Error、Flutter 的 FlutterErrorDetails、Python 的 sys.exc_info tuple）。SDK 在攔截後把平台特定的錯誤物件轉換為統一的 error 事件格式：&lt;/p>
&lt;ul>
&lt;li>type: &lt;code>&amp;quot;error&amp;quot;&lt;/code>&lt;/li>
&lt;li>name: 從 error class name 推導（&lt;code>TypeError&lt;/code> → &lt;code>error.TypeError&lt;/code>）&lt;/li>
&lt;li>data: 包含 message、stack trace（字串化）、觸發位置&lt;/li>
&lt;/ul>
&lt;p>轉換層是每個平台 SDK 唯一的平台特定程式碼。轉換完成後，事件進入和手動上報相同的 buffer → flush 管線。&lt;/p>
&lt;h2 id="和手動上報的分工">和手動上報的分工&lt;/h2>
&lt;p>自動攔截處理「開發者沒有預期到的錯誤」— 未捕獲的例外、未處理的 rejection。手動上報（&lt;code>Monitor.error()&lt;/code>）處理「開發者知道可能發生但想記錄的錯誤」— 已捕獲的例外、業務邏輯的異常狀態。&lt;/p>
&lt;p>兩者進入同一個 buffer 和 flush 管線，在 collector 端可以用 data 中的 &lt;code>source: &amp;quot;auto&amp;quot;&lt;/code> / &lt;code>source: &amp;quot;manual&amp;quot;&lt;/code> 欄位區分。&lt;/p>
&lt;h2 id="下一步路由">下一步路由&lt;/h2>
&lt;ul>
&lt;li>SDK 公開 API → &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計&lt;/a>&lt;/li>
&lt;li>各平台的深入適配問題 → &lt;a href="https://tarrragon.github.io/blog/monitoring/05-platform-adaptation/" data-link-title="模組五：平台適配" data-link-desc="JS CORS / Flutter isolate / Python GIL / Go graceful shutdown — 各平台的特殊考量">模組五 平台適配&lt;/a>&lt;/li>
&lt;li>Buffer 和 flush → &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出策略&lt;/a>&lt;/li>
&lt;li>主動感測器設計（和被動攔截互補）→ &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/frontend-sensor-design/" data-link-title="前端感測器設計" data-link-desc="什麼行為值得埋感測器、每類感測器的實作方式、取樣策略和效能影響 — 和 auto-intercept 的被動攔截互補">前端感測器設計&lt;/a>&lt;/li>
&lt;/ul></description><content:encoded><![CDATA[<p>自動攔截機制讓 SDK 在開發者不寫任何 error 上報程式碼的情況下，自動捕獲未處理的例外並記錄為 error 事件。每個平台有各自的全域錯誤處理器，SDK 在 init 時註冊攔截器，捕獲後轉換為統一的 error 事件格式送出。</p>
<h2 id="各平台的攔截點">各平台的攔截點</h2>
<h3 id="javascript--typescript">JavaScript / TypeScript</h3>
<p>JS 環境有兩個全域錯誤攔截點：</p>
<p><code>window.onerror</code> 捕獲同步程式碼中未處理的例外。回呼函式收到 error message、來源 URL、行號、列號和 Error 物件。</p>
<p><code>window.onunhandledrejection</code> 捕獲未處理的 Promise rejection。回呼函式收到 PromiseRejectionEvent，包含 rejection reason。</p>
<p>SDK 在 init 時註冊這兩個處理器。註冊前先保存原有的處理器（如果有），攔截後先呼叫原有處理器再執行 SDK 的記錄邏輯 — 避免覆蓋應用程式已有的錯誤處理。</p>
<p>限制：<code>onerror</code> 對跨域腳本的錯誤只收到 <code>Script error.</code> 訊息，沒有 stack trace。需要在 <code>&lt;script&gt;</code> 標籤加 <code>crossorigin</code> 屬性，server 端的 CORS header 加 <code>Access-Control-Allow-Origin</code>。</p>
<h3 id="flutter">Flutter</h3>
<p>Flutter 有兩個攔截層：</p>
<p><code>FlutterError.onError</code> 捕獲 widget build / layout / paint 過程中的例外。預設行為是在 console 印出錯誤，SDK 替換為記錄 error 事件後再呼叫預設處理器。</p>
<p><code>PlatformDispatcher.instance.onError</code> 捕獲其他非同步區域的未處理例外（Dart 2.15+）。包含 Isolate 內的未捕獲例外。</p>
<p><code>runZonedGuarded</code> 是另一個選項 — 在指定的 Zone 內捕獲所有未處理例外。SDK 可以用 <code>runZonedGuarded</code> 包住整個 <code>runApp()</code>，但這和 <code>PlatformDispatcher.onError</code> 有重疊，需要避免同一個例外被記錄兩次。</p>
<p>限制：Flutter 的 release mode 會移除 stack trace 的符號資訊（obfuscation）。需要保留 debug symbols 檔案（<code>.dSYM</code> / <code>mapping.txt</code>），在 collector 端做 symbolication。</p>
<h3 id="python">Python</h3>
<p><code>sys.excepthook</code> 處理主執行緒的未捕獲例外。回呼函式收到 exception type、value 和 traceback。</p>
<p><code>threading.excepthook</code>（Python 3.8+）處理子執行緒的未捕獲例外。</p>
<p><code>atexit.register</code> 用於在 Python 程序退出時 flush 剩餘的 buffer。但 <code>atexit</code> 在 <code>os._exit()</code> 或 SIGKILL 時不會執行。</p>
<p>限制：Python 的 GIL 讓 SDK 的網路操作可能阻塞主執行緒。SDK 的 flush 應該在獨立的 daemon thread 中執行，主執行緒只負責把事件放入 buffer。</p>
<h2 id="攔截後的統一處理">攔截後的統一處理</h2>
<p>不同平台的錯誤物件格式不同（JS 的 Error、Flutter 的 FlutterErrorDetails、Python 的 sys.exc_info tuple）。SDK 在攔截後把平台特定的錯誤物件轉換為統一的 error 事件格式：</p>
<ul>
<li>type: <code>&quot;error&quot;</code></li>
<li>name: 從 error class name 推導（<code>TypeError</code> → <code>error.TypeError</code>）</li>
<li>data: 包含 message、stack trace（字串化）、觸發位置</li>
</ul>
<p>轉換層是每個平台 SDK 唯一的平台特定程式碼。轉換完成後，事件進入和手動上報相同的 buffer → flush 管線。</p>
<h2 id="和手動上報的分工">和手動上報的分工</h2>
<p>自動攔截處理「開發者沒有預期到的錯誤」— 未捕獲的例外、未處理的 rejection。手動上報（<code>Monitor.error()</code>）處理「開發者知道可能發生但想記錄的錯誤」— 已捕獲的例外、業務邏輯的異常狀態。</p>
<p>兩者進入同一個 buffer 和 flush 管線，在 collector 端可以用 data 中的 <code>source: &quot;auto&quot;</code> / <code>source: &quot;manual&quot;</code> 欄位區分。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>SDK 公開 API → <a href="/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計</a></li>
<li>各平台的深入適配問題 → <a href="/blog/monitoring/05-platform-adaptation/" data-link-title="模組五：平台適配" data-link-desc="JS CORS / Flutter isolate / Python GIL / Go graceful shutdown — 各平台的特殊考量">模組五 平台適配</a></li>
<li>Buffer 和 flush → <a href="/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出策略</a></li>
<li>主動感測器設計（和被動攔截互補）→ <a href="/blog/monitoring/03-sdk-design/frontend-sensor-design/" data-link-title="前端感測器設計" data-link-desc="什麼行為值得埋感測器、每類感測器的實作方式、取樣策略和效能影響 — 和 auto-intercept 的被動攔截互補">前端感測器設計</a></li>
</ul>
]]></content:encoded></item><item><title>攢批送出策略</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/batch-flush/</link><pubDate>Fri, 19 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/batch-flush/</guid><description>&lt;p>攢批送出策略控制事件從 SDK 內部 buffer 送到 collector 的時機。事件產生後先進入記憶體 buffer，累積到一定數量或間隔一定時間後，一次性透過 HTTP POST 送出整批事件。攢批的目的是減少網路請求次數 — 100 筆事件合併成一個 HTTP 請求，比 100 個獨立請求的網路開銷低。&lt;/p>
&lt;h2 id="三個觸發條件">三個觸發條件&lt;/h2>
&lt;h3 id="時間觸發flush-interval">時間觸發（flush interval）&lt;/h3>
&lt;p>固定間隔自動 flush。SDK 在 init 時啟動計時器，每隔 N 毫秒檢查 buffer 是否有待發事件，有則送出。&lt;/p>
&lt;p>合理的間隔範圍：10-60 秒。間隔太短（1 秒）接近逐筆送出，失去攢批的效益；間隔太長（5 分鐘）可能讓事件延遲到達 collector，影響即時監控和告警的反應速度。&lt;/p>
&lt;p>自用工具場景下 30 秒是合理的預設 — 事件量低，30 秒的延遲對 debug 分析沒有實質影響。商業產品可以降到 10 秒以獲得更接近即時的 error 告警。&lt;/p>
&lt;h3 id="數量觸發buffer-size">數量觸發（buffer size）&lt;/h3>
&lt;p>Buffer 內的事件數量達到上限時立即 flush。Buffer size 設定為一次 HTTP POST 的合理 payload 大小對應的事件數量。&lt;/p>
&lt;p>合理的數量範圍：50-200 筆。數量太少（10 筆）頻繁觸發 flush；數量太多（1000 筆）單次 HTTP POST 的 payload 過大，增加傳輸失敗的風險（超時、記憶體）。&lt;/p>
&lt;p>數量觸發和時間觸發互為備援。高頻事件場景（使用者快速操作）靠數量觸發避免 buffer 溢出；低頻事件場景（使用者長時間閒置）靠時間觸發確保事件在合理時間內送出。&lt;/p>
&lt;h3 id="關閉觸發flush-on-close">關閉觸發（flush on close）&lt;/h3>
&lt;p>SDK close 時強制 flush buffer 中所有剩餘事件。這是最後一道保障 — app 關閉後 buffer 中未送出的事件就永久遺失了。&lt;/p>
&lt;p>close flush 的挑戰是時間限制。iOS app 進入背景後約 5 秒會被系統 suspend，Android 的限制更嚴格。Close flush 必須在這個時間窗口內完成網路請求。如果 buffer 中事件太多導致 flush 超時，需要截斷 — 送出最近的 N 筆，放棄較舊的。&lt;/p>
&lt;h2 id="buffer-管理">Buffer 管理&lt;/h2>
&lt;h3 id="記憶體-buffer">記憶體 buffer&lt;/h3>
&lt;p>Buffer 在記憶體中維護一個事件陣列。新事件 append 到尾端，flush 時取出整個陣列送出並清空。&lt;/p>
&lt;p>記憶體 buffer 的上限應該設定為 buffer size 的 2-3 倍（允許 1-2 次 flush 失敗後累積的事件）。超過上限時丟棄最舊的事件（FIFO），保留最新的 — 最新的事件對 debug 和即時分析的價值更高。&lt;/p>
&lt;h3 id="離線-buffer">離線 buffer&lt;/h3>
&lt;p>網路不可用時，事件累積在記憶體 buffer 中。如果離線時間超過記憶體 buffer 容量，需要離線 persistence — 見 &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/offline-buffer/" data-link-title="離線 buffer 與重試" data-link-desc="網路不可用時的事件保存策略 — FIFO 丟棄、本地 persistence、恢復後補發的取捨">離線 buffer 與重試&lt;/a>。&lt;/p>
&lt;h2 id="flush-失敗處理">Flush 失敗處理&lt;/h2>
&lt;p>HTTP POST 失敗時（網路中斷、server 回 5xx、超時），事件保留在 buffer 中等待下一次 flush 重試。不立即重試 — 連續失敗通常代表網路問題或 server 問題，立即重試只會增加負載。&lt;/p>
&lt;p>重試次數有上限（3 次）。超過重試上限的事件被丟棄，記錄一筆 &lt;code>sdk.flush.dropped&lt;/code> metric 事件（這筆 metric 本身也進 buffer，在下次成功 flush 時送出）。&lt;/p>
&lt;h3 id="sdk-對-collector-回應的處理">SDK 對 collector 回應的處理&lt;/h3>
&lt;p>SDK 只需要判斷 HTTP status code 就知道怎麼處理 buffer，不需要解析 response body 的細節。&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>Status&lt;/th>
 &lt;th>SDK 行為&lt;/th>
 &lt;th>理由&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>200&lt;/td>
 &lt;td>清除已送出的 buffer&lt;/td>
 &lt;td>全部成功&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>207&lt;/td>
 &lt;td>清除 buffer + 記錄 warning log&lt;/td>
 &lt;td>合法事件已被接受；失敗事件是 schema 問題，重試也不會過&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>400&lt;/td>
 &lt;td>清除 buffer + 記錄 error log&lt;/td>
 &lt;td>Schema 問題重試也不會過，保留在 buffer 只會擋住後續事件&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>503&lt;/td>
 &lt;td>保留 buffer + 等待 &lt;code>retry_after&lt;/code> 秒&lt;/td>
 &lt;td>collector 暫時不可用，事件本身沒問題&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>其他（network error / timeout）&lt;/td>
 &lt;td>保留 buffer + 下次 flush 重試&lt;/td>
 &lt;td>暫時性問題，重試有機會成功&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;p>207 和 400 都清 buffer 的關鍵判斷：Schema 驗證失敗是 SDK 端產出了不合規的事件，問題在 SDK 的事件建構邏輯（程式碼 bug），不在 collector 或網路 — 重試相同事件永遠不會過。SDK 把失敗事件的 error 訊息記到 warning/error log 供開發者排查，然後放行後續事件。&lt;/p></description><content:encoded><![CDATA[<p>攢批送出策略控制事件從 SDK 內部 buffer 送到 collector 的時機。事件產生後先進入記憶體 buffer，累積到一定數量或間隔一定時間後，一次性透過 HTTP POST 送出整批事件。攢批的目的是減少網路請求次數 — 100 筆事件合併成一個 HTTP 請求，比 100 個獨立請求的網路開銷低。</p>
<h2 id="三個觸發條件">三個觸發條件</h2>
<h3 id="時間觸發flush-interval">時間觸發（flush interval）</h3>
<p>固定間隔自動 flush。SDK 在 init 時啟動計時器，每隔 N 毫秒檢查 buffer 是否有待發事件，有則送出。</p>
<p>合理的間隔範圍：10-60 秒。間隔太短（1 秒）接近逐筆送出，失去攢批的效益；間隔太長（5 分鐘）可能讓事件延遲到達 collector，影響即時監控和告警的反應速度。</p>
<p>自用工具場景下 30 秒是合理的預設 — 事件量低，30 秒的延遲對 debug 分析沒有實質影響。商業產品可以降到 10 秒以獲得更接近即時的 error 告警。</p>
<h3 id="數量觸發buffer-size">數量觸發（buffer size）</h3>
<p>Buffer 內的事件數量達到上限時立即 flush。Buffer size 設定為一次 HTTP POST 的合理 payload 大小對應的事件數量。</p>
<p>合理的數量範圍：50-200 筆。數量太少（10 筆）頻繁觸發 flush；數量太多（1000 筆）單次 HTTP POST 的 payload 過大，增加傳輸失敗的風險（超時、記憶體）。</p>
<p>數量觸發和時間觸發互為備援。高頻事件場景（使用者快速操作）靠數量觸發避免 buffer 溢出；低頻事件場景（使用者長時間閒置）靠時間觸發確保事件在合理時間內送出。</p>
<h3 id="關閉觸發flush-on-close">關閉觸發（flush on close）</h3>
<p>SDK close 時強制 flush buffer 中所有剩餘事件。這是最後一道保障 — app 關閉後 buffer 中未送出的事件就永久遺失了。</p>
<p>close flush 的挑戰是時間限制。iOS app 進入背景後約 5 秒會被系統 suspend，Android 的限制更嚴格。Close flush 必須在這個時間窗口內完成網路請求。如果 buffer 中事件太多導致 flush 超時，需要截斷 — 送出最近的 N 筆，放棄較舊的。</p>
<h2 id="buffer-管理">Buffer 管理</h2>
<h3 id="記憶體-buffer">記憶體 buffer</h3>
<p>Buffer 在記憶體中維護一個事件陣列。新事件 append 到尾端，flush 時取出整個陣列送出並清空。</p>
<p>記憶體 buffer 的上限應該設定為 buffer size 的 2-3 倍（允許 1-2 次 flush 失敗後累積的事件）。超過上限時丟棄最舊的事件（FIFO），保留最新的 — 最新的事件對 debug 和即時分析的價值更高。</p>
<h3 id="離線-buffer">離線 buffer</h3>
<p>網路不可用時，事件累積在記憶體 buffer 中。如果離線時間超過記憶體 buffer 容量，需要離線 persistence — 見 <a href="/blog/monitoring/03-sdk-design/offline-buffer/" data-link-title="離線 buffer 與重試" data-link-desc="網路不可用時的事件保存策略 — FIFO 丟棄、本地 persistence、恢復後補發的取捨">離線 buffer 與重試</a>。</p>
<h2 id="flush-失敗處理">Flush 失敗處理</h2>
<p>HTTP POST 失敗時（網路中斷、server 回 5xx、超時），事件保留在 buffer 中等待下一次 flush 重試。不立即重試 — 連續失敗通常代表網路問題或 server 問題，立即重試只會增加負載。</p>
<p>重試次數有上限（3 次）。超過重試上限的事件被丟棄，記錄一筆 <code>sdk.flush.dropped</code> metric 事件（這筆 metric 本身也進 buffer，在下次成功 flush 時送出）。</p>
<h3 id="sdk-對-collector-回應的處理">SDK 對 collector 回應的處理</h3>
<p>SDK 只需要判斷 HTTP status code 就知道怎麼處理 buffer，不需要解析 response body 的細節。</p>
<table>
  <thead>
      <tr>
          <th>Status</th>
          <th>SDK 行為</th>
          <th>理由</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>200</td>
          <td>清除已送出的 buffer</td>
          <td>全部成功</td>
      </tr>
      <tr>
          <td>207</td>
          <td>清除 buffer + 記錄 warning log</td>
          <td>合法事件已被接受；失敗事件是 schema 問題，重試也不會過</td>
      </tr>
      <tr>
          <td>400</td>
          <td>清除 buffer + 記錄 error log</td>
          <td>Schema 問題重試也不會過，保留在 buffer 只會擋住後續事件</td>
      </tr>
      <tr>
          <td>503</td>
          <td>保留 buffer + 等待 <code>retry_after</code> 秒</td>
          <td>collector 暫時不可用，事件本身沒問題</td>
      </tr>
      <tr>
          <td>其他（network error / timeout）</td>
          <td>保留 buffer + 下次 flush 重試</td>
          <td>暫時性問題，重試有機會成功</td>
      </tr>
  </tbody>
</table>
<p>207 和 400 都清 buffer 的關鍵判斷：Schema 驗證失敗是 SDK 端產出了不合規的事件，問題在 SDK 的事件建構邏輯（程式碼 bug），不在 collector 或網路 — 重試相同事件永遠不會過。SDK 把失敗事件的 error 訊息記到 warning/error log 供開發者排查，然後放行後續事件。</p>
<p>503 保留 buffer 的關鍵判斷：collector 暫時不可用是基礎設施問題（SQLite busy timeout、背壓），事件本身合法，等 collector 恢復後重試會成功。<code>retry_after</code> 由 collector 在回應中指定，SDK 用這個值設定下次 flush 的最小等待時間。</p>
<h2 id="batch-格式">Batch 格式</h2>
<p>SDK 在 flush 時把 buffer 中所有事件包裝成一個 batch，帶上 <code>batch_id</code> 送出。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="ln">1</span><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">  <span class="nt">&#34;batch_id&#34;</span><span class="p">:</span> <span class="s2">&#34;019537a0-7b2c-7def-8a2b-3c4d5e6f7890&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">  <span class="nt">&#34;events&#34;</span><span class="p">:</span> <span class="p">[</span> <span class="err">...</span> <span class="p">]</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl"><span class="p">}</span></span></span></code></pre></div><p><code>batch_id</code> 由 SDK 在 flush 時產生。使用 UUID v7（<code>uuid.uuid7()</code>，Python 3.14+ 標準庫）——時間戳前綴保證有序（debug 時按 batch_id 排序即時間順序），隨機後綴保證唯一（高負載下多個 SDK 同時 flush 不碰撞）。用途是追蹤和 debug（collector log 中標記同一批事件的來源）。Collector 不依賴 batch_id 做去重 — 同一批事件被 SDK 重試時會帶不同的 batch_id（每次 flush 重新產生），collector 按事件內容（timestamp + source + name）判斷是否重複。</p>
<p>UUID v7 而非時間戳格式的選型理由：時間戳格式（<code>b-{YYYYMMDD}-{HHMMSSfff}</code>）在同毫秒多次 flush 時會碰撞，雖然 MVP 的 debug 用途碰撞無害，但 batch_id 碰撞在後續版本的離線補發去重場景（見 <a href="/blog/monitoring/03-sdk-design/offline-buffer/" data-link-title="離線 buffer 與重試" data-link-desc="網路不可用時的事件保存策略 — FIFO 丟棄、本地 persistence、恢復後補發的取捨">離線 buffer 與重試</a>）會造成歧義。UUID v7 兼顧有序和唯一，一次到位。</p>
<h2 id="heartbeat-和-flush-的整合">Heartbeat 和 flush 的整合</h2>
<p>DevOps dashboard 需要 <code>sdk.heartbeat</code> 事件判斷 SDK 是否存活。Heartbeat 不需要獨立的 timer — 整合在 flush timer 中：</p>
<p>flush timer 觸發時，如果 buffer 為空且距上次 heartbeat 超過設定間隔（預設 5 分鐘），自動注入一筆 <code>sdk.heartbeat</code> lifecycle 事件後送出。App idle 時仍有心跳但不多一個 timer；app 活躍時 heartbeat 被正常事件的 flush 取代（buffer 不會為空）。</p>
<p>Heartbeat 間隔由 SDK init config 的 <code>heartbeatInterval</code> 設定。設為 0 停用 heartbeat。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>離線場景的處理 → <a href="/blog/monitoring/03-sdk-design/offline-buffer/" data-link-title="離線 buffer 與重試" data-link-desc="網路不可用時的事件保存策略 — FIFO 丟棄、本地 persistence、恢復後補發的取捨">離線 buffer 與重試</a></li>
<li>SDK 公開 API → <a href="/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計</a></li>
<li>Collector 端如何接收批次事件 → <a href="/blog/monitoring/04-collector/" data-link-title="模組四：Collector 設計" data-link-desc="收 → 驗 → 存 → 查 → 觸發的完整鏈路 — Go 單一 binary、可插拔 Storage Backend、rule engine">模組四 Collector 架構</a></li>
</ul>
]]></content:encoded></item><item><title>離線 buffer 與重試</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/offline-buffer/</link><pubDate>Fri, 19 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/offline-buffer/</guid><description>&lt;p>離線 buffer 處理的是「事件產生時網路不可用」的場景。記憶體 buffer 有容量上限，離線時間超過 buffer 容量時需要決策：丟棄舊事件、持久化到本地儲存、或兩者混合。每種策略有不同的複雜度和資料保留量的取捨。&lt;/p>
&lt;h2 id="三種策略">三種策略&lt;/h2>
&lt;h3 id="fifo-丟棄最簡單">FIFO 丟棄（最簡單）&lt;/h3>
&lt;p>Buffer 滿時丟棄最舊的事件，保留最新的。整個 buffer 在記憶體中，不做本地 persistence。&lt;/p>
&lt;p>優點：實作最簡單（array + 容量檢查），不需要檔案系統存取，不增加磁碟 I/O。&lt;/p>
&lt;p>代價：離線超過 buffer 容量時，較舊的事件永久遺失。如果離線 30 分鐘、buffer 容量 200 筆、事件產生速率每分鐘 10 筆，前 100 筆（前 10 分鐘）的事件被丟棄。&lt;/p>
&lt;p>適合場景：自用工具（離線場景少、遺失部分事件影響低）、SDK 初期版本（先用最簡單的策略上線）。&lt;/p>
&lt;h3 id="本地-persistence最完整">本地 persistence（最完整）&lt;/h3>
&lt;p>Buffer 滿時把事件寫入本地檔案（SQLite、JSONL 檔案、SharedPreferences / UserDefaults）。網路恢復後從本地檔案讀取並補發。&lt;/p>
&lt;p>優點：離線期間的事件不會遺失（在本地儲存容量內）。&lt;/p>
&lt;p>代價：實作複雜度高 — 需要處理檔案讀寫、並發存取（多執行緒安全）、本地儲存容量管理（磁碟空間上限）、補發時的去重（同一筆事件可能已在記憶體 buffer 中被 flush 過）。&lt;/p>
&lt;p>適合場景：商業產品（使用者在地鐵、電梯、飛航模式下使用）、離線時間長且事件不可遺失的需求。&lt;/p>
&lt;h3 id="混合策略">混合策略&lt;/h3>
&lt;p>記憶體 buffer 處理正常情況和短暫離線。離線超過記憶體 buffer 容量時，溢出的事件寫入本地檔案。網路恢復後先 flush 記憶體 buffer（最新事件），再補發本地檔案中的事件（較舊事件）。&lt;/p>
&lt;p>混合策略的實作複雜度介於兩者之間。本地檔案只在溢出時使用，正常情況下不產生磁碟 I/O。&lt;/p>
&lt;h2 id="恢復後補發">恢復後補發&lt;/h2>
&lt;p>網路恢復後補發離線期間累積的事件，需要處理三個問題：&lt;/p>
&lt;h3 id="補發順序">補發順序&lt;/h3>
&lt;p>離線事件按 timestamp 順序補發，保持事件的時間順序。Collector 端收到的事件 timestamp 可能比當前時間早數小時 — 這是正常的離線補發，collector 應該根據事件的 timestamp 處理，不依賴收到時間。&lt;/p>
&lt;h3 id="補發速率">補發速率&lt;/h3>
&lt;p>一次送出大量離線事件可能讓 collector 過載。分批補發（每批 50-100 筆，間隔 1-2 秒），讓 collector 有時間處理。&lt;/p>
&lt;h3 id="去重">去重&lt;/h3>
&lt;p>同一筆事件可能同時存在於記憶體 buffer 和本地檔案中（寫入本地檔案時 buffer 中也有一份）。Collector 端用事件的唯一識別（timestamp + session_id + name 的組合，或 SDK 產生的 event_id UUID）做去重。&lt;/p>
&lt;h2 id="本地儲存容量管理">本地儲存容量管理&lt;/h2>
&lt;p>本地 persistence 需要設定磁碟使用上限。上限取決於事件大小和保留時間。&lt;/p>
&lt;p>以平均每筆事件 500 bytes 估算：&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>上限&lt;/th>
 &lt;th>可儲存事件數&lt;/th>
 &lt;th>備註&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>1 MB&lt;/td>
 &lt;td>~2,000&lt;/td>
 &lt;td>約 3 小時（每分鐘 10 筆）&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>10 MB&lt;/td>
 &lt;td>~20,000&lt;/td>
 &lt;td>約 33 小時&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>50 MB&lt;/td>
 &lt;td>~100,000&lt;/td>
 &lt;td>約 7 天&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;p>自用工具 1 MB 足夠（離線場景少）。行動 app 10-50 MB 合理（使用者可能整天離線）。超過上限時用 FIFO 丟棄最舊的本地檔案。&lt;/p>
&lt;h2 id="各平台的本地儲存路徑">各平台的本地儲存路徑&lt;/h2>
&lt;p>本地 persistence 的檔案路徑和格式因平台而異。MVP 階段全用記憶體 FIFO（最簡單策略），本地 persistence 標為第二階段。&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>平台&lt;/th>
 &lt;th>建議路徑&lt;/th>
 &lt;th>檔案格式&lt;/th>
 &lt;th>備註&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>Flutter&lt;/td>
 &lt;td>&lt;code>getApplicationSupportDirectory()&lt;/code>&lt;/td>
 &lt;td>JSONL&lt;/td>
 &lt;td>不會被 iCloud 備份（和 Documents 不同）、不會被系統自動清理&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>Python&lt;/td>
 &lt;td>&lt;code>~/.cache/monitor/&lt;/code> 或 &lt;code>platformdirs.user_cache_dir('monitor')&lt;/code>&lt;/td>
 &lt;td>JSONL&lt;/td>
 &lt;td>遵循 XDG 標準、&lt;code>platformdirs&lt;/code> 套件處理跨平台&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>JS/Web&lt;/td>
 &lt;td>&lt;code>localStorage&lt;/code> 或 &lt;code>IndexedDB&lt;/code>&lt;/td>
 &lt;td>JSON&lt;/td>
 &lt;td>localStorage 有 5MB 限制、IndexedDB 更大但 API 較複雜&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;p>App 被強制終止時（iOS 的 &lt;code>kill&lt;/code>、Android 的 process death），記憶體 buffer 中未 flush 的事件會遺失。Flutter 的 &lt;code>AppLifecycleState.detached&lt;/code> 不保證有時間執行 flush。接受這個遺失 — 強制終止是極端情境，下次啟動時 SDK 重新開始收集。&lt;/p></description><content:encoded><![CDATA[<p>離線 buffer 處理的是「事件產生時網路不可用」的場景。記憶體 buffer 有容量上限，離線時間超過 buffer 容量時需要決策：丟棄舊事件、持久化到本地儲存、或兩者混合。每種策略有不同的複雜度和資料保留量的取捨。</p>
<h2 id="三種策略">三種策略</h2>
<h3 id="fifo-丟棄最簡單">FIFO 丟棄（最簡單）</h3>
<p>Buffer 滿時丟棄最舊的事件，保留最新的。整個 buffer 在記憶體中，不做本地 persistence。</p>
<p>優點：實作最簡單（array + 容量檢查），不需要檔案系統存取，不增加磁碟 I/O。</p>
<p>代價：離線超過 buffer 容量時，較舊的事件永久遺失。如果離線 30 分鐘、buffer 容量 200 筆、事件產生速率每分鐘 10 筆，前 100 筆（前 10 分鐘）的事件被丟棄。</p>
<p>適合場景：自用工具（離線場景少、遺失部分事件影響低）、SDK 初期版本（先用最簡單的策略上線）。</p>
<h3 id="本地-persistence最完整">本地 persistence（最完整）</h3>
<p>Buffer 滿時把事件寫入本地檔案（SQLite、JSONL 檔案、SharedPreferences / UserDefaults）。網路恢復後從本地檔案讀取並補發。</p>
<p>優點：離線期間的事件不會遺失（在本地儲存容量內）。</p>
<p>代價：實作複雜度高 — 需要處理檔案讀寫、並發存取（多執行緒安全）、本地儲存容量管理（磁碟空間上限）、補發時的去重（同一筆事件可能已在記憶體 buffer 中被 flush 過）。</p>
<p>適合場景：商業產品（使用者在地鐵、電梯、飛航模式下使用）、離線時間長且事件不可遺失的需求。</p>
<h3 id="混合策略">混合策略</h3>
<p>記憶體 buffer 處理正常情況和短暫離線。離線超過記憶體 buffer 容量時，溢出的事件寫入本地檔案。網路恢復後先 flush 記憶體 buffer（最新事件），再補發本地檔案中的事件（較舊事件）。</p>
<p>混合策略的實作複雜度介於兩者之間。本地檔案只在溢出時使用，正常情況下不產生磁碟 I/O。</p>
<h2 id="恢復後補發">恢復後補發</h2>
<p>網路恢復後補發離線期間累積的事件，需要處理三個問題：</p>
<h3 id="補發順序">補發順序</h3>
<p>離線事件按 timestamp 順序補發，保持事件的時間順序。Collector 端收到的事件 timestamp 可能比當前時間早數小時 — 這是正常的離線補發，collector 應該根據事件的 timestamp 處理，不依賴收到時間。</p>
<h3 id="補發速率">補發速率</h3>
<p>一次送出大量離線事件可能讓 collector 過載。分批補發（每批 50-100 筆，間隔 1-2 秒），讓 collector 有時間處理。</p>
<h3 id="去重">去重</h3>
<p>同一筆事件可能同時存在於記憶體 buffer 和本地檔案中（寫入本地檔案時 buffer 中也有一份）。Collector 端用事件的唯一識別（timestamp + session_id + name 的組合，或 SDK 產生的 event_id UUID）做去重。</p>
<h2 id="本地儲存容量管理">本地儲存容量管理</h2>
<p>本地 persistence 需要設定磁碟使用上限。上限取決於事件大小和保留時間。</p>
<p>以平均每筆事件 500 bytes 估算：</p>
<table>
  <thead>
      <tr>
          <th>上限</th>
          <th>可儲存事件數</th>
          <th>備註</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>1 MB</td>
          <td>~2,000</td>
          <td>約 3 小時（每分鐘 10 筆）</td>
      </tr>
      <tr>
          <td>10 MB</td>
          <td>~20,000</td>
          <td>約 33 小時</td>
      </tr>
      <tr>
          <td>50 MB</td>
          <td>~100,000</td>
          <td>約 7 天</td>
      </tr>
  </tbody>
</table>
<p>自用工具 1 MB 足夠（離線場景少）。行動 app 10-50 MB 合理（使用者可能整天離線）。超過上限時用 FIFO 丟棄最舊的本地檔案。</p>
<h2 id="各平台的本地儲存路徑">各平台的本地儲存路徑</h2>
<p>本地 persistence 的檔案路徑和格式因平台而異。MVP 階段全用記憶體 FIFO（最簡單策略），本地 persistence 標為第二階段。</p>
<table>
  <thead>
      <tr>
          <th>平台</th>
          <th>建議路徑</th>
          <th>檔案格式</th>
          <th>備註</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Flutter</td>
          <td><code>getApplicationSupportDirectory()</code></td>
          <td>JSONL</td>
          <td>不會被 iCloud 備份（和 Documents 不同）、不會被系統自動清理</td>
      </tr>
      <tr>
          <td>Python</td>
          <td><code>~/.cache/monitor/</code> 或 <code>platformdirs.user_cache_dir('monitor')</code></td>
          <td>JSONL</td>
          <td>遵循 XDG 標準、<code>platformdirs</code> 套件處理跨平台</td>
      </tr>
      <tr>
          <td>JS/Web</td>
          <td><code>localStorage</code> 或 <code>IndexedDB</code></td>
          <td>JSON</td>
          <td>localStorage 有 5MB 限制、IndexedDB 更大但 API 較複雜</td>
      </tr>
  </tbody>
</table>
<p>App 被強制終止時（iOS 的 <code>kill</code>、Android 的 process death），記憶體 buffer 中未 flush 的事件會遺失。Flutter 的 <code>AppLifecycleState.detached</code> 不保證有時間執行 flush。接受這個遺失 — 強制終止是極端情境，下次啟動時 SDK 重新開始收集。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>攢批送出策略 → <a href="/blog/monitoring/03-sdk-design/batch-flush/" data-link-title="攢批送出策略" data-link-desc="flush interval / buffer size / flush on close 三個控制點決定事件何時離開 SDK — 平衡即時性和網路效率">攢批送出策略</a></li>
<li>SDK 端的資料脫敏 → <a href="/blog/monitoring/03-sdk-design/redaction-helper/" data-link-title="SDK redaction helper" data-link-desc="在事件離開 SDK 前移除敏感資訊 — 預設 redaction rule 處理常見 pattern，自訂 rule 處理業務特定的 secret">SDK redaction helper</a></li>
<li>Collector 端如何處理補發事件 → <a href="/blog/monitoring/04-collector/" data-link-title="模組四：Collector 設計" data-link-desc="收 → 驗 → 存 → 查 → 觸發的完整鏈路 — Go 單一 binary、可插拔 Storage Backend、rule engine">模組四 Collector 設計</a></li>
<li>從 SDK 到 storage 的端到端資料損失地圖 → <a href="/blog/monitoring/04-collector/data-integrity/" data-link-title="端到端資料完整性" data-link-desc="從 SDK 到 storage 的資料損失地圖 — 每個環節的損失類型、控制策略、完整性指標、被自己 SDK DDoS 的防護">端到端資料完整性</a></li>
</ul>
]]></content:encoded></item><item><title>SDK redaction helper</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/redaction-helper/</link><pubDate>Fri, 19 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/redaction-helper/</guid><description>&lt;p>SDK &lt;a href="https://tarrragon.github.io/blog/monitoring/knowledge-cards/redaction/" data-link-title="Redaction" data-link-desc="說明在事件資料離開 client 之前把敏感欄位的值替換成遮罩或移除的機制">redaction&lt;/a> helper 在事件離開 SDK（進入 HTTP POST payload）前掃描事件內容，把匹配敏感資訊 pattern 的欄位值替換為 &lt;code>[REDACTED]&lt;/code>。Redaction 在 SDK 端執行，確保敏感資訊不會經過網路傳輸到 collector — 即使 transport 層被攔截，攻擊者看到的也是脫敏後的資料。&lt;/p>
&lt;h2 id="預設-redaction-rule">預設 redaction rule&lt;/h2>
&lt;p>SDK 內建一組預設 rule，處理常見的敏感資訊 pattern：&lt;/p>
&lt;h3 id="密碼欄位">密碼欄位&lt;/h3>
&lt;p>匹配 data 物件中 key 包含 &lt;code>password&lt;/code>、&lt;code>passwd&lt;/code>、&lt;code>secret&lt;/code>、&lt;code>token&lt;/code>、&lt;code>api_key&lt;/code>、&lt;code>apiKey&lt;/code>、&lt;code>authorization&lt;/code> 的欄位。匹配方式是 key 名稱的子字串比對（case-insensitive）。&lt;/p>
&lt;h3 id="url-中的認證資訊">URL 中的認證資訊&lt;/h3>
&lt;p>匹配 &lt;code>https://user:password@host&lt;/code> 格式的 URL，把 &lt;code>user:password&lt;/code> 部分替換為 &lt;code>[REDACTED]&lt;/code>。&lt;/p>
&lt;h3 id="stack-trace-中的檔案路徑">Stack trace 中的檔案路徑&lt;/h3>
&lt;p>匹配 stack trace 字串中的使用者目錄路徑（&lt;code>/Users/username/&lt;/code>、&lt;code>/home/username/&lt;/code>、&lt;code>C:\Users\username\&lt;/code>），替換為 &lt;code>[USER_HOME]/&lt;/code>。避免使用者名稱從 stack trace 洩漏。&lt;/p>
&lt;h2 id="自訂-redaction-rule">自訂 redaction rule&lt;/h2>
&lt;p>業務特定的敏感資訊（信用卡號、身分證字號、醫療資料）不在預設 rule 的範圍內。SDK 提供 API 讓開發者在 init 時註冊自訂 rule。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-text" data-lang="text">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">Monitor.init({
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl"> redactionRules: [
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">3&lt;/span>&lt;span class="cl"> { pattern: /\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/, replace: &amp;#39;[CARD]&amp;#39; },
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">4&lt;/span>&lt;span class="cl"> { keyPattern: /^ssn$/i, replace: &amp;#39;[REDACTED]&amp;#39; },
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">5&lt;/span>&lt;span class="cl"> ],
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">6&lt;/span>&lt;span class="cl">})&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>自訂 rule 和預設 rule 一起執行。如果同一個值被多個 rule 匹配，第一個匹配的 rule 生效（rule 的執行順序：預設 rule 先，自訂 rule 後）。&lt;/p>
&lt;h2 id="redaction-的執行時機">Redaction 的執行時機&lt;/h2>
&lt;p>Redaction 在事件進入 flush payload 的那一刻執行 — buffer 中的事件保持原始內容，flush 時複製一份並在複製上執行 redaction。&lt;/p>
&lt;p>在 buffer 中保持原始內容的理由是 debug：開發者在本地 console 看到的 log 應該包含完整資訊（開發環境不需要脫敏），只有離開 SDK 時才脫敏。SDK 可以提供 &lt;code>debugMode&lt;/code> flag — debugMode 開啟時 console log 印出原始內容，HTTP POST 仍送出脫敏後的內容。&lt;/p>
&lt;h2 id="redaction-和模組七的關係">Redaction 和模組七的關係&lt;/h2>
&lt;p>SDK redaction helper 是&lt;a href="https://tarrragon.github.io/blog/monitoring/07-security-privacy/" data-link-title="模組七：資安與隱私" data-link-desc="SDK redaction / transport 加密 / collector access control / 去識別化 — 蒐集的資料本身就是風險資產">模組七 資安與隱私&lt;/a>中 redaction 策略的實作層。模組七定義「什麼資訊需要被保護」（策略），本章定義「SDK 如何在程式碼中實現這個保護」（實作）。&lt;/p>
&lt;p>兩者的分工：&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>層級&lt;/th>
 &lt;th>職責&lt;/th>
 &lt;th>定義在&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>策略層&lt;/td>
 &lt;td>哪些欄位需要 redaction、哪些 pattern 敏感&lt;/td>
 &lt;td>模組七&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>實作層&lt;/td>
 &lt;td>預設 rule、自訂 rule API、執行時機&lt;/td>
 &lt;td>本章&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>驗證層&lt;/td>
 &lt;td>確認脫敏後的事件不包含敏感資訊&lt;/td>
 &lt;td>collector 端&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;p>Collector 端可以做第二道檢查（re-scan 收到的事件是否仍包含敏感 pattern），作為 SDK 端 redaction 的備援。但主要的脫敏責任在 SDK 端 — 資料離開 SDK 後經過網路，已經暴露在傳輸風險中。&lt;/p>
&lt;h2 id="下一步路由">下一步路由&lt;/h2>
&lt;ul>
&lt;li>SDK 公開 API → &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計&lt;/a>&lt;/li>
&lt;li>資安與隱私的完整策略 → &lt;a href="https://tarrragon.github.io/blog/monitoring/07-security-privacy/" data-link-title="模組七：資安與隱私" data-link-desc="SDK redaction / transport 加密 / collector access control / 去識別化 — 蒐集的資料本身就是風險資產">模組七 資安與隱私&lt;/a>&lt;/li>
&lt;li>自動攔截的 error 也需要 redaction → &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制&lt;/a>&lt;/li>
&lt;/ul></description><content:encoded><![CDATA[<p>SDK <a href="/blog/monitoring/knowledge-cards/redaction/" data-link-title="Redaction" data-link-desc="說明在事件資料離開 client 之前把敏感欄位的值替換成遮罩或移除的機制">redaction</a> helper 在事件離開 SDK（進入 HTTP POST payload）前掃描事件內容，把匹配敏感資訊 pattern 的欄位值替換為 <code>[REDACTED]</code>。Redaction 在 SDK 端執行，確保敏感資訊不會經過網路傳輸到 collector — 即使 transport 層被攔截，攻擊者看到的也是脫敏後的資料。</p>
<h2 id="預設-redaction-rule">預設 redaction rule</h2>
<p>SDK 內建一組預設 rule，處理常見的敏感資訊 pattern：</p>
<h3 id="密碼欄位">密碼欄位</h3>
<p>匹配 data 物件中 key 包含 <code>password</code>、<code>passwd</code>、<code>secret</code>、<code>token</code>、<code>api_key</code>、<code>apiKey</code>、<code>authorization</code> 的欄位。匹配方式是 key 名稱的子字串比對（case-insensitive）。</p>
<h3 id="url-中的認證資訊">URL 中的認證資訊</h3>
<p>匹配 <code>https://user:password@host</code> 格式的 URL，把 <code>user:password</code> 部分替換為 <code>[REDACTED]</code>。</p>
<h3 id="stack-trace-中的檔案路徑">Stack trace 中的檔案路徑</h3>
<p>匹配 stack trace 字串中的使用者目錄路徑（<code>/Users/username/</code>、<code>/home/username/</code>、<code>C:\Users\username\</code>），替換為 <code>[USER_HOME]/</code>。避免使用者名稱從 stack trace 洩漏。</p>
<h2 id="自訂-redaction-rule">自訂 redaction rule</h2>
<p>業務特定的敏感資訊（信用卡號、身分證字號、醫療資料）不在預設 rule 的範圍內。SDK 提供 API 讓開發者在 init 時註冊自訂 rule。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Monitor.init({
</span></span><span class="line"><span class="ln">2</span><span class="cl">  redactionRules: [
</span></span><span class="line"><span class="ln">3</span><span class="cl">    { pattern: /\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/, replace: &#39;[CARD]&#39; },
</span></span><span class="line"><span class="ln">4</span><span class="cl">    { keyPattern: /^ssn$/i, replace: &#39;[REDACTED]&#39; },
</span></span><span class="line"><span class="ln">5</span><span class="cl">  ],
</span></span><span class="line"><span class="ln">6</span><span class="cl">})</span></span></code></pre></div><p>自訂 rule 和預設 rule 一起執行。如果同一個值被多個 rule 匹配，第一個匹配的 rule 生效（rule 的執行順序：預設 rule 先，自訂 rule 後）。</p>
<h2 id="redaction-的執行時機">Redaction 的執行時機</h2>
<p>Redaction 在事件進入 flush payload 的那一刻執行 — buffer 中的事件保持原始內容，flush 時複製一份並在複製上執行 redaction。</p>
<p>在 buffer 中保持原始內容的理由是 debug：開發者在本地 console 看到的 log 應該包含完整資訊（開發環境不需要脫敏），只有離開 SDK 時才脫敏。SDK 可以提供 <code>debugMode</code> flag — debugMode 開啟時 console log 印出原始內容，HTTP POST 仍送出脫敏後的內容。</p>
<h2 id="redaction-和模組七的關係">Redaction 和模組七的關係</h2>
<p>SDK redaction helper 是<a href="/blog/monitoring/07-security-privacy/" data-link-title="模組七：資安與隱私" data-link-desc="SDK redaction / transport 加密 / collector access control / 去識別化 — 蒐集的資料本身就是風險資產">模組七 資安與隱私</a>中 redaction 策略的實作層。模組七定義「什麼資訊需要被保護」（策略），本章定義「SDK 如何在程式碼中實現這個保護」（實作）。</p>
<p>兩者的分工：</p>
<table>
  <thead>
      <tr>
          <th>層級</th>
          <th>職責</th>
          <th>定義在</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>策略層</td>
          <td>哪些欄位需要 redaction、哪些 pattern 敏感</td>
          <td>模組七</td>
      </tr>
      <tr>
          <td>實作層</td>
          <td>預設 rule、自訂 rule API、執行時機</td>
          <td>本章</td>
      </tr>
      <tr>
          <td>驗證層</td>
          <td>確認脫敏後的事件不包含敏感資訊</td>
          <td>collector 端</td>
      </tr>
  </tbody>
</table>
<p>Collector 端可以做第二道檢查（re-scan 收到的事件是否仍包含敏感 pattern），作為 SDK 端 redaction 的備援。但主要的脫敏責任在 SDK 端 — 資料離開 SDK 後經過網路，已經暴露在傳輸風險中。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>SDK 公開 API → <a href="/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計</a></li>
<li>資安與隱私的完整策略 → <a href="/blog/monitoring/07-security-privacy/" data-link-title="模組七：資安與隱私" data-link-desc="SDK redaction / transport 加密 / collector access control / 去識別化 — 蒐集的資料本身就是風險資產">模組七 資安與隱私</a></li>
<li>自動攔截的 error 也需要 redaction → <a href="/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制</a></li>
</ul>
]]></content:encoded></item><item><title>前端感測器設計</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/frontend-sensor-design/</link><pubDate>Sat, 20 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/frontend-sensor-design/</guid><description>&lt;p>感測器是 SDK 主動偵測使用者行為的元件。和 &lt;a href="https://tarrragon.github.io/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制&lt;/a> 的被動攔截不同 — auto-intercept 攔截的是系統級事件（uncaught exception、unhandled rejection），感測器偵測的是業務級行為（使用者點了什麼、看了哪個畫面、操作花了多久）。兩者互補：auto-intercept 提供 error 和 lifecycle 的基礎層，感測器提供 event 和 metric 的業務層。&lt;/p>
&lt;h2 id="點擊觸碰感測器">點擊/觸碰感測器&lt;/h2>
&lt;p>點擊感測器偵測使用者和 UI 元素的互動 — 按鈕點擊、連結觸碰、選單選擇。每次互動產生一個 event 類型的事件。&lt;/p>
&lt;h3 id="哪些元素值得追蹤">哪些元素值得追蹤&lt;/h3>
&lt;p>追蹤粒度的判斷依據是「這個互動是否對應一個有意義的使用者意圖」。&lt;/p>
&lt;p>有意義的互動（值得追蹤）：提交表單、點擊導航按鈕、觸發功能操作（連線、配對、匯出）。這些互動對應使用者的明確意圖，是 &lt;a href="https://tarrragon.github.io/blog/monitoring/08-business-analytics/funnel-analysis/" data-link-title="Funnel Analysis" data-link-desc="使用者在哪一步流失 — 從事件序列計算每步轉換率、找出流失最嚴重的步驟、區分設計問題和技術問題">funnel 分析&lt;/a> 的步驟候選。&lt;/p>
&lt;p>低價值的互動（通常不追蹤）：滾動、hover、重複的相同操作（每秒多次的按鈕連按）。這些互動要麼太頻繁（滾動每秒觸發數十次），要麼不代表新的使用者意圖。&lt;/p>
&lt;h3 id="實作方式">實作方式&lt;/h3>
&lt;p>&lt;strong>Web（JS/TS）&lt;/strong>：在 document 層級用 event delegation 攔截 click 事件，過濾出帶 &lt;code>data-track&lt;/code> attribute 的元素。開發者在需要追蹤的元素上加 &lt;code>data-track=&amp;quot;connect-button&amp;quot;&lt;/code>，感測器自動收集。不追蹤所有 click — 只追蹤被標記的。&lt;/p>
&lt;p>&lt;strong>Flutter&lt;/strong>：用 NavigatorObserver 或 custom GestureDetector wrapper。GestureDetector 包裝在需要追蹤的 widget 外層，onTap 觸發時送出事件。&lt;/p>
&lt;h3 id="效能影響">效能影響&lt;/h3>
&lt;p>Event delegation 在 document 層級只有一個 listener，效能影響接近零。瓶頸在事件產生頻率 — 如果追蹤了高頻操作（每秒多次的滑動），事件進入 buffer 的速度可能超過 flush 的速度。用取樣控制（見本章末段）。&lt;/p>
&lt;h2 id="導航路由感測器">導航/路由感測器&lt;/h2>
&lt;p>導航感測器偵測使用者在不同畫面之間的切換 — page view、screen view、route change。每次切換產生一個 lifecycle 類型的事件。&lt;/p>
&lt;h3 id="平台差異">平台差異&lt;/h3>
&lt;p>&lt;strong>Web SPA&lt;/strong>：SPA 的 route 變換不觸發頁面載入，需要主動偵測 URL 變化。兩種偵測方式：&lt;/p>
&lt;ul>
&lt;li>History API 攔截：覆寫 &lt;code>pushState&lt;/code> / &lt;code>replaceState&lt;/code>，攔截 &lt;code>popstate&lt;/code> 事件&lt;/li>
&lt;li>框架層級 Hook：React Router 的 &lt;code>useLocation&lt;/code>、Vue Router 的 &lt;code>afterEach&lt;/code> guard&lt;/li>
&lt;/ul>
&lt;p>History API 攔截是 SDK 層的通用做法（不依賴框架）；框架 Hook 更精確但需要使用者整合（見 &lt;a href="https://tarrragon.github.io/blog/monitoring/05-platform-adaptation/js-ts-platform/" data-link-title="JS/TS 平台適配" data-link-desc="CORS 限制、Service Worker 攔截、SPA 路由變換偵測 — 瀏覽器環境中 SDK 需要處理的平台特殊問題">JS/TS 平台&lt;/a> 的 SPA 路由段）。&lt;/p>
&lt;p>&lt;strong>Flutter&lt;/strong>：用 &lt;code>NavigatorObserver&lt;/code> 的 &lt;code>didPush&lt;/code> / &lt;code>didPop&lt;/code> / &lt;code>didReplace&lt;/code> 回呼。每次路由變化自動觸發，不需要使用者在每個頁面手動埋點。&lt;/p>
&lt;p>&lt;strong>Python CLI/Hook&lt;/strong>：沒有「畫面切換」的概念。對應的 lifecycle 事件是 &lt;code>hook.start&lt;/code> / &lt;code>hook.complete&lt;/code> — 每個 Hook 執行視為一個「畫面」。&lt;/p>
&lt;h3 id="事件-schema">事件 schema&lt;/h3>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-json" data-lang="json">&lt;span class="line">&lt;span class="ln">1&lt;/span>&lt;span class="cl">&lt;span class="p">{&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">2&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;type&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;lifecycle&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">3&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;name&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;screen.view&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">4&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;data&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="p">{&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">5&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;screen_name&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;TerminalScreen&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">6&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;previous_screen&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;HomeScreen&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">7&lt;/span>&lt;span class="cl"> &lt;span class="nt">&amp;#34;navigation_method&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;push&amp;#34;&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">8&lt;/span>&lt;span class="cl"> &lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">9&lt;/span>&lt;span class="cl">&lt;span class="p">}&lt;/span>&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>&lt;code>navigation_method&lt;/code>（push / pop / replace / go）記錄導航方式，和 &lt;a href="https://tarrragon.github.io/blog/ux-design/05-navigation-patterns/go-push-semantics/" data-link-title="go vs push vs pushReplacement 的 UX 語意表" data-link-desc="三種導航方法對堆疊、back 行為、使用者心理模型的影響 — 選擇依據是使用者的意圖而非技術方便">go vs push 的 UX 語意&lt;/a> 對應。&lt;/p>
&lt;h2 id="錯誤邊界感測器">錯誤邊界感測器&lt;/h2>
&lt;p>錯誤邊界感測器攔截元件級的 error — 和 auto-intercept 的全域 error 攔截互補。&lt;/p></description><content:encoded><![CDATA[<p>感測器是 SDK 主動偵測使用者行為的元件。和 <a href="/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制</a> 的被動攔截不同 — auto-intercept 攔截的是系統級事件（uncaught exception、unhandled rejection），感測器偵測的是業務級行為（使用者點了什麼、看了哪個畫面、操作花了多久）。兩者互補：auto-intercept 提供 error 和 lifecycle 的基礎層，感測器提供 event 和 metric 的業務層。</p>
<h2 id="點擊觸碰感測器">點擊/觸碰感測器</h2>
<p>點擊感測器偵測使用者和 UI 元素的互動 — 按鈕點擊、連結觸碰、選單選擇。每次互動產生一個 event 類型的事件。</p>
<h3 id="哪些元素值得追蹤">哪些元素值得追蹤</h3>
<p>追蹤粒度的判斷依據是「這個互動是否對應一個有意義的使用者意圖」。</p>
<p>有意義的互動（值得追蹤）：提交表單、點擊導航按鈕、觸發功能操作（連線、配對、匯出）。這些互動對應使用者的明確意圖，是 <a href="/blog/monitoring/08-business-analytics/funnel-analysis/" data-link-title="Funnel Analysis" data-link-desc="使用者在哪一步流失 — 從事件序列計算每步轉換率、找出流失最嚴重的步驟、區分設計問題和技術問題">funnel 分析</a> 的步驟候選。</p>
<p>低價值的互動（通常不追蹤）：滾動、hover、重複的相同操作（每秒多次的按鈕連按）。這些互動要麼太頻繁（滾動每秒觸發數十次），要麼不代表新的使用者意圖。</p>
<h3 id="實作方式">實作方式</h3>
<p><strong>Web（JS/TS）</strong>：在 document 層級用 event delegation 攔截 click 事件，過濾出帶 <code>data-track</code> attribute 的元素。開發者在需要追蹤的元素上加 <code>data-track=&quot;connect-button&quot;</code>，感測器自動收集。不追蹤所有 click — 只追蹤被標記的。</p>
<p><strong>Flutter</strong>：用 NavigatorObserver 或 custom GestureDetector wrapper。GestureDetector 包裝在需要追蹤的 widget 外層，onTap 觸發時送出事件。</p>
<h3 id="效能影響">效能影響</h3>
<p>Event delegation 在 document 層級只有一個 listener，效能影響接近零。瓶頸在事件產生頻率 — 如果追蹤了高頻操作（每秒多次的滑動），事件進入 buffer 的速度可能超過 flush 的速度。用取樣控制（見本章末段）。</p>
<h2 id="導航路由感測器">導航/路由感測器</h2>
<p>導航感測器偵測使用者在不同畫面之間的切換 — page view、screen view、route change。每次切換產生一個 lifecycle 類型的事件。</p>
<h3 id="平台差異">平台差異</h3>
<p><strong>Web SPA</strong>：SPA 的 route 變換不觸發頁面載入，需要主動偵測 URL 變化。兩種偵測方式：</p>
<ul>
<li>History API 攔截：覆寫 <code>pushState</code> / <code>replaceState</code>，攔截 <code>popstate</code> 事件</li>
<li>框架層級 Hook：React Router 的 <code>useLocation</code>、Vue Router 的 <code>afterEach</code> guard</li>
</ul>
<p>History API 攔截是 SDK 層的通用做法（不依賴框架）；框架 Hook 更精確但需要使用者整合（見 <a href="/blog/monitoring/05-platform-adaptation/js-ts-platform/" data-link-title="JS/TS 平台適配" data-link-desc="CORS 限制、Service Worker 攔截、SPA 路由變換偵測 — 瀏覽器環境中 SDK 需要處理的平台特殊問題">JS/TS 平台</a> 的 SPA 路由段）。</p>
<p><strong>Flutter</strong>：用 <code>NavigatorObserver</code> 的 <code>didPush</code> / <code>didPop</code> / <code>didReplace</code> 回呼。每次路由變化自動觸發，不需要使用者在每個頁面手動埋點。</p>
<p><strong>Python CLI/Hook</strong>：沒有「畫面切換」的概念。對應的 lifecycle 事件是 <code>hook.start</code> / <code>hook.complete</code> — 每個 Hook 執行視為一個「畫面」。</p>
<h3 id="事件-schema">事件 schema</h3>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="ln">1</span><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">  <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;lifecycle&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">  <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;screen.view&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl">  <span class="nt">&#34;data&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">5</span><span class="cl">    <span class="nt">&#34;screen_name&#34;</span><span class="p">:</span> <span class="s2">&#34;TerminalScreen&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">6</span><span class="cl">    <span class="nt">&#34;previous_screen&#34;</span><span class="p">:</span> <span class="s2">&#34;HomeScreen&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">7</span><span class="cl">    <span class="nt">&#34;navigation_method&#34;</span><span class="p">:</span> <span class="s2">&#34;push&#34;</span>
</span></span><span class="line"><span class="ln">8</span><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="ln">9</span><span class="cl"><span class="p">}</span></span></span></code></pre></div><p><code>navigation_method</code>（push / pop / replace / go）記錄導航方式，和 <a href="/blog/ux-design/05-navigation-patterns/go-push-semantics/" data-link-title="go vs push vs pushReplacement 的 UX 語意表" data-link-desc="三種導航方法對堆疊、back 行為、使用者心理模型的影響 — 選擇依據是使用者的意圖而非技術方便">go vs push 的 UX 語意</a> 對應。</p>
<h2 id="錯誤邊界感測器">錯誤邊界感測器</h2>
<p>錯誤邊界感測器攔截元件級的 error — 和 auto-intercept 的全域 error 攔截互補。</p>
<h3 id="和-auto-intercept-的職責分工">和 auto-intercept 的職責分工</h3>
<table>
  <thead>
      <tr>
          <th>層級</th>
          <th>機制</th>
          <th>攔截什麼</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>全域</td>
          <td>auto-intercept（<code>window.onerror</code> / <code>FlutterError.onError</code>）</td>
          <td>uncaught exception、未處理的 Promise rejection</td>
      </tr>
      <tr>
          <td>元件</td>
          <td>錯誤邊界感測器（React ErrorBoundary / Flutter Widget error handler）</td>
          <td>元件渲染失敗、子樹 error</td>
      </tr>
  </tbody>
</table>
<p>全域攔截捕獲「逃逸到頂層的 error」，錯誤邊界捕獲「在元件層級就被攔住的 error」。如果一個 error 被元件的 ErrorBoundary 捕獲，它不會觸發 <code>window.onerror</code> — auto-intercept 看不到它。錯誤邊界感測器填補這個缺口。</p>
<h3 id="實作方式-1">實作方式</h3>
<p><strong>React</strong>：ErrorBoundary 元件的 <code>componentDidCatch</code> 回呼中呼叫 <code>monitor.error()</code>。</p>
<p><strong>Flutter</strong>：在 Widget 層用 <code>ErrorWidget.builder</code> 或自訂的 error handling widget。</p>
<h3 id="額外-context">額外 context</h3>
<p>錯誤邊界感測器比全域攔截多一個 context — 知道 error 發生在哪個元件（component name / widget name）。這個資訊在 error 的 data schema 中記錄為 <code>component</code> 欄位。</p>
<h2 id="效能標記感測器">效能標記感測器</h2>
<p>效能標記感測器量測操作的延遲和系統的渲染表現。產生 metric 類型的事件。</p>
<h3 id="web-core-vitals">Web Core Vitals</h3>
<p>Web 平台用 <code>PerformanceObserver</code> API 自動收集三個核心指標：</p>
<ul>
<li><strong>LCP</strong>（Largest Contentful Paint）：最大內容元素的載入時間</li>
<li><strong>FID</strong>（First Input Delay）：首次互動的延遲</li>
<li><strong>CLS</strong>（Cumulative Layout Shift）：累計佈局位移分數</li>
</ul>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-javascript" data-lang="javascript"><span class="line"><span class="ln">1</span><span class="cl"><span class="k">new</span> <span class="nx">PerformanceObserver</span><span class="p">((</span><span class="nx">list</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">  <span class="k">for</span> <span class="p">(</span><span class="kr">const</span> <span class="nx">entry</span> <span class="k">of</span> <span class="nx">list</span><span class="p">.</span><span class="nx">getEntries</span><span class="p">())</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">    <span class="nx">monitor</span><span class="p">.</span><span class="nx">metric</span><span class="p">(</span><span class="sb">`web.vitals.</span><span class="si">${</span><span class="nx">entry</span><span class="p">.</span><span class="nx">entryType</span><span class="si">}</span><span class="sb">`</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl">      <span class="nx">value</span><span class="o">:</span> <span class="nx">entry</span><span class="p">.</span><span class="nx">startTime</span> <span class="o">||</span> <span class="nx">entry</span><span class="p">.</span><span class="nx">value</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">5</span><span class="cl">      <span class="nx">url</span><span class="o">:</span> <span class="nx">location</span><span class="p">.</span><span class="nx">pathname</span>
</span></span><span class="line"><span class="ln">6</span><span class="cl">    <span class="p">});</span>
</span></span><span class="line"><span class="ln">7</span><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="ln">8</span><span class="cl"><span class="p">}).</span><span class="nx">observe</span><span class="p">({</span> <span class="nx">type</span><span class="o">:</span> <span class="s1">&#39;largest-contentful-paint&#39;</span><span class="p">,</span> <span class="nx">buffered</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span></span></span></code></pre></div><p>實務上依 entryType 分別取值（LCP 用 <code>startTime</code>、CLS 用 <code>value</code>、FID 用 <code>processingStart - startTime</code>），上述範例簡化示意。</p>
<h3 id="flutter-frame-timing">Flutter frame timing</h3>
<p>Flutter 用 <code>SchedulerBinding.addTimingsCallback</code> 偵測掉幀：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-dart" data-lang="dart"><span class="line"><span class="ln"> 1</span><span class="cl"><span class="n">SchedulerBinding</span><span class="p">.</span><span class="n">instance</span><span class="p">.</span><span class="n">addTimingsCallback</span><span class="p">((</span><span class="n">timings</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln"> 2</span><span class="cl">  <span class="k">for</span> <span class="p">(</span><span class="kd">final</span> <span class="n">t</span> <span class="k">in</span> <span class="n">timings</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln"> 3</span><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">t</span><span class="p">.</span><span class="n">totalSpan</span> <span class="o">&gt;</span> <span class="kd">const</span> <span class="n">Duration</span><span class="p">(</span><span class="nl">milliseconds:</span> <span class="m">16</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln"> 4</span><span class="cl">      <span class="n">monitor</span><span class="p">.</span><span class="n">metric</span><span class="p">(</span><span class="s1">&#39;render.frame_drop&#39;</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln"> 5</span><span class="cl">        <span class="s1">&#39;build_ms&#39;</span><span class="o">:</span> <span class="n">t</span><span class="p">.</span><span class="n">buildDuration</span><span class="p">.</span><span class="n">inMilliseconds</span><span class="p">,</span>
</span></span><span class="line"><span class="ln"> 6</span><span class="cl">        <span class="s1">&#39;raster_ms&#39;</span><span class="o">:</span> <span class="n">t</span><span class="p">.</span><span class="n">rasterDuration</span><span class="p">.</span><span class="n">inMilliseconds</span><span class="p">,</span>
</span></span><span class="line"><span class="ln"> 7</span><span class="cl">      <span class="p">});</span>
</span></span><span class="line"><span class="ln"> 8</span><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="ln"> 9</span><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="ln">10</span><span class="cl"><span class="p">});</span></span></span></code></pre></div><p>16ms 是 60fps 的單幀預算。超過代表掉幀。</p>
<h3 id="自訂-duration-量測">自訂 duration 量測</h3>
<p>業務操作的延遲用手動標記量測：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-dart" data-lang="dart"><span class="line"><span class="ln">1</span><span class="cl"><span class="kd">final</span> <span class="n">stopwatch</span> <span class="o">=</span> <span class="n">Stopwatch</span><span class="p">()..</span><span class="n">start</span><span class="p">();</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl"><span class="kd">await</span> <span class="n">connectToTerminal</span><span class="p">();</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl"><span class="n">stopwatch</span><span class="p">.</span><span class="n">stop</span><span class="p">();</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl"><span class="n">monitor</span><span class="p">.</span><span class="n">metric</span><span class="p">(</span><span class="s1">&#39;terminal.connect.duration&#39;</span><span class="p">,</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">5</span><span class="cl">  <span class="s1">&#39;duration_ms&#39;</span><span class="o">:</span> <span class="n">stopwatch</span><span class="p">.</span><span class="n">elapsedMilliseconds</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">6</span><span class="cl"><span class="p">});</span></span></span></code></pre></div><h2 id="輸入敏感度感測器">輸入敏感度感測器</h2>
<p>輸入敏感度感測器偵測使用者正在輸入敏感資料 — 密碼欄位、API key 輸入、信用卡號碼。這個感測器的責任是<strong>觸發 redaction，而非記錄輸入內容</strong>。</p>
<h3 id="偵測邏輯">偵測邏輯</h3>
<p><strong>Web</strong>：偵測 <code>&lt;input type=&quot;password&quot;&gt;</code>、帶有 <code>autocomplete=&quot;cc-number&quot;</code> 或 <code>data-sensitive</code> attribute 的欄位。當使用者 focus 這些欄位時，標記當前 session 進入「敏感輸入模式」— 後續的事件自動加嚴 <a href="/blog/monitoring/knowledge-cards/redaction/" data-link-title="Redaction" data-link-desc="說明在事件資料離開 client 之前把敏感欄位的值替換成遮罩或移除的機制">redaction</a> 規則（例如暫停記錄按鍵事件）。</p>
<p><strong>Flutter</strong>：偵測 <code>TextField</code> 的 <code>obscureText: true</code> 或 <code>enableIMEPersonalizedLearning: false</code>（見 <a href="/blog/ux-design/03-input-mechanism/ime-security-checklist/" data-link-title="安全敏感輸入框的 IME 控制 checklist" data-link-desc="處理密碼、API key、伺服器路徑等 secret 的輸入框需要關閉 IME 的個人化學習和自動校正 — 安全要求而非 UX 偏好">安全敏感輸入框的 IME 控制</a>）。</p>
<h3 id="不記錄的原則">不記錄的原則</h3>
<p>輸入敏感度感測器偵測「使用者正在輸入敏感內容」這個事實，但不記錄輸入的內容本身。送出的事件只包含：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="ln">1</span><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">  <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;lifecycle&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">  <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;input.sensitive_mode.entered&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl">  <span class="nt">&#34;data&#34;</span><span class="p">:</span> <span class="p">{</span> <span class="nt">&#34;field_type&#34;</span><span class="p">:</span> <span class="s2">&#34;password&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="ln">5</span><span class="cl"><span class="p">}</span></span></span></code></pre></div><h2 id="取樣策略設計">取樣策略設計</h2>
<p>感測器產生的事件量可能很大（效能標記每 30 秒一筆 × 活躍使用者數）。取樣控制事件量、避免 SDK 和 collector 的資源壓力。</p>
<h3 id="三種取樣模式">三種取樣模式</h3>
<p><strong>全收</strong>：每筆事件都送出。適合事件量低且每筆都有價值的類型 — error（每筆都可能是新 bug）、lifecycle 狀態轉換（量低）、認證失敗（安全敏感）。</p>
<p><strong>百分比取樣</strong>：隨機丟棄一定比例的事件。適合高頻的效能和行為事件。取樣率由 SDK config 控制：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="ln">1</span><span class="cl"><span class="nt">sensors</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln">2</span><span class="cl"><span class="w">  </span><span class="nt">metric</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln">3</span><span class="cl"><span class="w">    </span><span class="nt">render.frame_drop</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">sampling</span><span class="p">:</span><span class="w"> </span><span class="m">0.1</span><span class="w"> </span>}<span class="w">    </span><span class="c"># 只收 10%</span><span class="w">
</span></span></span><span class="line"><span class="ln">4</span><span class="cl"><span class="w">    </span><span class="nt">resource.memory</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">sampling</span><span class="p">:</span><span class="w"> </span><span class="m">0.5</span><span class="w"> </span>}<span class="w">       </span><span class="c"># 收 50%</span><span class="w">
</span></span></span><span class="line"><span class="ln">5</span><span class="cl"><span class="w">  </span><span class="nt">event</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln">6</span><span class="cl"><span class="w">    </span><span class="nt">feature.*.used</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">sampling</span><span class="p">:</span><span class="w"> </span><span class="m">1.0</span><span class="w"> </span>}<span class="w">        </span><span class="c"># 全收</span><span class="w">
</span></span></span><span class="line"><span class="ln">7</span><span class="cl"><span class="w">    </span><span class="nt">click.*</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">sampling</span><span class="p">:</span><span class="w"> </span><span class="m">0.1</span><span class="w"> </span>}<span class="w">               </span><span class="c"># 只收 10%</span></span></span></code></pre></div><p>百分比取樣的代價是低機率事件可能被漏掉（取樣 10% 時、發生 5 次的事件可能一次都沒收到）。</p>
<p><strong>條件取樣</strong>：正常情況下取樣、特定條件下全收。適合「平時不需要全量但問題發生時需要完整資料」的場景。例：正常 session 取樣 10%、但 session 內發生 error 後、該 session 剩餘事件全收（error session 的完整 context 比正常 session 更有價值）。</p>
<h3 id="取樣率的管理">取樣率的管理</h3>
<p>取樣率可以從三個層級設定：</p>
<table>
  <thead>
      <tr>
          <th>層級</th>
          <th>設定方式</th>
          <th>適用場景</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>SDK 本地 config</td>
          <td>隨 app 版本部署</td>
          <td>固定的基線取樣率</td>
      </tr>
      <tr>
          <td>Collector 下發</td>
          <td>SDK 啟動時從 collector 取得 config</td>
          <td>動態調整、不需要重新部署 app</td>
      </tr>
      <tr>
          <td>Feature flag 服務</td>
          <td>整合 LaunchDarkly / Unleash</td>
          <td>實驗期間對特定群組調整取樣</td>
      </tr>
  </tbody>
</table>
<p>三個層級由上到下優先順序遞增 — feature flag 覆蓋 collector config、collector config 覆蓋本地 config。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>動機驅動的事件設計（哪些動機需要哪些感測器） → <a href="/blog/monitoring/01-mental-model/motivation-to-event-mapping/" data-link-title="動機驅動的事件設計" data-link-desc="Debug / 商業 / 資安 / 效能四個動機各自需要什麼事件 — 從「為什麼收」反推「收什麼」和「什麼階段啟用」">動機驅動的事件設計</a></li>
<li>感測器的啟停控制和生命週期 → <a href="/blog/monitoring/03-sdk-design/sensor-lifecycle-management/" data-link-title="感測器生命週期管理" data-link-desc="產品生命週期的五個階段各啟用什麼感測器 — feature flag 整合、取樣率動態調整、感測器開關的可觀察性">感測器生命週期管理</a></li>
<li>被動攔截機制（和感測器互補） → <a href="/blog/monitoring/03-sdk-design/auto-intercept/" data-link-title="自動攔截機制" data-link-desc="JS window.onerror / Flutter FlutterError.onError / Python sys.excepthook — 各平台攔截未捕獲例外的機制和限制">自動攔截機制</a></li>
<li>安全敏感輸入的完整 checklist → <a href="/blog/ux-design/03-input-mechanism/ime-security-checklist/" data-link-title="安全敏感輸入框的 IME 控制 checklist" data-link-desc="處理密碼、API key、伺服器路徑等 secret 的輸入框需要關閉 IME 的個人化學習和自動校正 — 安全要求而非 UX 偏好">安全敏感輸入框的 IME 控制</a></li>
</ul>
]]></content:encoded></item><item><title>感測器生命週期管理</title><link>https://tarrragon.github.io/blog/monitoring/03-sdk-design/sensor-lifecycle-management/</link><pubDate>Sat, 20 Jun 2026 00:00:00 +0000</pubDate><guid>https://tarrragon.github.io/blog/monitoring/03-sdk-design/sensor-lifecycle-management/</guid><description>&lt;p>感測器的啟用組合隨產品階段變化。早期開發只需要 error 和 lifecycle 幫助 debug，production 上線後需要商業事件和效能量測，A/B 測試期間需要實驗專用感測器。把所有感測器一次全開會浪費頻寬和儲存、產生大量低價值事件；全程只開 error 則在需要行為分析時發現沒有資料。感測器的啟停是設計決策，由 SDK config、collector 下發和 feature flag 三層機制控制。&lt;/p>
&lt;h2 id="五個階段">五個階段&lt;/h2>
&lt;h3 id="早期開發">早期開發&lt;/h3>
&lt;p>開發期的首要需求是 debug — 程式碼寫完跑起來、出問題時能定位。&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>感測器類型&lt;/th>
 &lt;th>啟用&lt;/th>
 &lt;th>理由&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>error&lt;/td>
 &lt;td>全開&lt;/td>
 &lt;td>每個例外都要看到&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>lifecycle&lt;/td>
 &lt;td>全開&lt;/td>
 &lt;td>app 啟動、連線、狀態轉換的步驟紀錄&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>event&lt;/td>
 &lt;td>按需&lt;/td>
 &lt;td>正在開發的功能手動加埋點，其他關閉&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>metric&lt;/td>
 &lt;td>關閉&lt;/td>
 &lt;td>效能量測在功能穩定前沒有意義&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;p>開發期的取樣率全部設 1.0（全收）— 事件量極低（開發者自己操作），不需要取樣。&lt;/p>
&lt;h3 id="功能測試">功能測試&lt;/h3>
&lt;p>針對被測功能開啟完整感測器，驗證功能的行為事件和效能指標是否正確觸發。&lt;/p>
&lt;p>被測功能的 event 和 metric 全開。其他功能維持開發期設定。測試期間的感測器設定通常由測試 config 檔覆寫 SDK 預設值。&lt;/p>
&lt;h3 id="production-上線">Production 上線&lt;/h3>
&lt;p>上線後的感測器組合平衡覆蓋率和成本：&lt;/p>
&lt;table>
 &lt;thead>
 &lt;tr>
 &lt;th>感測器類型&lt;/th>
 &lt;th>策略&lt;/th>
 &lt;th>理由&lt;/th>
 &lt;/tr>
 &lt;/thead>
 &lt;tbody>
 &lt;tr>
 &lt;td>error&lt;/td>
 &lt;td>全收&lt;/td>
 &lt;td>每個 production error 都有 debug 價值&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>lifecycle&lt;/td>
 &lt;td>全收&lt;/td>
 &lt;td>session 分析和環境資訊需要完整紀錄&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>event（核心操作）&lt;/td>
 &lt;td>全收&lt;/td>
 &lt;td>漏斗關鍵步驟、轉換事件不能漏&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>event（高頻 UI）&lt;/td>
 &lt;td>取樣&lt;/td>
 &lt;td>scroll、mousemove、hover 等高頻操作只取部分&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>metric&lt;/td>
 &lt;td>取樣&lt;/td>
 &lt;td>效能指標按時間取樣（每 30 秒一次而非每 frame）&lt;/td>
 &lt;/tr>
 &lt;tr>
 &lt;td>安全事件&lt;/td>
 &lt;td>全收&lt;/td>
 &lt;td>auth 失敗、權限越界、敏感操作不取樣&lt;/td>
 &lt;/tr>
 &lt;/tbody>
&lt;/table>
&lt;h3 id="ab-測試">A/B 測試&lt;/h3>
&lt;p>實驗感測器只對 treatment group 啟用。Control group 不觸發實驗事件，避免污染對照組資料。&lt;/p>
&lt;p>實驗專用事件（&lt;code>experiment.pricing_test.assigned&lt;/code>、&lt;code>experiment.pricing_test.converted&lt;/code>）由 feature flag 控制 — flag 開啟時 SDK 才送這些事件。實驗結束後 flag 關閉，感測器自動停止。&lt;/p>
&lt;p>實驗事件的保留期和實驗週期綁定，實驗結束 + 分析完成後可以 purge。&lt;/p>
&lt;h3 id="功能下線">功能下線&lt;/h3>
&lt;p>功能移除時，對應的感測器 config 一起移除。Collector 端 purge 該功能的歷史事件（或降級到聚合摘要）。&lt;/p>
&lt;p>移除 checklist：SDK config 移除事件名稱 → SDK 版本部署 → 確認 collector 不再收到該事件 → purge 歷史資料（可選）。&lt;/p>
&lt;h2 id="控制機制">控制機制&lt;/h2>
&lt;p>三層控制機制各自適合不同的變更頻率：&lt;/p>
&lt;h3 id="sdk-init-config靜態">SDK init config（靜態）&lt;/h3>
&lt;p>隨 app 版本部署的本地設定檔。變更需要發新版本。適合穩定的感測器組合。&lt;/p>





&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-yaml" data-lang="yaml">&lt;span class="line">&lt;span class="ln"> 1&lt;/span>&lt;span class="cl">&lt;span class="nt">sensors&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 2&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">error&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled: true, sampling&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="m">1.0&lt;/span>&lt;span class="w"> &lt;/span>}&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 3&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">lifecycle&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled: true, sampling&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="m">1.0&lt;/span>&lt;span class="w"> &lt;/span>}&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 4&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">event&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 5&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">funnel.*&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled: true, sampling&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="m">1.0&lt;/span>&lt;span class="w"> &lt;/span>}&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 6&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">click.*&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled: true, sampling&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="m">0.1&lt;/span>&lt;span class="w"> &lt;/span>}&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 7&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">metric&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 8&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">duration&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled: true, sampling&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="m">0.5&lt;/span>&lt;span class="w"> &lt;/span>}&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln"> 9&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">experiment&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w">
&lt;/span>&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="ln">10&lt;/span>&lt;span class="cl">&lt;span class="w"> &lt;/span>&lt;span class="nt">pricing_test&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>{&lt;span class="w"> &lt;/span>&lt;span class="nt">enabled&lt;/span>&lt;span class="p">:&lt;/span>&lt;span class="w"> &lt;/span>&lt;span class="kc">false&lt;/span>&lt;span class="w"> &lt;/span>}&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;h3 id="collector-端下發動態">Collector 端下發（動態）&lt;/h3>
&lt;p>SDK 啟動時從 collector 的 &lt;code>/config&lt;/code> endpoint 拉取當前的感測器設定。Collector 端修改設定後，下一次 SDK 重啟或定期 refresh（每 5 分鐘）時生效。適合需要動態調整但不值得接 feature flag 服務的場景。&lt;/p></description><content:encoded><![CDATA[<p>感測器的啟用組合隨產品階段變化。早期開發只需要 error 和 lifecycle 幫助 debug，production 上線後需要商業事件和效能量測，A/B 測試期間需要實驗專用感測器。把所有感測器一次全開會浪費頻寬和儲存、產生大量低價值事件；全程只開 error 則在需要行為分析時發現沒有資料。感測器的啟停是設計決策，由 SDK config、collector 下發和 feature flag 三層機制控制。</p>
<h2 id="五個階段">五個階段</h2>
<h3 id="早期開發">早期開發</h3>
<p>開發期的首要需求是 debug — 程式碼寫完跑起來、出問題時能定位。</p>
<table>
  <thead>
      <tr>
          <th>感測器類型</th>
          <th>啟用</th>
          <th>理由</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>error</td>
          <td>全開</td>
          <td>每個例外都要看到</td>
      </tr>
      <tr>
          <td>lifecycle</td>
          <td>全開</td>
          <td>app 啟動、連線、狀態轉換的步驟紀錄</td>
      </tr>
      <tr>
          <td>event</td>
          <td>按需</td>
          <td>正在開發的功能手動加埋點，其他關閉</td>
      </tr>
      <tr>
          <td>metric</td>
          <td>關閉</td>
          <td>效能量測在功能穩定前沒有意義</td>
      </tr>
  </tbody>
</table>
<p>開發期的取樣率全部設 1.0（全收）— 事件量極低（開發者自己操作），不需要取樣。</p>
<h3 id="功能測試">功能測試</h3>
<p>針對被測功能開啟完整感測器，驗證功能的行為事件和效能指標是否正確觸發。</p>
<p>被測功能的 event 和 metric 全開。其他功能維持開發期設定。測試期間的感測器設定通常由測試 config 檔覆寫 SDK 預設值。</p>
<h3 id="production-上線">Production 上線</h3>
<p>上線後的感測器組合平衡覆蓋率和成本：</p>
<table>
  <thead>
      <tr>
          <th>感測器類型</th>
          <th>策略</th>
          <th>理由</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>error</td>
          <td>全收</td>
          <td>每個 production error 都有 debug 價值</td>
      </tr>
      <tr>
          <td>lifecycle</td>
          <td>全收</td>
          <td>session 分析和環境資訊需要完整紀錄</td>
      </tr>
      <tr>
          <td>event（核心操作）</td>
          <td>全收</td>
          <td>漏斗關鍵步驟、轉換事件不能漏</td>
      </tr>
      <tr>
          <td>event（高頻 UI）</td>
          <td>取樣</td>
          <td>scroll、mousemove、hover 等高頻操作只取部分</td>
      </tr>
      <tr>
          <td>metric</td>
          <td>取樣</td>
          <td>效能指標按時間取樣（每 30 秒一次而非每 frame）</td>
      </tr>
      <tr>
          <td>安全事件</td>
          <td>全收</td>
          <td>auth 失敗、權限越界、敏感操作不取樣</td>
      </tr>
  </tbody>
</table>
<h3 id="ab-測試">A/B 測試</h3>
<p>實驗感測器只對 treatment group 啟用。Control group 不觸發實驗事件，避免污染對照組資料。</p>
<p>實驗專用事件（<code>experiment.pricing_test.assigned</code>、<code>experiment.pricing_test.converted</code>）由 feature flag 控制 — flag 開啟時 SDK 才送這些事件。實驗結束後 flag 關閉，感測器自動停止。</p>
<p>實驗事件的保留期和實驗週期綁定，實驗結束 + 分析完成後可以 purge。</p>
<h3 id="功能下線">功能下線</h3>
<p>功能移除時，對應的感測器 config 一起移除。Collector 端 purge 該功能的歷史事件（或降級到聚合摘要）。</p>
<p>移除 checklist：SDK config 移除事件名稱 → SDK 版本部署 → 確認 collector 不再收到該事件 → purge 歷史資料（可選）。</p>
<h2 id="控制機制">控制機制</h2>
<p>三層控制機制各自適合不同的變更頻率：</p>
<h3 id="sdk-init-config靜態">SDK init config（靜態）</h3>
<p>隨 app 版本部署的本地設定檔。變更需要發新版本。適合穩定的感測器組合。</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="ln"> 1</span><span class="cl"><span class="nt">sensors</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln"> 2</span><span class="cl"><span class="w">  </span><span class="nt">error</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled: true, sampling</span><span class="p">:</span><span class="w"> </span><span class="m">1.0</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="ln"> 3</span><span class="cl"><span class="w">  </span><span class="nt">lifecycle</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled: true, sampling</span><span class="p">:</span><span class="w"> </span><span class="m">1.0</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="ln"> 4</span><span class="cl"><span class="w">  </span><span class="nt">event</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln"> 5</span><span class="cl"><span class="w">    </span><span class="nt">funnel.*</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled: true, sampling</span><span class="p">:</span><span class="w"> </span><span class="m">1.0</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="ln"> 6</span><span class="cl"><span class="w">    </span><span class="nt">click.*</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled: true, sampling</span><span class="p">:</span><span class="w"> </span><span class="m">0.1</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="ln"> 7</span><span class="cl"><span class="w">  </span><span class="nt">metric</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln"> 8</span><span class="cl"><span class="w">    </span><span class="nt">duration</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled: true, sampling</span><span class="p">:</span><span class="w"> </span><span class="m">0.5</span><span class="w"> </span>}<span class="w">
</span></span></span><span class="line"><span class="ln"> 9</span><span class="cl"><span class="w">  </span><span class="nt">experiment</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="ln">10</span><span class="cl"><span class="w">    </span><span class="nt">pricing_test</span><span class="p">:</span><span class="w"> </span>{<span class="w"> </span><span class="nt">enabled</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w"> </span>}</span></span></code></pre></div><h3 id="collector-端下發動態">Collector 端下發（動態）</h3>
<p>SDK 啟動時從 collector 的 <code>/config</code> endpoint 拉取當前的感測器設定。Collector 端修改設定後，下一次 SDK 重啟或定期 refresh（每 5 分鐘）時生效。適合需要動態調整但不值得接 feature flag 服務的場景。</p>
<p>MVP 階段跳過 collector 下發，只用 SDK 本地 config。下發 API 的定義和實作標為第二階段 — 感測器的開關在 SDK 本地 config 已經能完全控制。</p>
<h3 id="feature-flag-服務整合">Feature flag 服務整合</h3>
<p>SDK 在送出事件前查詢 feature flag 判斷感測器是否啟用。適合 A/B 測試 — flag 可以按使用者 / 百分比 / 條件分群啟用。</p>
<h3 id="優先順序">優先順序</h3>
<p>三層控制的覆蓋優先順序：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="ln">1</span><span class="cl">Feature flag &gt; Collector 下發 &gt; SDK 本地 config</span></span></code></pre></div><p>SDK 本地 config 是 baseline。Collector 下發覆蓋 baseline 的特定欄位。Feature flag 覆蓋一切 — 即使本地 config 和 collector 都說啟用，flag 說關閉就關閉。</p>
<h2 id="取樣率設計">取樣率設計</h2>
<p>取樣率決定「多少比例的事件會被實際送出」。取樣在 SDK 端執行 — 不送的事件不佔頻寬和儲存。</p>
<h3 id="全收sampling-10">全收（sampling: 1.0）</h3>
<p>每筆事件都送。適用於：</p>
<ul>
<li><strong>error</strong>：每個 production error 都有 debug 價值，漏掉的 error 可能是最嚴重的那個</li>
<li><strong>安全事件</strong>：auth 失敗、權限越界的取樣可能讓攻擊嘗試隱形</li>
<li><strong>漏斗關鍵步驟</strong>：funnel 分析的轉換率計算需要精確的步驟計數</li>
</ul>
<h3 id="百分比取樣001-05">百分比取樣（0.01-0.5）</h3>
<p>只送一定比例的事件。適用於高頻且個別事件價值低的場景：</p>
<ul>
<li>scroll / mousemove / hover：每秒觸發數十次，全收會產生大量事件。取樣 1-10% 足以分析使用者行為模式</li>
<li>frame rate 量測：每幀一筆 metric 太多，每秒或每 30 秒取一筆足夠</li>
</ul>
<p>取樣的實作用 SDK 端的隨機數 — <code>if random() &lt; sampling_rate then send(event)</code> — 不需要 server 端參與。</p>
<h3 id="條件取樣retrospective-full-capture">條件取樣（retrospective full capture）</h3>
<p>正常情況取樣，但發生 error 時回溯收集該 session 的全部事件。實作方式是 SDK 在記憶體中保留最近 N 筆事件的環形 buffer，觸發 error 時把 buffer 中的事件一併送出。</p>
<p>條件取樣讓「error session 的上下文完整」和「正常 session 不過度收集」兩個目標共存。</p>
<h2 id="感測器開關的可觀察性">感測器開關的可觀察性</h2>
<p>感測器本身的狀態變化需要被觀察 — 如果感測器靜默失效（config 錯誤導致某類事件停送），開發者可能很久後才發現「怎麼最近沒有 funnel 資料」。</p>
<h3 id="啟動時-log-感測器清單">啟動時 log 感測器清單</h3>
<p>SDK 初始化完成時 log 當前啟用的感測器清單和取樣率。開發者在 debug console 就能看到「哪些感測器在跑」。</p>
<h3 id="config-變更事件">Config 變更事件</h3>
<p>感測器 config 變更時（collector 下發新 config、或 feature flag 變化），SDK 送一個 lifecycle 事件：</p>





<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="ln">1</span><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">  <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;lifecycle&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">  <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;sensor.config.changed&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl">  <span class="nt">&#34;data&#34;</span><span class="p">:</span> <span class="p">{</span>
</span></span><span class="line"><span class="ln">5</span><span class="cl">    <span class="nt">&#34;source&#34;</span><span class="p">:</span> <span class="s2">&#34;collector_push&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="ln">6</span><span class="cl">    <span class="nt">&#34;changed&#34;</span><span class="p">:</span> <span class="p">{</span><span class="nt">&#34;click.*&#34;</span><span class="p">:</span> <span class="p">{</span><span class="nt">&#34;sampling&#34;</span><span class="p">:</span> <span class="s2">&#34;0.1 → 0.05&#34;</span><span class="p">}},</span>
</span></span><span class="line"><span class="ln">7</span><span class="cl">    <span class="nt">&#34;active_sensors&#34;</span><span class="p">:</span> <span class="mi">12</span>
</span></span><span class="line"><span class="ln">8</span><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="ln">9</span><span class="cl"><span class="p">}</span></span></span></code></pre></div><p>這筆事件讓開發者在查詢時能看到「某個時間點感測器 config 改變了」，和事件量的變化做交叉比對。</p>
<h2 id="下一步路由">下一步路由</h2>
<ul>
<li>感測器偵測哪些行為 → <a href="/blog/monitoring/03-sdk-design/frontend-sensor-design/" data-link-title="前端感測器設計" data-link-desc="什麼行為值得埋感測器、每類感測器的實作方式、取樣策略和效能影響 — 和 auto-intercept 的被動攔截互補">前端感測器設計</a></li>
<li>SDK 的公開 API → <a href="/blog/monitoring/03-sdk-design/public-api/" data-link-title="SDK 公開 API 設計" data-link-desc="init / event / error / metric / flush / close 六個方法構成 SDK 的完整生命週期 — 跨平台共用相同 API 介面">SDK 公開 API 設計</a></li>
<li>四類事件的定義 → <a href="/blog/monitoring/01-mental-model/four-event-types/" data-link-title="四類事件的完整定義" data-link-desc="Event / Error / Metric / Lifecycle 四類事件各自的語意、觸發時機和典型用途 — 分類是監控體系的統一語言">四類事件的完整定義</a></li>
<li>事件枚舉方法 → <a href="/blog/monitoring/01-mental-model/event-enumeration-method/" data-link-title="事件枚舉與補齊檢查" data-link-desc="從操作盤點系統性地推導出完整的事件清單 — 四類補齊檢查確保沒有遺漏、粒度判準確保每個事件只記一個事實">事件枚舉與補齊檢查</a></li>
</ul>
]]></content:encoded></item></channel></rss>