開發與維運

Sentry(v20.12.1) K8S 雲原生架構探索,SENTRY FOR JAVASCRIPT SDK 配置詳解(二)

Default Integrations


所有 Sentry 的 SDK 都提供了集成(integrations),擴展了 SDK 的功能。

默認情況下,系統集成(System integrations)是啟用的,以集成到標準庫或解釋器本身中。它們已記錄在案,因此您既可以知道它們在做什麼,也可以在它們引起問題時禁用它們。


Enabled by Default

InboundFilters

Import name: Sentry.Integrations.InboundFilters

通過這種集成,您可以根據給定異常中的類型,消息或 URL 忽略特定錯誤。

默認情況下,它忽略以 Script error 或 Javascript error: Script error 開頭的錯誤。


要配置這個集成,直接使用 ignoreErrorsdenyUrls,和 allowUrls SDK 選項。請記住,denyURL 和 allowURL 只對捕獲的異常有效,而不是原始消息事件。

FunctionToString

Import name: Sentry.Integrations.FunctionToString

這種集成使 SDK 可以提供原始的函數和方法名稱,即使我們的錯誤或麵包屑處理程序包裝了它們也是如此。


TryCatch

Import name: Sentry.Integrations.TryCatch

這個集成封裝了原生 time 和 events APIs (setTimeoutsetIntervalrequestAnimationFrameaddEventListener/removeEventListener) 在 try/catch 塊處理 async 異常。

Breadcrumbs

Import name: Sentry.Integrations.Breadcrumbs

這種集成封裝了原生 API 以捕獲麵包屑。默認情況下,Sentry SDK 封裝了所有 API。


Available options:


{ beacon: boolean; // Log HTTP requests done with the Beacon API
  console: boolean; // Log calls to `console.log`, `console.debug`, etc
  dom: boolean; // Log all click and keypress events
  fetch: boolean; // Log HTTP requests done with the Fetch API
  history: boolean; // Log calls to `history.pushState` and friends
  sentry: boolean; // Log whenever we send an event to the server
  xhr: boolean; // Log HTTP requests done with the XHR API
}

GlobalHandlers

Import name: Sentry.Integrations.GlobalHandlers

這個集成附加了全局處理程序來捕獲未捕獲的 exceptions 和未處理的 rejections。

可用的選項:


{
  onerror: boolean;
  onunhandledrejection: boolean;
}

LinkedErrors

Import name: Sentry.Integrations.LinkedErrors

此集成允許您配置鏈接錯誤。它們將被遞歸地讀取到指定的限制,並由特定的 key 執行查找。默認情況下,Sentry SDK 將限制設置為 5,使用的鍵 key 是 cause

可用的選項:


{
  key: string;
  limit: number;
}

UserAgent

Import name: Sentry.Integrations.UserAgent

這種集成將 user-agent 信息附加到事件中,這使我們能夠正確地分類並使用特定的操作系統(OS),瀏覽器(browser)和版本(version)信息對其進行標記。


Modifying System Integrations

要禁用系統集成,在調用 init() 時設置 defaultIntegrations: false

要覆蓋它們的設置,請提供一個帶有配置到 integrations 選項的新實例。例如,關閉瀏覽器捕獲的控制檯調用:integrations: [new Sentry.Integrations.Breadcrumbs({ console: false })]

Removing an Integration

這個例子移除了為事件添加麵包屑的默認啟用的集成:


Sentry.init({
  // ...
  integrations: function(integrations) {
    // integrations will be all default integrations
    return integrations.filter(function(integration) {
      return integration.name !== "Breadcrumbs";
    });
  },
});

Pluggable Integrations

這些可插拔的集成是為特定的應用程序和/或框架增加功能的代碼片段。我們對它們進行了記錄,這樣您就可以看到它們的功能,並且可以啟用它們。


How to Enable

安裝 @sentry/integrations 包,並提供一個帶有你配置到 integrations 選項的新實例。加載 SDK 之後,包括插件。

示例:


import * as Sentry from "@sentry/browser";
import { ReportingObserver as ReportingObserverIntegration } from "@sentry/integrations";
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations: [new ReportingObserverIntegration()],
});

ExtraErrorData

Import name: Sentry.Integrations.ExtraErrorData

這個集成從錯誤對象中提取所有非原生(non-native)屬性,並將它們作為 extra 數據附加到事件中。

可用的選項:


{
  // limit of how deep the object serializer should go. Anything deeper than limit will
  // be replaced with standard Node.js REPL notation of [Object], [Array], [Function] or
  // a primitive value. Defaults to 3.
  depth: number;
}

CaptureConsole

Import name: Sentry.Integrations.CaptureConsole

這種集成捕獲所有的 Console API 調用,並使用 captureMessage 調用將它們重定向到 Sentry。然後,它會重新觸發以保留默認的原生行為。


{
  // array of methods that should be captured
  // defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']
  levels: string[];
}

Dedupe

Import name: Sentry.Integrations.Dedupe

這種集成可以對某些事件進行重複數據刪除。如果您收到許多重複的錯誤,可能會有所幫助。請注意,Sentry 將僅比較堆棧跟蹤和指紋。


Debug

Import name: Sentry.Integrations.Debug

通過這種集成,您可以檢查已處理事件的內容,該事件將被傳遞到 beforeSend 並有效地發送到 Sentry SDK。無論何時註冊,它都將始終作為最後的集成運行。

可用的選項:


{
  // trigger DevTools debugger instead of using console.log
  debugger: boolean;
  // stringify event before passing it to console.log
  stringify: boolean;
}

RewriteFrames

Import name: Sentry.Integrations.RewriteFrames

這種集成允許您對堆棧跟蹤的每一幀應用轉換。在 streamlined 場景中,可以使用它來更改文件框架的名稱,或者向它提供一個迭代函數來應用任何任意的轉換。

在 Windows 機器上,你必須使用 Unix 路徑並跳過 root 選項中的卷(volume)號來啟用。例如,C:\\Program Files\\Apache\\www 不能工作,但是,/Program Files/Apache/www 可以。


可用的選項:


{
  // root path that will be appended to the basename of the current frame's url
  root: string;
  // function that takes the frame, applies a transformation, and returns it
  iteratee: (frame) => frame;
}

ReportingObserver

Import name: Sentry.Integrations.ReportingObserver

此集成與 ReportingObserver API 掛鉤,並將捕獲的事件發送到 Sentry。可以將其配置為僅處理特定的問題類型。

可用的選項:


{
  types: <'crash'|'deprecation'|'intervention'>[];
}

Custom Integrations

使用以下格式在 JavaScript 中添加一個自定義集成:


// All integration that come with an SDK can be found on Sentry.Integrations object
// Custom integration must conform Integration interface: https://github.com/getsentry/sentry-javascript/blob/master/packages/types/src/integration.ts
Sentry.init({
  // ...
  integrations: [new MyAwesomeIntegration()],
});

rrweb: Session Replays

Sentry 提供了與 rrweb 的 proof-of-concept(概念驗證) 集成,該工具包用於記錄和重放用戶會話。在功能豐富的單頁應用程序中診斷複雜的用戶行為時,這可能非常有用。


有關可用 hints 的信息,請參閱 hints in JavaScript

回放使用 Attachments.


Configuration

首先,您需要添加 @sentry/rrweb 和 rrweb 軟件包:


npm install --save @sentry/rrweb rrweb

接下來,使用 Sentry SDK 註冊集成。這將根據您使用的框架而有所不同:


import * as Sentry from "@sentry/browser";
import SentryRRWeb from "@sentry/rrweb";
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations: [
    new SentryRRWeb({
      // ...options
    }),
  ],
  // ...
});

有關配置的更多信息,請參閱 @sentry/rrweb project on GitHub。

捕獲到事件的重播後,您會發現該事件在事件的 “Replay” 部分下的“問題詳細信息”中可見。


Sampling

為了滿足組織的需求,您可能希望對 replay 進行採樣。最簡單的方法是在初始化 Sentry SDK 時做出抽樣決定。例如,以下是 Sentry 本身如何使用採樣來僅捕獲員工的樣本的方法:


const hasReplays = getCurrentUser().isStaff;
let integrations = [];
if (hasReplays) {
  console.log("[sentry] Instrumenting session with rrweb");
  integrations.push(new SentryRRWeb());
}
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations,
});
Sentry.setTag("rrweb.active", hasReplays ? "yes" : "no");

您會注意到我們還設置了 rrweb.active 標記,該標記可幫助我們識別附加了 replay 的事件,因為否則我們將無法找到它們。配置完成後,您將可以在搜索查詢中簡單地使用 rrweb.active:yes


Sentry Testkit

在為應用程序構建測試時,您希望斷言正確的 flow-tracking 或錯誤正在發送到 Sentry,而不是真正地將其發送到 Sentry 服務器。這樣,您就不會在測試運行或其他 CI 操作期間用錯誤報告淹沒 Sentry。


Note: Wix, 一個 Sentry 合作伙伴, 負責維護Sentry Testkit。

Sentry Testkit 是一個 Sentry 插件,允許攔截 Sentry 的報告,並進一步檢查正在發送的數據。它允許 Sentry 在您的應用程序中原生工作,並且通過覆蓋缺省 Sentry 的傳輸機制,報告並不真正發送,而是在本地記錄到內存中。通過這種方式,可以在以後獲取記錄的報告,用於您自己的使用、驗證,或者您在本地開發/測試環境中的任何其他用途。


Installation

npm install sentry-testkit --save-dev

Using in tests

const sentryTestkit = require("sentry-testkit");
const { testkit, sentryTransport } = sentryTestkit();
// initialize your Sentry instance with sentryTransport
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  transport: sentryTransport,
  //... other configurations
});
// then run any scenario that should call Sentry.catchException(...)
expect(testkit.reports()).toHaveLength(1);
const report = testkit.reports()[0];
expect(report).toHaveProperty(/*...*/);

您也可以在 sentry-testkit 倉庫中的 testing section 中看到更多用法示例。

Testkit API

Sentry Testkit 由一個非常簡單和直接的 API 組成。在 Sentry Testkit Docs 中可以看到完整的 API 描述和文檔。

Leave a Reply

Your email address will not be published. Required fields are marked *