Sentry For Vue 完整接入详解(2021 Sentry v21.8.x)前方高能预警!三万字,慎入!
內(nèi)容源于:https://docs.sentry.io/platforms/javascript/guides/vue/
系列
- 1 分鐘快速使用 Docker 上手最新版 Sentry-CLI - 創(chuàng)建版本
- 快速使用 Docker 上手 Sentry-CLI - 30 秒上手 Source Maps
- Sentry For React 完整接入詳解
腦圖
公眾號:黑客下午茶快速開始
Sentry 的 SDK 支持自動報告錯誤和異常。
安裝
Sentry 通過在應(yīng)用程序 runtime 使用 SDK 捕獲數(shù)據(jù)。
# 使用 npm npm install --save @sentry/vue @sentry/tracing # 使用 yarn yarn add @sentry/vue @sentry/tracing配置
配置應(yīng)該在應(yīng)用程序的生命周期中盡早進行。
要在您的 Vue 應(yīng)用程序中初始化 Sentry,請將其添加到您的 app.js 中:
Vue2
import Vue from "vue"; import Router from "vue-router"; import * as Sentry from "@sentry/vue"; import { Integrations } from "@sentry/tracing";Vue.use(Router);const router = new Router({// ... });Sentry.init({Vue,dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new Integrations.BrowserTracing({routingInstrumentation: Sentry.vueRouterInstrumentation(router),tracingOrigins: ["localhost", "my-site-url.com", /^\//],}),],// Set tracesSampleRate to 1.0 to capture 100%// of transactions for performance monitoring.// We recommend adjusting this value in productiontracesSampleRate: 1.0, });// ...new Vue({router,render: h => h(App), }).$mount("#app");Vue3
import { createApp } from "vue"; import { createRouter } from "vue-router"; import * as Sentry from "@sentry/vue"; import { Integrations } from "@sentry/tracing";const app = createApp({// ... }); const router = createRouter({// ... });Sentry.init({app,dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new Integrations.BrowserTracing({routingInstrumentation: Sentry.vueRouterInstrumentation(router),tracingOrigins: ["localhost", "my-site-url.com", /^\//],}),],// Set tracesSampleRate to 1.0 to capture 100%// of transactions for performance monitoring.// We recommend adjusting this value in productiontracesSampleRate: 1.0, });app.use(router); app.mount("#app");此外,Vue 3 允許您使用具有相同 Sentry SDK 實例的多個應(yīng)用程序,以及在 SDK 已經(jīng)初始化后動態(tài)添加更多應(yīng)用程序。
Vue 3 - 多個 App
const appOne = Vue.createApp(App); const appTwo = Vue.createApp(App); const appThree = Vue.createApp(App);Sentry.init({app: [appOne, appTwo, appThree], });Vue 3 - 手動初始化
import * as Sentry from "@sentry/vue";// ... const app = createApp(App);Sentry.init({app,// ... });const miscApp = createApp(MiscApp); miscApp.mixin(Sentry.createTracingMixins({ trackComponents: true })); Sentry.attachErrorHandler(miscApp, { logErrors: true });SDK 接受一些不同的配置選項,可讓您更改其行為:
- attachProps(默認為 true)- 包括所有 Vue 組件的帶有事件的屬性(props)。
- logErrors (默認為 false) - 決定 SDK 是否也應(yīng)該調(diào)用 Vue 的原始 logError 函數(shù)。
- trackComponents(默認為 false)- 決定是否通過 hooking 到其生命周期方法來跟蹤組件。可以設(shè)置為布爾值(boolean),以啟用/禁用對所有組件的跟蹤,或設(shè)置為特定組件名稱的數(shù)組(區(qū)分大小寫)。
- timeout(默認為 2000)- 以毫秒為單位的時間,指示等待被跟蹤的根活動標記為完成(finished)并發(fā)送給 Sentry 的時間。
- hooks(默認為['activate', 'mount', 'update'])- 在組件生命周期 'activate' | 'create' | 'destroy' | 'mount' | 'unmount' | 'update' 期間要跟蹤的 hooks 列表。
如果啟用 SDK,Vue 將不會在內(nèi)部調(diào)用其 logError。因此,Vue 渲染器中發(fā)生的錯誤將不會顯示在開發(fā)人員控制臺中。要保留此功能,請傳遞 logErrors:true 選項。
驗證
此代碼段包含一個故意錯誤,因此您可以在設(shè)置后立即測試一切是否正常:
向頁面添加一個引發(fā)錯誤的按鈕:
// ... <button @click="throwError">Throw error</button> // ...export default {// ...methods: {throwError() {throw new Error('Sentry Error');}} };配置
基本選項
SDK 可以使用多種選項進行配置。這些選項在 SDK 中基本上是標準化的,但在更好地適應(yīng)平臺特性方面存在一些差異。選項是在 SDK 首次初始化時設(shè)置的。
選項作為對象傳遞給 init() 函數(shù):
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",maxBreadcrumbs: 50,debug: true, });常見選項
跨 SDK 的常用選項列表。這些在所有 SDK 中的工作方式或多或少都相同,但為了更好地支持平臺,將存在一些細微差別。 可以從環(huán)境變量(SENTRY_DSN、SENTRY_ENVIRONMENT、SENTRY_RELEASE)中讀取的選項會自動讀取。
dsn
DSN 告訴 SDK 將事件發(fā)送到哪里。如果沒有提供這個值,SDK 將嘗試從 SENTRY_DSN 環(huán)境變量中讀取它。如果這個變量也不存在,SDK 就不會發(fā)送任何事件。
在沒有進程環(huán)境(如瀏覽器)的運行時中,fallback 不會應(yīng)用。
更多:https://docs.sentry.io/product/sentry-basics/dsn-explainer/#dsn-utilization
debug
打開或關(guān)閉調(diào)試模式。如果啟用了調(diào)試,如果發(fā)送事件時出現(xiàn)問題,SDK 將嘗試打印出有用的調(diào)試信息。默認值總是 false。一般不建議在生產(chǎn)環(huán)境中打開它,盡管打開 debug 模式不會引起任何安全問題。
release
設(shè)置 release。某些 SDK 會嘗試自動配置 release,但是最好手動設(shè)置 release,以確保該 release 與您的 deploy integrations 或 source map uploads 同步。Release 名稱是字符串,但是 Sentry 會檢測到某些格式,并且它們的呈現(xiàn)方式可能有所不同。
更多:https://docs.sentry.io/product/releases/
默認情況下,SDK 會嘗試從環(huán)境變量 SENTRY_RELEASE 中讀取該值(在瀏覽器 SDK 中,將從 window.SENTRY_RELEASE 中讀取該值,如果可用)。
environment
設(shè)置環(huán)境。此字符串為自由形式,默認情況下不設(shè)置。一個 release 可以與多個環(huán)境相關(guān)聯(lián),以便在 UI 中將它們分開(可以考慮staging 與 prod 或類似的方式)。
默認情況下,SDK 將嘗試從 SENTRY_ENVIRONMENT 環(huán)境變量中讀取該值(瀏覽器 SDK 除外)。
tunnel
設(shè)置將用于傳輸捕獲事件的 URL,而不是使用 DSN。這可用于解決廣告攔截器(ad-blockers)或?qū)Πl(fā)送到 Sentry 的事件進行更精細的控制。此選項需要實現(xiàn)自定義服務(wù)器端點。
更多:https://docs.sentry.io/platforms/javascript/troubleshooting/#dealing-with-ad-blockers
sampleRate
配置錯誤事件的采樣率,范圍為 0.0 到 1.0。默認值為 1.0,表示發(fā)送了 100% 的錯誤事件。如果設(shè)置為 0.1,則僅發(fā)送 10% 的錯誤事件。事件是隨機選擇的。
maxBreadcrumbs
這個變量控制應(yīng)該捕獲的面包屑總數(shù)。默認值為 100。
attachStacktrace
當啟用時,堆棧跟蹤將自動附加到所有記錄的消息。堆棧跟蹤總是附加到異常;然而,當設(shè)置此選項時,堆棧跟蹤也會與消息一起發(fā)送。例如,該選項意味著堆棧跟蹤顯示在所有日志消息的旁邊。
該選項默認為 off。
Sentry 中的分組對于有和沒有堆棧跟蹤的事件是不同的。因此,當您為某些事件啟用或禁用此 flag 時,您將獲得新組。
denyUrls
與不應(yīng)該發(fā)送到 Sentry 的錯誤 URL 相匹配的字符串或正則表達式模式列表。默認情況下,將發(fā)送所有錯誤。這是一個 “contains(包含)” 匹配整個文件 URL。因此,如果你添加 foo.com,它也會匹配 https://bar.com/myfile/foo.com。默認情況下,將發(fā)送所有錯誤。
allowUrls
匹配錯誤 URL 的字符串列表或正則表達式模式的遺留別名,這些錯誤 URL 應(yīng)該專門發(fā)送給 Sentry。默認情況下,將發(fā)送所有錯誤。這是一個 “contains(包含)” 匹配整個文件 URL。因此,如果您將 foo.com 添加到它,它也將匹配 https://bar.com/myfile/foo.com。默認情況下,所有錯誤將被發(fā)送。
autoSessionTracking
設(shè)置為 true 時,SDK 將向 Sentry 發(fā)送 session 事件。這在所有瀏覽器 SDK 中都受支持,每個頁面加載和頁面導(dǎo)航都向 Sentry 發(fā)出一個 session。在移動 SDK 中,當應(yīng)用進入后臺超過 30 秒時,會話結(jié)束。
initialScope
要設(shè)置為初始作用域的數(shù)據(jù)。初始作用域可以定義為對象或回調(diào)函數(shù),如下所示。
對象:
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",debug: true,initialScope: {tags: {"my-tag": "my value"},user: {id: 42, email: "john.doe@example.com"},} });回調(diào)函數(shù):
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",debug: true,initialScope: scope => {scope.setTags({ a: 'b' });return scope;}, });maxValueLength
單個值在被截斷之前可以具有的最大字符數(shù)(默認為 250)。
normalizeDepth
Sentry SDK 將任何上下文數(shù)據(jù)標準化到給定的深度。 任何包含結(jié)構(gòu)比這更深的數(shù)據(jù)的 key 都將使用其類型([Object] 或 [Array])進行修剪和標記,而不會進一步遍歷樹。默認情況下,步行執(zhí)行 3 級深度。
集成配置
對于許多平臺,SDK 集成可以與之一起配置。在一些平臺上,這是 init() 調(diào)用的一部分,而在另一些平臺上,則應(yīng)用不同的模式。
integrations
在某些 SDK 中,在庫初始化時通過此參數(shù)配置集成。
更多:
defaultIntegrations
這可以用來禁用默認添加的集成。當設(shè)置為 false 時,不會添加默認的集成。
Hooks
這些選項可用于以各種方式 hook SDK,以定制事件的報告。
beforeSend
使用 SDK-specific 事件對象調(diào)用此函數(shù),可以返回修改后的事件對象或不返回任何內(nèi)容,以跳過報告事件。例如,這可以用于在發(fā)送前手動剝離 PII。
beforeBreadcrumb
在將面包屑添加到作用域之前,使用 SDK 特定的面包屑(SDK-specific breadcrumb)對象調(diào)用此函數(shù)。當該函數(shù)未返回任何內(nèi)容時,將刪除 breadcrumb。要傳遞 breadcrumb,請返回第一個參數(shù),其中包含 breadcrumb 對象。回調(diào)通常會獲得第二個參數(shù)(稱為“hint”),該參數(shù)包含創(chuàng)建 breadcrumb 的原始對象,以進一步自定義面包屑的外觀。
傳輸選項
Transports 被用來發(fā)送事件到 Sentry。可以在某種程度上對傳輸進行定制,以更好地支持高度特定的部署。
transport
切換出用于發(fā)送事件的 transport。如何運作取決于 SDK。例如,它可以用于捕獲事件以進行單元測試,或通過需要代理身份驗證的更復(fù)雜的設(shè)置發(fā)送事件。
跟蹤選項
tracesSampleRate
0 到 1 之間的數(shù)字,控制給定事務(wù)發(fā)送到 Sentry 的概率百分比。(0 表示 0%,1 表示 100%)同樣適用于應(yīng)用程序中創(chuàng)建的所有事務(wù)。必須定義這個或 tracesSampler 以啟用跟蹤。
tracesSampler
一個函數(shù)負責確定一個給定的事務(wù)將被發(fā)送到 Sentry 的概率百分比。它將自動被傳遞有關(guān)事務(wù)和創(chuàng)建它的上下文的信息,并且必須返回一個介于 0(被發(fā)送的概率為 0%)和 1(被發(fā)送的概率為 100%) 之間的數(shù)字。還可以用于過濾事務(wù),對不需要的事務(wù)返回 0。必須定義這個或 tracesSampleRate 來啟用跟蹤。
集成
默認集成
Sentry 的所有 SDK 都提供集成,可擴展 SDK 的功能。
默認情況下啟用系統(tǒng)集成以集成到標準庫或解釋器本身。 它們被記錄在案,因此您既可以了解它們的作用,也可以在它們引起問題時禁用它們。
默認啟用
InboundFilters
Import name: Sentry.Integrations.InboundFilters
通過這種集成,您可以根據(jù)給定異常中的類型,消息或 URL 忽略特定錯誤。
默認情況下,它忽略以 Script error 或 Javascript error: Script error 開頭的錯誤。
要配置這個集成,直接使用 ignoreErrors,denyUrls,和 allowUrls SDK 選項。請記住,denyURL 和 allowURL 只對捕獲的異常有效,而不是原始消息事件。
FunctionToString
Import name: Sentry.Integrations.FunctionToString
這種集成使 SDK 可以提供原始的函數(shù)和方法名稱,即使我們的錯誤(error)或面包屑處理程序(breadcrumbs handlers)包裝了它們也是如此。
TryCatch
Import name: Sentry.Integrations.TryCatch
這個集成封裝了原生 time 和 events APIs (setTimeout, setInterval, requestAnimationFrame, addEventListener/removeEventListener) 在 try/catch 塊處理 async 異常。
Breadcrumbs
Import name: Sentry.Integrations.Breadcrumbs
這種集成封裝了原生 API 以捕獲面包屑。默認情況下,Sentry SDK 封裝了所有 API。
可用選項:
{// 記錄對 `console.log`、`console.debug` 等的調(diào)用console: boolean;// 記錄所有點擊和按鍵事件// - 當提供帶有 `serializeAttribute` key 的對象時,// 面包屑集成將在 DOM 元素中查找給定的屬性,同時生成面包屑路徑。// 匹配的元素后跟它們的自定義屬性,而不是它們的 `id` 或 `class` 名稱。dom: boolean | { serializeAttribute: string | string[] };// 記錄使用 `Fetch API` 完成的 `HTTP` 請求fetch: boolean;// 記錄對 `history.pushState` 的調(diào)用history: boolean;// 每當我們向服務(wù)器發(fā)送事件時記錄sentry: boolean;// 記錄使用 XHR API 完成的 HTTP 請求xhr: boolean; }GlobalHandlers
Import name: Sentry.Integrations.GlobalHandlers
這個集成附加了全局處理程序來捕獲未捕獲的 exceptions 和未處理的 rejections。
可用的選項:
{onerror: boolean;onunhandledrejection: boolean; }LinkedErrors
Import name: Sentry.Integrations.LinkedErrors
此集成允許您配置 linked 錯誤。它們將被遞歸地讀取到指定的限制,并由特定的 key 執(zhí)行查找。默認情況下,Sentry SDK 將限制設(shè)置為 5,使用的鍵 key 是 cause。
可用的選項:
{key: string;limit: number; }這是如何實現(xiàn)的代碼示例:
document.querySelector("#get-reviews-btn").addEventListener("click", async event => {const movie = event.target.dataset.title;try {const reviews = await fetchMovieReviews(movie);renderMovieReviews(reviews);} catch (e) {const fetchError = new Error(`Failed to fetch reviews for: ${movie}`);fetchError.cause = e;Sentry.captureException(fetchError);renderMovieReviewsError(fetchError);}});UserAgent
Import name: Sentry.Integrations.UserAgent
這種集成將 user-agent 信息附加到事件中,這使我們能夠正確地分類并使用特定的操作系統(tǒng)(OS),瀏覽器(browser)和版本(version)信息對其進行標記。
Dedupe
Import name: Sentry.Integrations.Dedupe
這種集成消除了某些事件的重復(fù)數(shù)據(jù)。如果您收到許多重復(fù)的錯誤,這會很有幫助。請注意,Sentry 只會比較堆棧跟蹤(stack traces)和指紋(fingerprints)。默認情況下為瀏覽器啟用此集成。
import * as Sentry from "@sentry/browser"; import { Dedupe as DedupeIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new DedupeIntegration()], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/dedupe.min.js"integrity="sha384-3IMGY+DN27Yns7KDiKL3sOWXBYlILQ/bxLogt02NG7DL7qEJHIMbpnXfqNlO0J8G"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new Dedupe()], });修改系統(tǒng)集成
要禁用系統(tǒng)集成,請在調(diào)用 init() 時設(shè)置 defaultIntegrations: false。
要覆蓋它們的設(shè)置,請?zhí)峁┮粋€帶有您的配置到集成選項的新實例。 例如,要關(guān)閉瀏覽器捕獲控制臺調(diào)用:integrations: [new Sentry.Integrations.Breadcrumbs({ console: false })]。
刪除集成
此示例刪除了用于向事件添加面包屑的默認啟用集成:
Sentry.init({// ...integrations: function(integrations) {// integrations will be all default integrationsreturn integrations.filter(function(integration) {return integration.name !== "Breadcrumbs";});}, });可插拔集成
這些可插拔的集成是為特定的應(yīng)用程序和/或框架增加功能的代碼片段。我們對它們進行了記錄,這樣您就可以看到它們的功能,并且可以啟用它們。
如何啟用
安裝 @sentry/integrations 包,并提供一個帶有你配置到 integrations 選項的新實例。加載 SDK 之后,包括插件。
示例:
import * as Sentry from "@sentry/browser"; import { ReportingObserver as ReportingObserverIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ReportingObserverIntegration()], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/reportingobserver.min.js"integrity="sha384-20D83MPBNSRANJFguhj0o9Qo7p9MCemwdMMQXotwA8742WuIwga85k+T7qEgIMWK"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ReportingObserver()], });ExtraErrorData
Import name: Sentry.Integrations.ExtraErrorData
這個集成從錯誤對象中提取所有非原生(non-native)屬性,并將它們作為 extra 數(shù)據(jù)附加到事件中。
可用的選項:
import * as Sentry from "@sentry/browser"; import { ExtraErrorData as ExtraErrorDataIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ExtraErrorDataIntegration({// 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;})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/extraerrordata.min.js"integrity="sha384-DMO/ZWwA4ztkOtskx1Uad3cH6lbfSA/PGdW2IZ7A/c2qd/BU6zh5xiJ5D4nxJbye"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ExtraErrorData({// 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 調(diào)用,并使用 captureMessage 調(diào)用將它們重定向到 Sentry。然后,它會重新觸發(fā)以保留默認的原生行為。
import * as Sentry from "@sentry/browser"; import { CaptureConsole as CaptureConsoleIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new CaptureConsoleIntegration({// array of methods that should be captured// defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']levels: string[];})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/captureconsole.min.js"integrity="sha384-FJ5n80A08NroQF9DJzikUUhiCaQT2rTIYeJyHytczDDbIiejfcCzBR5lQK4AnmVt"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new CaptureConsole({// array of methods that should be captured// defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']levels: string[];})], });Debug
Import name: Sentry.Integrations.Debug
通過這種集成,您可以檢查已處理事件的內(nèi)容,該事件將被傳遞到 beforeSend 并有效地發(fā)送到 Sentry SDK。無論何時注冊,它都將始終作為最后的集成運行。
可用的選項:
import * as Sentry from "@sentry/browser"; import { Debug as DebugIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new DebugIntegration({// trigger DevTools debugger instead of using console.logdebugger: boolean;// stringify event before passing it to console.logstringify: boolean;})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/debug.min.js"integrity="sha384-OIzIETBTnmaXcnCVlI4DzHq1+YxDdBS6uyZPp8yS60YZNUqzIQvrudJplBqEZ09K"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new Debug({// trigger DevTools debugger instead of using console.logdebugger: boolean;// stringify event before passing it to console.logstringify: boolean;})], });Offline
Import name: Sentry.Integrations.Offline
此集成使用 Web 瀏覽器的在線和離線事件來檢測何時沒有可用的網(wǎng)絡(luò)連接。如果離線,它會將事件保存到 Web 瀏覽器的客戶端存儲(通常是 IndexedDB),然后在網(wǎng)絡(luò)連接恢復(fù)時自動上傳事件。
Online and offline events
- https://developer.mozilla.org/en-US/docs/Web/API/Navigator/Online_and_offline_events
此插件不會嘗試為其他場景提供本地存儲或重試。 例如,如果瀏覽器有本地連接但沒有互聯(lián)網(wǎng)連接,那么它可能會報告它在線,并且在這種情況下,Sentry 的 Offline 插件不會嘗試保存或重試任何發(fā)送失敗。
import * as Sentry from "@sentry/browser"; import { Offline as OfflineIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new OfflineIntegration({// limit how many events will be localled saved. Defaults to 30.maxStoredEvents: number;})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/offline.min.js"integrity="sha384-rRq5WRQ3OncIj4lduaVZMtyfVwZnqeWXM0nXyXckOrhFLS2mlKEYX+VAlbLlIZL4"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new Offline({// limit how many events will be localled saved. Defaults to 30.maxStoredEvents: number;})], });RewriteFrames
Import name: Sentry.Integrations.RewriteFrames
這種集成允許您對堆棧跟蹤的每個幀應(yīng)用轉(zhuǎn)換。 在流線型(streamlined)場景中,它可用于更改其來源的文件幀的名稱,或者可以使用迭代函數(shù)為其提供任意變換。
在 Windows 機器上,您必須使用 Unix 路徑并跳過 root 選項中的卷號才能啟用。例如 C:\\Program Files\\Apache\\www 將不起作用,但是 /Program Files/Apache/www 將起作用。
可用的選項:
import * as Sentry from "@sentry/browser"; import { RewriteFrames as RewriteFramesIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new RewriteFramesIntegration({// root path that will be stripped from the current frame's filename by the default iteratee if the filename is an absolute pathroot: string;// a custom prefix that will be used by the default iteratee (default: `app://`)prefix: string;// function that takes the frame, applies a transformation, and returns ititeratee: (frame) => frame;})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/rewriteframes.min.js"integrity="sha384-WOm9k3kzVt1COFAB/zCXOFx4lDMtJh/2vmEizIwgog7OW0P/dPwl3s8f6MdwrD7q"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new RewriteFrames({// root path that will be stripped from the current frame's filename by the default iteratee if the filename is an absolute pathroot: string;// a custom prefix that will be used by the default iteratee (default: `app://`)prefix: string;// function that takes the frame, applies a transformation, and returns ititeratee: (frame) => frame;})], });使用示例:
例如,如果文件的完整路徑是 /www/src/app/file.js:
| RewriteFrames() | app:///file.js | 默認行為是替換除文件名之外的絕對路徑,并使用默認前綴 (app:///) 作為前綴。 |
| RewriteFrames({prefix: 'foo/'}) | foo/file.js | 使用前綴 foo/ 代替默認前綴 app:///。 |
| RewriteFrames({root: '/www'}) | app:///src/app/file.js | root 定義為 /www,因此僅從路徑的開頭修剪該部分。 |
ReportingObserver
Import name: Sentry.Integrations.ReportingObserver
此集成掛鉤到 ReportingObserver API 并將捕獲的事件發(fā)送到 Sentry。它可以配置為僅處理特定的 issue 類型。
可用的選項:
import * as Sentry from "@sentry/browser"; import { ReportingObserver as ReportingObserverIntegration } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ReportingObserverIntegration({types: <'crash'|'deprecation'|'intervention'>[];})], });CDN
<scriptsrc="https://browser.sentry-cdn.com/6.12.0/bundle.min.js"integrity="sha384-S3qfdh3AsT1UN84WIYNuOX9vVOoFg3nB17Jp5/pTFGDBGBt+dtz7MGAV845efkZr"crossorigin="anonymous" ></script><scriptsrc="https://browser.sentry-cdn.com/6.12.0/reportingobserver.min.js"integrity="sha384-20D83MPBNSRANJFguhj0o9Qo7p9MCemwdMMQXotwA8742WuIwga85k+T7qEgIMWK"crossorigin="anonymous" ></script>Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new ReportingObserver({types: <'crash'|'deprecation'|'intervention'>[];})], });Vue Router 集成
Vue 跟蹤集成允許您在初始應(yīng)用程序加載期間跟蹤渲染性能。
Sentry 使用 mixins 功能在其生命周期階段提供對 Vue 組件的訪問。
當 Sentry 遇到一個名為 root 的組件,它是一個頂級 Vue 實例(如 new Vue({})),
我們使用我們的 BrowserTracing 集成,并創(chuàng)建一個名為 Vue Application Render 的新跨度。
一旦創(chuàng)建了 Vue Application Render 跨度,它將等待它的所有子組件都渲染完畢,然后才將跨度標記為完成(finished)。
所描述的檢測功能將為您提供有關(guān) Vue 實例渲染性能的非常高級的信息。
但是,集成還可以提供有關(guān)特定活動期間實際發(fā)生的情況的更細粒度的詳細信息。 為此,您需要指定要跟蹤的組件和要偵聽的鉤子(https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)。
您還可以為所有組件打開跟蹤。但是,如果您的應(yīng)用程序由數(shù)百個組件組成,則可能會相當嘈雜。
我們鼓勵更具體。如果您不提供 hooks,Sentry 將跟蹤組件的 mount 和 update 鉤子。
請注意,在指定 hooks 時,我們使用簡單動詞而不是 before 和 -ed 對。
例如,destroy 是正確的。beforeDestroy 和 destroyed 是不正確的。
要設(shè)置 Vue Tracing 集成,您首先需要配置 BrowserTracing 集成本身。
有關(guān)如何執(zhí)行此操作的詳細信息,請查看我們的性能文檔。
配置完 BrowserTracing 集成后,繼續(xù)配置 Vue 集成本身。Sentry 將新的跟蹤功能構(gòu)建到原始 Vue 錯誤處理程序集成中,因此無需添加任何新包。
您只需要提供適當?shù)呐渲谩?/p>
跟蹤 Vue 應(yīng)用程序的最基本配置(僅跟蹤頂級組件)如下所示:
import Vue from "vue"; import * as Sentry from "@sentry/browser"; import { Integrations } from "@sentry/tracing";Sentry.init({// ...integrations: [new Integrations.BrowserTracing()],// We recommend adjusting this value in production, or using tracesSampler// for finer controltracesSampleRate: 1.0, });如果要跟蹤子組件,并查看有關(guān)渲染過程的更多詳細信息,請配置集成以跟蹤它們:
Sentry.init({Vue,trackComponents: true, });或者,您可以選擇更多粒度:
Sentry.init({Vue,integrations: [new Integrations.BrowserTracing()],trackComponents: ["App","RwvHeader","RwvFooter","RwvArticleList","Pagination",], });例如,如果您想知道某些組件是否在初始頁面加載期間被刪除,請向默認值添加一個 destroy 鉤子:
Sentry.init({Vue,integrations: [new Integrations.BrowserTracing()],trackComponents: ["App","RwvHeader","RwvFooter","RwvArticleList","Pagination",],hooks: ["mount", "update", "destroy"], });您可以指定頂級活動應(yīng)等待最后一個組件渲染的時間。
每個新的渲染周期都會消除超時的抖動,并從頭開始計數(shù)。
一旦達到超時,跟蹤就完成了,所有的信息都會發(fā)送給 Sentry。
配置
tracingOptions: {/*** Decides whether to track components by hooking into its lifecycle methods.* Can be either set to `boolean` to enable/disable tracking for all of them.* Or to an array of specific component names (case-sensitive).* Default: false*/trackComponents: boolean | string[];/*** How long to wait (in ms) until the tracked root activity is marked as finished and sent to Sentry* Default: 2000*/timeout: number;/*** List of hooks to keep track of during component lifecycle.* Available hooks: 'activate' | 'create' | 'destroy' | 'mount' | 'unmount' | 'update'* Based on https://vuejs.org/v2/api/#Options-Lifecycle-Hooks*/hooks: string[]; }使用 Vue Router
如果您使用 Vue Router,您可以使用我們提供的集成來獲得更好的 transaction 名稱。這是如何使用它的完整示例:
import Vue from "vue"; import App from "./App"; import * as Sentry from "@sentry/vue"; import { Integrations } from "@sentry/tracing"; import Router from "vue-router"; import HelloWorld from "@/components/HelloWorld";Vue.use(Router);const Foo = { template: "<div>foo</div>" }; const Bar = { template: "<div>bar</div>" };const router = new Router({routes: [{path: "/",name: "HelloWorld",component: HelloWorld,},{ path: "/foo/:id", component: Foo },{ path: "/bar", component: Bar },], });Vue.config.productionTip = false;Sentry.init({Vue: Vue,dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",tracesSampleRate: 1.0,integrations: [new Integrations.BrowserTracing({routingInstrumentation: Sentry.vueRouterInstrumentation(router),}),],trackComponents: true, });/* eslint-disable no-new */ new Vue({el: "#app",router,components: { App },template: "<App/>", });自定義集成
使用以下格式向 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.tsSentry.init({// ...integrations: [new MyAwesomeIntegration()], });rrweb:Session 重播
Sentry 提供了與 rrweb 的概念驗證集成 - 一個用于記錄和重放用戶會話的工具包。 這在診斷豐富的單頁應(yīng)用程序中的復(fù)雜用戶行為時非常有用。
更多信息:
- https://www.rrweb.io/
- https://docs.sentry.io/platforms/javascript/guides/react/configuration/filtering/#using-hints
- https://docs.sentry.io/platforms/javascript/guides/react/enriching-events/attachments/
配置
要開始,您需要添加 @sentry/rrweb 和 rrweb 包:
npm install --save @sentry/rrweb rrweb接下來注冊與 Sentry SDK 的集成。這將根據(jù)您使用的框架而有所不同:
// If you're using one of our integration packages, like `@sentry/react` or // `@sentry/angular`, substitute its name for `@sentry/browser` here import * as Sentry from "@sentry/browser"; import SentryRRWeb from "@sentry/rrweb";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new SentryRRWeb({// ...options}),],// ... });捕獲事件的重播后,您會在事件的“重播(Replay)”部分下的“問題詳細信息(Issue Details)”中找到它。
- 更多:https://github.com/getsentry/sentry-rrweb
采樣
為了滿足您組織的需求,您可能更喜歡對回放進行采樣。最簡單的方法是在初始化 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: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations, });Sentry.setTag("rrweb.active", hasReplays ? "yes" : "no");您會注意到我們還設(shè)置了 rrweb.active 標簽,這有助于我們識別附加了重播(replay)的事件,否則我們將無法找到它們。 配置完成后,您就可以在搜索查詢中簡單地使用 rrweb.active:yes。
Release & 運行狀況
Release 是部署到環(huán)境中的代碼版本。當您向 Sentry 提供有關(guān)您的版本的信息時,您可以:
- 確定新版本中引入的問題和回歸
- 預(yù)測哪個提交導(dǎo)致了問題以及誰可能負責
- 通過在提交消息中包含問題編號來解決問題
- 部署代碼時接收電子郵件通知
此外,release用于將 source maps 應(yīng)用于被壓縮的 JavaScript 以查看原始的、未轉(zhuǎn)換的源代碼。
綁定版本
配置客戶端 SDK 時包含 release ID(通常稱為“版本 version”)。
release 名稱不能:
- 包含換行符、制表符、正斜杠 (/) 或反斜杠 (\)
- 是(全部)句號 (.)、雙句號 (..) 或空格 ( )
- 超過 200 個字符
該值可以是任意的,但我們推薦以下任一命名策略:
- 語義版本控制: package@version 或 package@version+build(例如,my.project.name@2.3.12+1234)
- package 是 project/app 的唯一標識符(iOS 上的 CFBundleIdentifier,Android 上的 packageName)
- version 是類似于 semver 的結(jié)構(gòu) <major>.<minor?>.<patch?>.<revision?>-<prerelease?>(iOS 上的 CFBundleShortVersionString,Android 上的 versionName)
- build 是標識 app 迭代的數(shù)字(iOS 上的 CFBundleVersion,Android 上的 versionCode)
- Commit SHA: 如果您使用 DVCS,我們建議使用標識哈希 identifying hash(例如,commit SHA,da39a3ee5e6b4b0d3255bfef95601890afd80709)。您可以讓 Sentry CLI 使用 sentry-clireleases proposal-version 為支持的版本控制系統(tǒng)自動確定此哈希值。
每個組織的發(fā)布都是全局性的;為它們添加特定于項目的前綴,以便于區(qū)分。
Sentry.init({release: "my-project-name@2.3.12", });在 Node/npm 環(huán)境中使用 JavaScript 執(zhí)行此操作的一種常見方法是使用 process.env.npm_package_version ,如下所示:
- 更多:https://docs.npmjs.com/misc/scripts#packagejson-vars
您如何使版本(version)可用于您的代碼取決于您。例如,您可以使用在構(gòu)建過程中設(shè)置的環(huán)境變量。
這用 release 值標記每個事件。我們建議您在部署之前告訴 Sentry 一個新 release,因為這將解鎖我們關(guān)于 releases 的文檔中討論的更多功能。但是,如果您不這樣做,Sentry 將在第一次看到具有該 release ID 的事件時自動在系統(tǒng)中創(chuàng)建一個 release 實體。
- release:https://docs.sentry.io/product/releases/
配置您的 SDK 后,您可以安裝 repository integration 或手動為 Sentry 提供您自己的 commit metadata。 閱讀我們關(guān)于設(shè)置 releases 的文檔,以獲取有關(guān)集成 integrations、關(guān)聯(lián)提交 associating commits以及在部署 releases 時通知 Sentry 的更多信息。
- 設(shè)置 releases: https://docs.sentry.io/product/releases/setup/
Release 運行狀況
通過觀察用戶采用情況、應(yīng)用程序使用情況、崩潰百分比和會話數(shù)據(jù)來監(jiān)控 release 的運行狀況。 release 運行狀況將深入了解與用戶體驗相關(guān)的崩潰和錯誤的影響,并通過 release 詳細信息、圖表和過濾器揭示每個新問題的趨勢。
- health of releases : https://docs.sentry.io/product/releases/health/
- crashes:https://docs.sentry.io/product/releases/health/#crash
- session data:https://docs.sentry.io/product/releases/health/#session
SDK 將在 SDK 初始化時自動管理會話的開始和結(jié)束。
我們?yōu)槊總€頁面加載創(chuàng)建一個會話。對于單頁應(yīng)用程序,我們將為每次導(dǎo)航更改(History API)創(chuàng)建一個新會話。
我們將會話標記為:
- 如果unhandled error 或 unhandled promise rejection 冒泡到全局處理程序,則崩潰。
- 如果 SDK 捕獲包含異常的事件(這包括手動捕獲的錯誤),則會出現(xiàn)錯誤。
要接收有關(guān)用戶采用的數(shù)據(jù),例如用戶崩潰率百分比和采用特定版本的用戶數(shù),請在初始化 SDK 時將用戶設(shè)置在 initialScope 上。
默認情況下,JavaScript SDK 正在發(fā)送會話。
要禁用發(fā)送會話,請將 autoSessionTracking 標志設(shè)置為 false:
環(huán)境
Sentry 在收到帶有 environment 標簽的事件時會自動創(chuàng)建環(huán)境。環(huán)境區(qū)分大小寫。 環(huán)境名稱不能包含換行符、空格或正斜杠,不能是字符串“None”或超過 64 個字符。 您無法刪除環(huán)境,但可以隱藏它們。
- hidden-environments: https://docs.sentry.io/product/sentry-basics/environments/#hidden-environments
環(huán)境可幫助您在 sentry.io 的問題詳細信息頁面中更好地過濾問題、版本和用戶反饋,您可以在我們涵蓋使用環(huán)境的文檔中了解更多信息。
- environments:https://docs.sentry.io/product/sentry-basics/environments/
過濾
將 Sentry 添加到您的應(yīng)用程序可為您提供大量關(guān)于錯誤和性能的非常有價值的信息,否則您將無法獲得這些信息。 大量的信息是好的——只要它是正確的信息,并且數(shù)量合理。
Sentry SDK 有幾個配置選項可以幫助您過濾事件。
我們還提供入站過濾器 Inbound Filters來過濾 sentry.io 中的事件。 不過,我們建議在客戶端級別進行過濾,因為它消除了發(fā)送您實際上不想要的事件的開銷。 了解有關(guān)事件中可用字段的更多信息。
- Inbound Filters: https://docs.sentry.io/product/data-management-settings/filtering/
- fields available in an event:https://develop.sentry.dev/sdk/event-payloads/
過濾錯誤事件
通過使用 beforeSend 回調(diào)方法和配置、啟用或禁用集成來配置您的 SDK 以過濾錯誤事件。
使用 beforeSend
所有 Sentry SDK 都支持 beforeSend 回調(diào)方法。beforeSend 在事件發(fā)送到服務(wù)器之前立即調(diào)用,因此它是您可以編輯其數(shù)據(jù)的最后位置。它將事件對象作為參數(shù)接收,因此您可以使用該參數(shù)根據(jù)自定義邏輯和事件上可用的數(shù)據(jù)修改事件的數(shù)據(jù)或完全刪除它(通過返回 null)。
Sentry.init({// ...beforeSend(event, hint) {const error = hint.originalException;if (error &&error.message &&error.message.match(/database unavailable/i)) {event.fingerprint = ["database-unavailable"];}return event;}, });還要注意,正如我們的 breadcrumbs 文檔中所討論的,breadcrumbs 可以被過濾。
- breadcrumbs: https://docs.sentry.io/product/error-monitoring/breadcrumbs/
Event Hints
before-send 回調(diào)傳遞 event 和第二個參數(shù) hint,該參數(shù)包含一個或多個 hints。
通常,hint 保存原始異常,以便可以提取附加數(shù)據(jù)或影響分組。 在本例中,如果捕獲到某種類型的異常,指紋將被強制為一個公共值:
Sentry.init({// ...beforeSend(event, hint) {const error = hint.originalException;if (error &&error.message &&error.message.match(/database unavailable/i)) {event.fingerprint = ["database-unavailable"];}return event;}, });有關(guān)哪些 hints 可用的信息,請參閱:
- hints in JavaScript: https://docs.sentry.io/platforms/javascript/guides/react/configuration/filtering/#using-hints
當 SDK 創(chuàng)建用于傳輸(transmission)的事件或面包屑時,該傳輸通常是從某種源對象創(chuàng)建的。例如,錯誤事件通常是從日志記錄或異常實例中創(chuàng)建的。為了更好地定制,SDK 將這些對象發(fā)送到某些回調(diào)(beforeSend、beforeBreadcrumb 或 SDK 中的事件處理器系統(tǒng))。
使用 Hints
Hints 可在兩個地方獲得:
事件和面包屑 hints 是包含用于組合事件或面包屑的各種信息的對象。 通常 hints 保存原始異常,以便可以提取附加數(shù)據(jù)或影響分組。
對于事件,例如 event_id、originalException、syntheticException(在內(nèi)部用于生成更清晰的堆棧跟蹤)以及您附加的任何其他任意數(shù)據(jù)。
對于面包屑,hints 的使用取決于實現(xiàn)。對于 XHR 請求,hint 包含 xhr 對象本身;對于用戶交互,提示包含 DOM 元素和事件名稱等。
在本例中,如果捕獲到某種類型的異常,指紋將被強制為一個公共值:
Sentry.init({// ...beforeSend(event, hint) {const error = hint.originalException;if (error &&error.message &&error.message.match(/database unavailable/i)) {event.fingerprint = ["database-unavailable"];}return event;}, });Hints for Events
originalException
導(dǎo)致 Sentry SDK 創(chuàng)建事件的原始異常。這對于更改 Sentry SDK 分組事件的方式或提取附加信息很有用。
syntheticException
當引發(fā)字符串(string)或非錯誤(non-error)對象時,Sentry 會創(chuàng)建一個合成異常(synthetic exception),以便您可以獲得基本的堆棧跟蹤。 此異常存儲在此處以供進一步提取數(shù)據(jù)。
Hints for Breadcrumbs
event
對于從瀏覽器事件創(chuàng)建的面包屑,Sentry SDK 通常將事件作為 hint 提供給面包屑。例如,這可用于將目標 DOM 元素中的數(shù)據(jù)提取到面包屑中。
level / input
對于從控制臺日志(console.log)攔截創(chuàng)建的面包屑。 這保存了原始 console log level 和 log function 的原始輸入數(shù)據(jù)。
response / input
對于從 HTTP 請求創(chuàng)建的面包屑。它保存響應(yīng)對象(來自 fetch API)和 fetch 函數(shù)的輸入?yún)?shù)。
request / response / event
對于從 HTTP 請求創(chuàng)建的面包屑。這包含請求和響應(yīng)對象(來自 node HTTP API)以及 node event(response或error)。
xhr
對于通過遺留 XMLHttpRequest API 完成的 HTTP 請求創(chuàng)建的面包屑。這保存了原始的 xhr 對象。
整理 Sentry
您可以構(gòu)建一個允許的域列表,這些域可能會引發(fā)可接受的異常。 例如,如果您的腳本是從 cdn.example.com 加載的并且您的站點是 example.com,您可以將 allowUrls 設(shè)置為:
Sentry.init({allowUrls: [/https?:\/\/((cdn|www)\.)?example\.com/] });如果您想永遠阻止特定的 URL,您也可以使用 denyUrls。
Note
在 5.17.0 版本之前,allowUrls 和 denyUrls 分別稱為 whitelistUrls 和 blacklistUrls。
出于向后兼容性的原因,這些選項仍受支持,但它們將在 6.0 版中刪除。 有關(guān)更多信息,請參閱
Inclusive Language Policy:https://develop.sentry.dev/inclusion/
此外,我們的社區(qū)還為日常事務(wù)編制了一份常見的忽略規(guī)則列表,例如 Facebook、Chrome extensions 等。 這很有用,建議您檢查一下這些內(nèi)容,看看它們是否適用于您。這不是我們 SDK 的默認值; 這只是一個廣泛示例的一個亮點。
- Here is the original gist:https://gist.github.com/impressiver/5092952
使用采樣過濾 Transaction 事件
為了防止某些 transactions 被報告給 Sentry,請使用 tracesSampler 配置選項,它允許您提供一個函數(shù)來評估當前 transaction 并在它不是您想要的時候刪除它。 (它還允許您以不同的采樣率對不同的 transaction 進行抽樣。)
注意: tracesSampler 和 tracesSampleRate 配置選項是互斥的。 如果您定義了一個 tracesSampler 來過濾掉某些 transaction,您還必須通過返回您希望對它們進行采樣的速率來處理未過濾 transaction 的情況。
最簡單的形式,僅用于過濾 transaction,它看起來像這樣:
Sentry.init({// ...tracesSampler: samplingContext => {if ("...") {// Drop this transaction, by setting its sample rate to 0%return 0;} else {// Default sample rate for all others (replaces tracesSampleRate)return 0.1;}}; });關(guān)閉與清空
大多數(shù) SDK 的默認行為是在后臺通過網(wǎng)絡(luò)異步發(fā)送事件。 這意味著如果應(yīng)用程序意外關(guān)閉,某些事件可能會丟失。SDK 提供了處理這種情況的機制。
close 方法可選地接受以毫秒為單位的 timeout,并返回一個 promise,該 promise 在刷新所有掛起事件或 timeout 生效時 resolve。
Sentry.close(2000).then(function() {// perform something after close });調(diào)用 close 后,不能再使用當前客戶端。 僅在關(guān)閉應(yīng)用程序之前立即調(diào)用 close 很重要。
或者,flush 方法清空事件隊列,同時保持客戶端啟用以供繼續(xù)使用。
采樣
將 Sentry 添加到您的應(yīng)用程序可為您提供大量關(guān)于錯誤和性能的非常有價值的信息,否則您將無法獲得這些信息。 大量的信息是好的——只要它是正確的信息,并且數(shù)量合理。
采樣 Error 事件
要將具有代表性的錯誤樣本發(fā)送到 Sentry,請將 SDK 配置中的 sampleRate 選項設(shè)置為 0(發(fā)送的錯誤的 0%)和 1(發(fā)送的錯誤的 100%)之間的數(shù)字。 這是一個靜態(tài)比率,它同樣適用于所有錯誤。例如,要對 25% 的錯誤進行抽樣:
Sentry.init({ sampleRate: 0.25 });更改錯誤采樣率需要重新部署。
此外,設(shè)置 SDK 采樣率會限制對事件源的可見性。
為您的項目設(shè)置速率限制(僅在 volume 高時丟棄事件)可能更適合您的需求。
采樣 Transaction 事件
我們建議對您的 transaction 進行抽樣,原因有兩個:
選擇采樣率的目標是在性能和數(shù)量問題與數(shù)據(jù)準確性之間找到平衡。 您不想收集太多數(shù)據(jù),但希望收集足夠的數(shù)據(jù)以得出有意義的結(jié)論。 如果您不確定要選擇什么速率,請從一個較低的值開始,隨著您對流量模式和流量的了解越來越多,逐漸增加它。
配置 Transaction 采樣率
Sentry SDK 有兩個配置選項來控制發(fā)送到 Sentry 的 transaction 量,讓您可以獲取具有代表性的樣本:
- 提供均勻的事務(wù)橫截面,無論它們在您的應(yīng)用程序中的哪個位置或在什么情況下發(fā)生。
- 使用默認繼承(inheritance)和優(yōu)先(precedence)行為
- 以不同的速率采樣不同的 transaction
- 完全過濾掉一些 transaction
- 修改默認優(yōu)先級和繼承行為
inheritance: https://docs.sentry.io/platforms/javascript/guides/react/configuration/sampling/#inheritance
precedence:https://docs.sentry.io/platforms/javascript/guides/react/configuration/sampling/#precedence
Filters:https://docs.sentry.io/platforms/javascript/guides/react/configuration/filtering/
設(shè)置統(tǒng)一采樣率
為此,請將 Sentry.init() 中的 tracesSampleRate 選項設(shè)置為 0 到 1 之間的數(shù)字。設(shè)置此選項后,創(chuàng)建的每個 transaction 都有該百分比的機會被發(fā)送到 Sentry。(因此,例如,如果您將 tracesSampleRate 設(shè)置為 0.2,大約 20% 的 transaction 將被記錄和發(fā)送。)看起來像這樣:
Sentry.init({// ...tracesSampleRate: 0.2, });設(shè)置采樣函數(shù)
要使用采樣函數(shù),請將 Sentry.init() 中的 tracesSampler 選項設(shè)置為一個函數(shù),該函數(shù)將接受 samplingContext 對象并返回介于 0 和 1 之間的采樣率。例如:
Sentry.init({// ...tracesSampler: samplingContext => {// Examine provided context data (including parent decision, if any) along// with anything in the global namespace to compute the sample rate or// sampling decision for this transactionif ("...") {// These are important - take a big samplereturn 0.5;} else if ("...") {// These are less important or happen much more frequently - only take 1%return 0.01;} else if ("...") {// These aren't something worth tracking - drop all transactions like thisreturn 0;} else {// Default sample ratereturn 0.1;}}; });為方便起見,該函數(shù)還可以返回一個布爾值。返回 true 等同于返回 1,并且將保證 transaction 將發(fā)送到 Sentry。返回 false 相當于返回 0,并保證 transaction 不會被發(fā)送到 Sentry。
采樣 Context 數(shù)據(jù)
默認采樣 Context 數(shù)據(jù)
在 transaction 事務(wù)時傳遞給 tracesSampler 的 SamplingContext 對象中包含的信息因平臺和集成(integration)而異。
對于基于瀏覽器的 SDK,它至少包括以下內(nèi)容:
// contents of `samplingContext` {transactionContext: {name: string; // human-readable identifier, like "GET /users"op: string; // short description of transaction type, like "pageload"}parentSampled: boolean; // if this transaction has a parent, its sampling decisionlocation: Location | WorkerLocation; // the window.location or self.location object... // custom context as passed to `startTransaction` }自定義采樣 Context 數(shù)據(jù)
使用自定義檢測創(chuàng)建 transaction 時,您可以通過將數(shù)據(jù)作為可選的第二個參數(shù)傳遞給 startTransaction 來將數(shù)據(jù)添加到 samplesContext。 如果您希望采樣器可以訪問某些數(shù)據(jù),但又不想將其作為標簽(tag)或數(shù)據(jù)(data)附加到 transaction 中,例如敏感信息或太大而無法與 transaction 一起發(fā)送的信息,這將非常有用。例如:
Sentry.startTransaction({// `transactionContext` - will be recorded on transactionname: 'Search from navbar',op: 'search',tags: {testGroup: 'A3',treatmentName: 'eager load',},},// `customSamplingContext` - won't be recorded{// PIIuserId: '12312012',// too big to sendresultsFromLastSearch: { ... }}, );繼承
無論 transaction 的抽樣決策如何,該決策都將傳遞到其子跨度,并從那里傳遞到它們隨后在其他服務(wù)中引起的任何 transaction。 (有關(guān)如何完成傳播的更多信息,請參閱連接服務(wù)。)
- Connecting Services: https://docs.sentry.io/platforms/javascript/performance/
如果當前正在創(chuàng)建的 transaction 是那些后續(xù)事務(wù)之一(換句話說,如果它有父 transaction),則上游(父)采樣決策將始終包含在采樣上下文數(shù)據(jù)中,以便您的 tracesSampler 可以選擇是否和何時繼承該決策。 (在大多數(shù)情況下,繼承是正確的選擇,以避免部分跟蹤痕跡。)
在某些 SDK 中,為了方便起見,tracesSampler 函數(shù)可以返回一個布爾值,這樣如果這是所需的行為,則可以直接返回父級的決策。
tracesSampler: samplingContext => {// always inheritif (samplingContext.parentSampled !== undefined) {return samplingContext.parentSampled}...// rest of sampling logic here }如果您使用的是 tracesSampleRate 而不是 tracesSampler,則決策將始終被繼承。
強制抽樣決策
如果您在 transaction 創(chuàng)建時知道是否要將 transaction 發(fā)送到 Sentry,您還可以選擇將采樣決策直接傳遞給 transaction 構(gòu)造函數(shù)(注意,不是在 customSamplingContext 對象中)。如果您這樣做,transaction 將不受 tracesSampleRate 的約束,也不會運行 tracesSampler,因此您可以指望通過的決策不會被覆蓋。
Sentry.startTransaction({name: "Search from navbar",sampled: true, });優(yōu)先級
transaction 以多種方式結(jié)束抽樣決策。
- 根據(jù) tracesSampleRate 中設(shè)置的靜態(tài)采樣率隨機采樣
- 根據(jù) tracesSampler 采樣函數(shù)返回的采樣率隨機采樣
- tracesSampler 返回的絕對決策(100% 機會或 0% 機會)
- 如果 transaction 有父級,繼承其父級的抽樣決策
- 絕對決策傳遞給 startTransaction
當有可能不止一個發(fā)揮作用時,以下優(yōu)先規(guī)則適用:
Sentry Testkit
在為您的應(yīng)用程序構(gòu)建測試時,您希望斷言正確的流跟蹤(flow-tracking)或錯誤正在發(fā)送到 Sentry,但沒有真正將其發(fā)送到 Sentry 服務(wù)器。 這樣您就不會在測試運行或其他 CI 操作期間用錯誤報告淹沒 Sentry。
注意:Sentry 合作伙伴 Wix 維護 Sentry Testkit。
- Wix:https://wix.github.io/sentry-testkit/
Sentry Testkit 是一個 Sentry 插件,它允許攔截 Sentry 的 report 并進一步檢查正在發(fā)送的數(shù)據(jù)。它使 Sentry 能夠在您的應(yīng)用程序中原生工作,并且通過覆蓋默認 Sentry 的傳輸機制(transport mechanism),報告不會真正發(fā)送,而是本地記錄到內(nèi)存中。 這樣,您可以稍后獲取記錄的報告以供您自己使用、驗證或您在本地開發(fā)/測試環(huán)境中可能擁有的任何其他用途。
Sentry Testkit: https://wix.github.io/sentry-testkit/
安裝
npm install sentry-testkit --save-dev在測試中使用
const sentryTestkit = require("sentry-testkit");const { testkit, sentryTransport } = sentryTestkit();// initialize your Sentry instance with sentryTransport Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",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: https://github.com/wix/sentry-testkit/tree/master/test
Testkit API
Sentry Testkit 由一個非常簡單直接的 API 組成。 請參閱 Sentry Testkit Docs 中的完整 API 描述和文檔。
Sentry Testkit Docs: https://wix.github.io/sentry-testkit/
用法
Sentry 的 SDK 與您的運行時環(huán)境掛鉤,并根據(jù)平臺自動報告錯誤、未捕獲的異常和未處理的拒絕以及其他類型的錯誤。
關(guān)鍵術(shù)語:
- event 是向 Sentry 發(fā)送數(shù)據(jù)的一個實例。 通常,此數(shù)據(jù)是錯誤(error)或異常(exception)。
- issue 是一組相似的事件。
- 事件的報告稱為捕獲(capturing)。當一個事件被捕獲時,它被發(fā)送到 Sentry。
最常見的捕獲形式是捕獲錯誤。可以捕獲為錯誤的內(nèi)容因平臺而異。 一般來說,如果你有一些看起來像異常的東西,它可以被捕獲。對于某些 SDK,您還可以省略 captureException 的參數(shù),Sentry 將嘗試捕獲當前異常。它對于手動向 Sentry 報告錯誤或消息也很有用。
在捕獲事件時,您還可以記錄導(dǎo)致該事件的面包屑(breadcrumbs)。 面包屑與事件不同:它們不會在 Sentry 中創(chuàng)建事件,而是會被緩沖,直到發(fā)送下一個事件。 在我們的面包屑文檔中了解有關(guān)面包屑的更多信息。
breadcrumbs: https://docs.sentry.io/platforms/javascript/guides/react/enriching-events/breadcrumbs/
捕獲 Errors
通過包含和配置 Sentry,我們的 React SDK 會自動附加全局處理程序(global handlers)來捕獲未捕獲的異常和未處理的 promise 拒絕,如官方 ECMAScript 6 標準中所述。您可以通過在 GlobalHandlers 集成中將 onunhandledrejection 選項更改為 false 并手動掛接到每個事件處理程序,然后直接調(diào)用 Sentry.captureException 或 Sentry.captureMessage 來禁用此默認行為。
您可以將 Error 對象傳遞給 captureException() 以將其捕獲為事件。也可以傳遞非 Error(non-Error) 對象和字符串(string),但請注意 Sentry 中的結(jié)果事件(resulting events)可能會丟失堆棧跟蹤。
import * as Sentry from "@sentry/react";try {aFunctionThatMightFail(); } catch (err) {Sentry.captureException(err); }捕獲 Messages
另一種常見的操作是捕獲裸消息。消息是應(yīng)該發(fā)送給 Sentry 的文本信息。通常不會發(fā)出消息,但它們對某些團隊很有用。
Sentry.captureMessage("Something went wrong");設(shè)置 Level
級別 - 類似于日志級別 - 通常基于集成默認添加。 您還可以在事件中覆蓋它。
要設(shè)置超出范圍的級別,您可以為每個事件調(diào)用 captureMessage():
Sentry.captureMessage("this is a debug message", "debug");要在作用域內(nèi)設(shè)置級別,您可以調(diào)用 setLevel():
Sentry.configureScope(function(scope) {scope.setLevel(Sentry.Severity.Warning); });或每個事件:
Sentry.withScope(function(scope) {scope.setLevel("info");Sentry.captureException("info"); });SDK 指紋
所有事件都有一個指紋。具有相同指紋的事件被組合成一個 issue。
默認情況下,Sentry 將運行一種內(nèi)置分組算法,以根據(jù)事件中可用的信息(如堆棧跟蹤stacktrace、異常exception和消息message)生成指紋。 要擴展默認分組行為或完全更改它,您可以使用以下選項的組合:
- Fingerprint Rules: https://docs.sentry.io/product/data-management-settings/event-grouping/fingerprint-rules/
- Stack Trace Rules:https://docs.sentry.io/product/data-management-settings/event-grouping/stack-trace-rules/
在受支持的sdk中,您可以覆蓋 Sentry 的默認分組,該分組將指紋屬性作為字符串數(shù)組傳遞。指紋數(shù)組的長度不受限制。這類似于指紋規(guī)則功能,它總是可用的,可以實現(xiàn)類似的結(jié)果。
- fingerprint-rules:https://docs.sentry.io/product/data-management-settings/event-grouping/fingerprint-rules/
基本示例
在最基本的情況下,直接傳遞值:
function makeRequest(method, path, options) {return fetch(method, path, options).catch(function(err) {Sentry.withScope(function(scope) {// group errors together based on their request and responsescope.setFingerprint([method, path, String(err.statusCode)]);Sentry.captureException(err);});}); }您可以使用變量替換將動態(tài)值填充到通常在服務(wù)器上計算的指紋中。 例如,可以添加值 {{ default }} 以將整個正常生成的分組哈希添加到指紋中。 這些值與服務(wù)器端指紋識別相同。有關(guān)更多信息,請參閱:
Variables: https://docs.sentry.io/product/data-management-settings/event-grouping/fingerprint-rules/#variables
以更大的粒度對錯誤進行分組
您的應(yīng)用程序查詢遠程過程調(diào)用模型 (RPC) 接口或外部應(yīng)用程序編程接口 (API) 服務(wù),因此堆棧跟蹤通常是相同的(即使傳出請求非常不同)。
以下示例將進一步拆分 Sentry 將創(chuàng)建的默認組(由 {{ default }} 表示),并考慮到錯誤對象的一些屬性:
class MyRPCError extends Error {constructor(message, functionName, errorCode) {super(message);// The name of the RPC function that was called (e.g. "getAllBlogArticles")this.functionName = functionName;// For example a HTTP status code returned by the server.this.errorCode = errorCode;} }Sentry.init({...,beforeSend: function(event, hint) {const exception = hint.originalException;if (exception instanceof MyRPCError) {event.fingerprint = ['{{ default }}',String(exception.functionName),String(exception.errorCode)];}return event;} });更進一步地分組錯誤
通用錯誤(例如數(shù)據(jù)庫連接錯誤)具有許多不同的堆棧跟蹤,并且永遠不會組合在一起。
以下示例將通過從數(shù)組中省略 {{ default }} 來完全覆蓋 Sentry 的分組:
class DatabaseConnectionError extends Error {}Sentry.init({...,beforeSend: function(event, hint) {const exception = hint.originalException;if (exception instanceof DatabaseConnectionError) {event.fingerprint = ['database-connection-error'];}return event;} });Source Maps
生成 Source Maps
大多數(shù)現(xiàn)代 JavaScript 編譯器都支持 source maps。以下是一些常用工具的說明。
我們建議使用 Sentry 的 Webpack 插件來配置 source maps 并在構(gòu)建過程中自動上傳它們。
sentry-webpack-plugin: https://github.com/getsentry/sentry-webpack-plugin
source-map-support
要依賴 Sentry 的 source map 解析,您的代碼不能使用 source-map-support 包。 該包以一種阻止我們的處理器正確解析它的方式覆蓋捕獲的堆棧跟蹤。
source-map-support:https://www.npmjs.com/package/source-map-support
Webpack
Sentry 提供了一個方便的 Webpack 插件,可以配置 source maps 并自動將它們上傳到 Sentry。
要使用該插件,您首先需要安裝它:
npm install --save-dev @sentry/webpack-plugin // or yarn add --dev @sentry/webpack-plugin然后,配置它webpack.config.js:
const SentryWebpackPlugin = require("@sentry/webpack-plugin");module.exports = {// other webpack configurationdevtool: 'source-map',plugins: [new SentryWebpackPlugin({// sentry-cli configuration - can also be done directly through sentry-cli// see https://docs.sentry.io/product/cli/configuration/ for detailsauthToken: process.env.SENTRY_AUTH_TOKEN,org: "example-org",project: "example-project",release: process.env.SENTRY_RELEASE,// other SentryWebpackPlugin configurationinclude: ".",ignore: ["node_modules", "webpack.config.js"],}),], };此外,Webpack 插件會自動設(shè)置 window.SENTRY_RELEASE,因此您的 Sentry.init 調(diào)用不需要包含 release 值。
將 Webpack 插件設(shè)置為最后運行的插件;
否則,插件收到的 source maps 可能不是最終的。
高級用法
如果您更喜歡手動上傳 source maps,請配置 Webpack 去輸出 source maps:
module.exports = {devtool: 'source-map',output: {// Make maps auto-detectable by sentry-clifilename: "[name].js",sourceMapFilename: "[name].js.map",// Other `output` configuration},// Other webpack configuration };如果您使用 SourceMapDevToolPlugin 對 source map 生成進行更細粒度的控制,請關(guān)閉 noSources,以便 Sentry 可以在事件堆棧跟蹤中顯示正確的源代碼上下文。
SourceMapDevToolPlugin:https://webpack.js.org/plugins/source-map-dev-tool-plugin
Rollup
您可以配置 Rollup 以生成 source maps,然后您可以使用 sentry-cli 上傳 source maps:
- Rollup:https://rollupjs.org/
- upload using sentry-cli:https://docs.sentry.io/product/cli/releases/#sentry-cli-sourcemaps
SystemJS
SystemJS 可以配置為輸出 source maps,然后您可以使用 sentry-cli 上傳 source maps:
builder.bundle("src/app.js", "dist/app.min.js", {minify: true,sourceMaps: true,sourceMapContents: true, });此示例配置將您的原始、未轉(zhuǎn)換的源代碼內(nèi)聯(lián)到生成的 source map 文件中。Sentry 需要 source map 和您的原始源文件來執(zhí)行反向轉(zhuǎn)換。 如果您選擇不內(nèi)聯(lián)源文件,則除了 source map 外,您還必須使這些源文件可供 Sentry 使用(見下文)。
- SystemJS:https://github.com/systemjs/builder
- upload using sentry-cli:https://docs.sentry.io/product/cli/releases/#sentry-cli-sourcemaps
TypeScript
TypeScript 編譯器可以輸出 source maps,然后您可以使用 sentry-cli 上傳源映射。
將 sourceRoot 屬性配置為 / 以從生成的源代碼引用中去除構(gòu)建路徑前綴。這允許 Sentry 相對于您的源根文件夾匹配源文件:
{"compilerOptions": {"sourceMap": true,"inlineSources": true,"sourceRoot": "/"} }UglifyJS
我們強烈建議您使用更高級的打包器(或轉(zhuǎn)譯器),因為 UglifyJS 配置會變得非常復(fù)雜,并且很難達到預(yù)期的結(jié)果。
UglifyJS 可以配置為輸出 source maps,然后您可以使用 sentry-cli 上傳:
uglifyjs app.js \-o app.min.js.map \--source-map url=app.min.js.map,includeSourcesUglifyJS:https://github.com/mishoo/UglifyJS
上傳 Source Maps
Webpack
Sentry 使用 releases 來將正確的 source maps 與您的事件相匹配。release API 旨在允許您在 Sentry 中存儲源文件(和 source maps)。
您可以在我們的 Webpack 插件的幫助下完成此操作,該插件在內(nèi)部使用我們的 Sentry CLI。
使用我們的 Sentry Webpack 插件文檔了解有關(guān)插件進一步配置的更多信息。sentry-webpack-plugin:https://github.com/getsentry/sentry-webpack-plugin
此外,您需要配置 client 以發(fā)送 release:
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",release: process.env.RELEASE, });您不必使用 RELEASE 環(huán)境變量。只要您上傳的版本與 SDK 的 init 調(diào)用的版本相匹配,您就可以以任何形式提供它們。
Releases API:https://docs.sentry.io/api/releases/
Sentry CLI
使用 sentry-cli 上傳 Source Maps
使用 sentry-cli 上傳 source maps 時,您需要設(shè)置構(gòu)建系統(tǒng)以創(chuàng)建版本(release)并上傳與該版本對應(yīng)的各種源文件。要讓 Sentry 對您的堆棧跟蹤進行解碼,請同時提供:
- 要部署的文件(換句話說,您的編譯/壓縮/打包(transpilation/minification/bundling) 過程的結(jié)果;例如,app.min.js)
- 對應(yīng)的 source maps
如果 source map 文件不包含您的原始源代碼 (sourcesContent),您還必須提供原始源文件。 如果源文件丟失,Sentry CLI 將嘗試自動將源嵌入到您的 source maps 中。
Sentry 使用 releases 將正確的 source maps 與您的事件相匹配。
要創(chuàng)建新版本,請運行以下命令(例如,在發(fā)布期間):
releases:https://docs.sentry.io/product/releases/
sentry-cli releases new <release_name>release 名稱在您的組織中必須是唯一的,并且與您的 SDK 初始化代碼中的 release 選項相匹配。
然后,使用 upload-sourcemaps 命令掃描文件夾中的 source maps,處理它們,并將它們上傳到 Sentry。
您可以通過導(dǎo)航到 [Project] > Project Settings > Source Maps 找到上傳到 Sentry 的工件。
此命令會將所有以 .js 和 .map 結(jié)尾的文件上傳到指定的版本(release)。如果你想改變這些擴展 — 例如,上傳 typescript 源文件 — 使用 --ext 選項:
sentry-cli releases files <release_name> upload-sourcemaps --ext ts --ext map /path/to/files到目前為止,該版本處于草稿狀態(tài)(“unreleased”)。
上傳所有 source maps 后,您的應(yīng)用程序已成功發(fā)布,使用以下命令完成 release:
為方便起見,您可以將 --finalize 標志傳遞給新命令,這將立即完成 release。
有關(guān)更多信息,請參閱我們的 sentry-cli 文檔。
- sentry-cli:https://docs.sentry.io/product/cli/releases/#managing-release-artifacts
Web 應(yīng)用程序可在多個來源訪問的情況并不少見。 請參閱我們關(guān)于多源的文檔以了解如何處理此問題。
- multiple origins:https://docs.sentry.io/platforms/javascript/guides/react/sourcemaps/uploading/multiple-origins/
公開托管
將 source maps 提供給 Sentry 的最可靠方法是上傳它們,因為它減少了網(wǎng)絡(luò)流量并確保將使用正確版本的代碼和源映射。
默認情況下,Sentry 將在您編譯的 JavaScript 文件中查找 source map 指令。這些指令位于最后一行,格式如下:
//# sourceMappingURL=<url>當 Sentry 遇到這樣的指令時,它會解析相對于它所在的源文件的 source map URL,并嘗試一個 HTTP 請求來獲取它。
例如,如果您有一個位于 http://example.org/js/app.min.js 的壓縮的 JavaScript 文件,并且在該文件的最后一行,可以找到以下指令:
//# sourceMappingURL=app.js.mapSentry 將嘗試從 http://example.org/js/app.js.map 獲取 app.js.map。
或者,在 source map 生成期間,您可以指定 source map 所在的完全限定 URL:
//# sourceMappingURL=http://example.org/js/app.js.map雖然從您的服務(wù)器向 Sentry 提供 source maps 是最自然的集成,但并不總是可取的:
- Sentry 可能并不總是能夠訪問您的服務(wù)器。
- 如果您未在 asset URL 中指定版本,則可能存在版本不匹配
- 額外的延遲可能意味著源映射并非適用于所有錯誤。
由于這些原因,最好事先將 source maps 上傳到 Sentry(見下文)。
在防火墻后面工作
雖然推薦的解決方案是將您的源工件(打包轉(zhuǎn)譯后的代碼)上傳到 Sentry,但有時需要允許來自 Sentry 的內(nèi)部 IP 的通信。
有關(guān) Sentry public IP 的更多信息,請參閱:
- IP Ranges:https://docs.sentry.io/product/security/ip-ranges/
安全訪問 Source Maps
如果您想對 source maps 保密并選擇不將 source maps 直接上傳到 Sentry,您可以在項目設(shè)置中啟用 “Security Token” 選項。
這將導(dǎo)致從 Sentry 的服務(wù)器發(fā)出的來自你的 “Allowed Domains” 的 url 的出站請求附加 HTTP header X-Sentry-Token 頭:
GET /assets/bundle.min.js X-Sentry-Token: {token}token 是您在項目設(shè)置中定義的安全值。然后,您可以配置您的 Web 服務(wù)器以允許在此 header/token 對存在時訪問您的 source maps。 您也可以覆蓋默認 header 名稱 (X-Sentry-Token) 并使用 HTTP Basic Authentication,例如通過傳遞 Authorization: Basic {encoded_password}。
多個 Origin
Web 應(yīng)用程序可在多個來源訪問的情況并不少見。例如:
- 網(wǎng)站可通過 https 和 http 運行
- 地理定位網(wǎng)址:例如 https://us.example.com、https://eu.example.com
- 多個靜態(tài) CDN:如 https://static1.example.com、https://static2.example.com
- 客戶特定的域/子域
在這種情況下,相同的 JavaScript 和 source map 文件可能位于兩個或多個不同的來源。 在這種情況下,我們建議在路徑上使用我們特殊的波浪號 (~) 前綴。
例如,如果您有以下內(nèi)容:
- https://static1.example.com/js/app.js
- https://static2.example.com/js/app.js
您可以使用 ~/js/app.js 的 URL 上傳。這將告訴 Sentry 忽略域并將 artifact 用于任何來源。
此外,您還可以以多個名稱上傳同一個文件。 在引擎蓋(hood)下 Sentry 將對這些進行重復(fù)數(shù)據(jù)刪除。
~ 前綴告訴 Sentry 對于給定的 URL,路徑為 /js/app.js 的協(xié)議和主機名的任何組合都應(yīng)該使用這個工件。
驗證文件
確保 source maps 本身有效并正確上傳可能非常具有挑戰(zhàn)性。 為了解決這個問題,我們維護了一個在線驗證工具,可用于針對您的托管源測試您的 source map:sourcemaps.io。
- https://sourcemaps.io/
此外,您可以在使用 sentry-cli 上傳 source maps 時使用 --validate 標志,這將嘗試在本地解析源映射并查找引用。 請注意,在已知情況下,驗證標志將在設(shè)置正確時指示失敗(如果您引用了外部 source maps,則驗證工具將指示失敗)。
除了驗證步驟之外,您還可以檢查這些:
- 確保您的文件的 URL 前綴正確。 這很容易出錯。
- 上傳壓縮文件的匹配 source maps。
- 確保您在服務(wù)器上的壓縮文件實際上引用了您的文件。
最佳實踐
一個簡單的設(shè)置
在這個簡單的項目中,minified/transpiled 的文件及其 source maps 位于同一目錄中:
├── build/ │ ├── worker.js │ ├── worker.js.map │ ├── app.js │ ├── app.js.map │ ├── index.html ├── package.json ├── public/ │ └── index.html ├── sentry.properties ├── src/ │ ├── app.js │ └── worker.js ├── webpack.config.js對于這個項目,我們可以使用一個簡單的 Sentry 配置:
const SentryWebpackPlugin = require("@sentry/webpack-plugin"); // ... plugins: [new SentryWebpackPlugin({authToken: process.env.SENTRY_AUTH_TOKEN,org: "example-org",project: "example-project",include: "build",configFile: "sentry.properties",release: process.env.SENTRY_RELEASE,}), ], // ...我們建議使用 Webpack 插件將 source maps 集成到 Sentry。 如果您的項目中沒有使用 Webpack,則可以使用 Sentry CLI。
一致的版本
要讓 Sentry 將錯誤堆棧跟蹤與您的 source maps 相關(guān)聯(lián),請將您的版本號定義為 Webpack 插件選項或 Sentry CLI 參數(shù)(無論您使用哪個)。如果您使用 Sentry CLI,您還應(yīng)該在 Sentry.init() 調(diào)用中定義相同的版本號。 確保版本號一致性的最簡單方法是將其設(shè)置為項目中的環(huán)境變量:
# ... SENTRY_RELEASE="1.2.3" # ...然后,如果您使用的是 sentry-webpack-plugin:
// ... new SentryWebpackPlugin({// ... other optionsrelease: process.env.SENTRY_RELEASE, }); // ...或者,如果您使用的是 Sentry CLI:
sh sentry-cli releases new "$SENTRY_RELEASE" sentry-cli releases files "$SENTRY_RELEASE" upload-sourcemaps /path/to/sourcemaps
// ... Sentry.init({// ... other optionsrelease: process.env.SENTRY_RELEASE, }); // ...正確的 Source Paths
您的 release artifacts(bundle 文件和源 source maps)的文件名應(yīng)與堆棧跟蹤中報告的路徑匹配。 您可以使用上傳配置來調(diào)整文件的名稱。 Webpack 插件和 Sentry CLI 都有相同的選項;下面介紹了與 source maps 相關(guān)的內(nèi)容。還可以使用我們的 RewriteFrames 集成來調(diào)整堆棧跟蹤內(nèi)的路徑。
根據(jù)您的設(shè)置,您可能需要在開發(fā)和生產(chǎn)環(huán)境中為 source maps 進行不同的配置,因為堆棧跟蹤中的路徑可能不同。
Webpack 和 Sentry CLI 的選項
這些選項和示例將有助于集成您的source maps。
include
此選項接受一個或多個路徑來遞歸掃描源和 *.map 文件。例如:
- include: './app/.next'
- include: './build'
- 包括:['./src', './lib']
- include: '.'
rewrite
允許重寫匹配的 source maps,以便在可能的情況下將索引映射扁平化并內(nèi)聯(lián)缺失的源。默認為 true。
應(yīng)該啟用此選項以使 stripPrefix 和 stripCommonPrefix 工作。
urlPrefix
此選項在所有文件名的開頭添加一個公共前綴。默認為 ~/,這是一個匹配任何 scheme 和 hostname 的通配符(http://my.web.site/path/to/script.js 的 http://my.web.site/ 部分)。
當應(yīng)用程序的入口點(通常是瀏覽器端的 index.html 和 Node 的 index.js)位于源/源映射文件之上一個或多個級別時,此選項很有用,如下例所示:
├── build/ │ ├── index.html │ ├── static/ │ │ ├── app.js │ │ ├── app.js.map在這種情況下,請按照以下示例進行配置:
// ... new SentryWebpackPlugin({// ...include: "build/static/",urlPrefix: "~/static/"// ... }), // ...stripPrefix
此選項從 sourcemap 中(例如,在 sources entry 中)引用的文件名中刪除給定的前綴。 當您需要修剪捆綁器/開發(fā)(bundler/development)服務(wù)器可能添加到文件名的額外前綴時,這很有用,例如 webpack://_N_E/。
請注意,使用 stripPrefix 選項不會更改上傳文件的名稱。 當您將目標文件的父文件夾作為不需要的前綴時,請在包含 Webpack 插件選項或傳遞給 sentry-cli 的 path/to/sourcemaps 中包含要刪除的部分。例如,如果您的文件存儲在 ./build/static/js/ 并且您在 Webpack 插件配置中有 include: "build",您的文件將使用類似 ~/static/js/bundle.js 的名稱上傳。如果您更新您的配置 include: "build/static/js",您的文件將上傳為 ~/bundle.js(等等)。
調(diào)整幀(Frames)
或者,您可以使用 Sentry 的 RewriteFrames 集成來微調(diào)堆棧跟蹤內(nèi)的路徑。
import { RewriteFrames } from "@sentry/integrations";Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [new RewriteFrames({// ... options}),], });對 Source Maps 進行故障排除
Source maps 有時很難開始。如果您遇到問題:
驗證在您的 SDK 中配置了一個 release
要定位和應(yīng)用上傳的 source maps,需要通過 CLI 或 API(以及隨其上傳的正確工件)創(chuàng)建 release,并且需要在您的 SDK 配置中指定新創(chuàng)建的 release 的名稱。
要驗證這一點,請從 Sentry UI 打開 issue 并檢查 release 是否已配置。如果屏幕右側(cè)的 “Release” 旁邊顯示 “not configured” 或 “N/A”(或者如果您在標簽列表中沒有看到 release tag),則需要返回并標記你的錯誤。如果設(shè)置正確,您將看到 "Release: my_example_release"。
驗證工件(artifacts)已上傳
正確配置您的 release 并標記問題后,您可以通過導(dǎo)航到 [Project] ? Project Settings ? Source Maps 找到上傳到 Sentry 的工件。
此外,請確保所有必要的文件都可用。要讓 Sentry de-minify 堆棧跟蹤,您必須同時提供 minify 的文件(例如 app.min.js)和相應(yīng)的 source map。如果 source map 文件不包含您的原始源代碼 (sourcesContent),您必須另外提供原始源代碼文件。或者,sentry-cli 會自動將源代碼(如果缺少)嵌入到您的 source maps 中。
驗證 sourceMappingURL 是否存在
一些 CDN 會自動從靜態(tài)文件(包括 JavaScript 文件)中去除注釋。 這可能會導(dǎo)致刪除 JavaScript 文件的 sourceMappingURL 指令,因為它被視為注釋。例如,CloudFlare 有一個名為 Auto-Minify 的功能,如果啟用它,它將去除 sourceMappingURL。
- Auto-Minify:https://blog.cloudflare.com/an-all-new-and-improved-autominify/
仔細檢查您部署的最終 JavaScript 文件是否存在 sourceMappingURL。
或者,您可以在 minify 的文件上設(shè)置 SourceMap HTTP header,而不是 sourceMappingURL。如果此 header 存在,Sentry 將使用它來發(fā)現(xiàn) source map 的位置。
驗證 artifact 發(fā)布值是否與您的 SDK 中配置的值匹配
每當您使用分發(fā)標識符(SDK 中的 dist 配置選項)時,在 source map 上傳期間必須使用相同的值。相反,如果您的 source map 使用 dist 值上傳,則必須在您的 SDK 中設(shè)置相同的值。要將 dist 值添加到您上傳的 source maps,請使用 --dist 標志和 sentry-cli 或 dist 選項和 @sentry/webpack-plugin。要在 SDK 中設(shè)置 dist 值,請使用 Sentry.init() 中的 dist 選項。
要驗證 SDK 中的分發(fā)設(shè)置是否正確,請在 Sentry UI 中打開一個 issue 并檢查 dist 標簽是否存在。對于工件,轉(zhuǎn)到項目設(shè)置中的 Source Maps 頁面,選擇您剛剛檢查的事件中顯示的 release,并驗證 dist 值(在 upload time 旁邊的小橢圓中)與事件上的值匹配。
驗證 artifact 名稱與 sourceMappingURL 值匹配
bundled 或 minified 的 JavaScript 文件最后一行的 sourceMappingURL 注釋告訴 Sentry(或瀏覽器)在哪里找到相應(yīng)的 source map。這可以是完全限定的 URL、相對路徑或文件名本身。 將 artifact 上傳到 Sentry 時,您必須使用文件解析為的值命名源映射文件。
也就是說,如果您的文件類似于:
// -- end script.min.js //# sourceMappingURL=script.min.js.map并托管在 http://example.com/js/script.min.js,然后 Sentry 將在 http://example.com/js/script.min.js.map 查找該 source map 文件。 因此,您上傳的 artifact 必須命名為 http://example.com/js/script.min.js.map(或 ~/js/script.min.js.map)。
或者,如果您的文件類似于:
//-- end script.min.js //# sourceMappingURL=https://example.com/dist/js/script.min.js.map那么您上傳的 artifact 也應(yīng)該命名為:
https://example.com/dist/js/script.min.js.map(或 ~/dist/js/script.min.js.map)。
最后,如果您的文件類似于:
//-- end script.min.js //# sourceMappingURL=../maps/script.min.js.map那么您上傳的 artifact 應(yīng)命名為 https://example.com/dist/maps/script.min.js.map(或 ~/dist/maps/script.min.js.map)。
驗證 artifact 名稱與堆棧跟蹤幀匹配
如果您已上傳 source maps,但它們并未應(yīng)用于 Sentry 問題中的代碼,請查看事件的 JSON 并查找 abs_path 以準確查看我們嘗試解析文件的位置 - 對于 例如,http://localhost:8000/scripts/script.js(對于堆棧跟蹤中的每一幀,abs_path 將出現(xiàn)一次 - 將其與未 deminified 的文件匹配。)。 可以在事件發(fā)生日期旁邊的 issue 頁面頂部找到指向 JSON 視圖的鏈接。上傳的 artifact 名稱必須與這些值匹配。
如果您的路徑中有動態(tài)值(例如,https://www.site.com/{some_value}/scripts/script.js),您可能需要使用 rewriteFrames 集成來更改您的 abs_path 值。
使用 sentry-cli
如果您的 sourceMappingURL 注釋類似于:
// -- end script.min.js (located at http://localhost:8000/scripts/script.min.js) //# sourceMappingURL=script.min.js.map正確上傳這些文件的示例 sentry-cli 命令如下所示(假設(shè)您在 /scripts 目錄中,從上一級目錄運行 Web 服務(wù)器,這就是我們使用 --url-prefix 選項的原因) :
sentry-cli releases files VERSION upload-sourcemaps . --url-prefix '~/scripts'此命令上傳當前目錄中的所有 JavaScript 文件。 Sentry 中的 Artifacts 頁面現(xiàn)在應(yīng)如下所示:
~/scripts/script.js ~/scripts/script.min.js ~/scripts/script.min.js.map或者,您可以指定要上傳的文件。 例如:
sentry-cli releases files VERSION upload-sourcemaps script.min.js script.min.js.map --url-prefix '~/scripts'您還可以使用完全限定的 URL 上傳它。例如:
sentry-cli releases files VERSION upload-sourcemaps . --url-prefix 'http://localhost:8000/scripts'使用 API
您也可以使用 API 上傳 artifact。
curl -X POST \https://sentry.io/api/0/organizations/ORG_SLUG/releases/VERSION/files/ \-H 'Authorization: Bearer AUTH_TOKEN' \-H 'content-type: multipart/form-data' \-F file=@script.min.js.map \-F 'name=~/scripts/script.min.js.map'使用 ~
~ 在 Sentry 中用于替換 scheme 和 domain。
http://example.com/dist/js/script.js 將匹配 ~/dist/js/script.js 或 http://example.com/dist/js/script.js
但不會匹配 ~/script.js。
在發(fā)生錯誤之前驗證 artifact 已上傳
Sentry 期望給定版本中的源代碼和 source maps 在該 release 中發(fā)生錯誤之前上傳到 Sentry。
如果您在 Sentry 捕獲錯誤后上傳 artifact,Sentry 將不會返回并追溯將任何源注釋(source annotations)應(yīng)用于這些錯誤。 只有在 artifact 上傳后觸發(fā)的新錯誤才會受到影響。
驗證您的 source maps 是否正確構(gòu)建
我們維護一個在線驗證工具,可用于針對您的托管源測試您的source maps:sourcemaps.io。
- https://sourcemaps.io/
或者,如果您使用 Sentry CLI 將 source maps 上傳到 Sentry,您可以使用 --validate 命令行選項來驗證您的 source maps 是否正確。
驗證您的 source maps 在本地工作
如果您發(fā)現(xiàn) Sentry 沒有正確映射文件名、行或列映射,您應(yīng)該驗證您的 source maps 是否在本地運行。為此,您可以將 Node.js 與 Mozilla 的source-map library 結(jié)合使用。
- https://github.com/mozilla/source-map
首先,將 source-map 作為 npm 模塊全局安裝:
npm install -g source-map然后,編寫一個腳本來讀取您的 source map 文件并測試映射。 下面是一個例子:
var fs = require("fs"),path = require("path"),sourceMap = require("source-map");// file output by Webpack, Uglify, and so forth var GENERATED_FILE = path.join(".", "app.min.js.map");// line and column located in your generated file (for example, the source of your error // from your minified file) var GENERATED_LINE_AND_COLUMN = { line: 1, column: 1000 };var rawSourceMap = fs.readFileSync(GENERATED_FILE).toString(); new sourceMap.SourceMapConsumer(rawSourceMap).then(function(smc) {var pos = smc.originalPositionFor(GENERATED_LINE_AND_COLUMN);// should see something like:// { source: 'original.js', line: 57, column: 9, name: 'myfunc' }console.log(pos); });如果您在本地獲得與通過 Sentry 獲得的結(jié)果相同(不正確)的結(jié)果,請仔細檢查您的 source map 生成配置。
驗證您的源文件不是太大
對于單個 artifact,Sentry 接受的最大文件大小為 40 MB。
用戶通常會達到此限制,因為他們在臨時構(gòu)建階段傳輸源文件。例如,在 Webpack/Browserify 合并所有源文件之后,但在 minification 之前。 如果可能,請發(fā)送原始源文件。
驗證 artifact 沒有被 gzip
Sentry API 目前僅適用于以純文本(UTF-8 編碼)形式上傳的 source maps 和源文件。如果文件以壓縮格式(例如 gzip)上傳,它們將不會被正確解釋。
這有時發(fā)生在生成 pre-compressed minified 文件的構(gòu)建腳本和插件中。 例如,Webpack 的 compression 插件。您需要禁用此類插件并在生成的 source maps/source files 上傳到 Sentry 后執(zhí)行壓縮。
- https://github.com/webpack/compression-webpack-plugin
驗證 worker 與 Web 共享相同的卷(如果通過 Docker 運行自托管 Sentry)
Sentry 在其 worker 中進行 source map 計算。 這意味著 worker 需要訪問通過前端上傳的文件。仔細檢查 cron worker 和 web worker 是否可以從同一個磁盤讀取/寫入文件。
故障排除
如果您需要幫助解決 Sentry JavaScript SDK integration 問題,您可以閱讀此處記錄的邊緣案例。
調(diào)試附加數(shù)據(jù)
您可以查看事件的 JSON payload 以了解 Sentry 如何在事件中存儲其他數(shù)據(jù)。數(shù)據(jù)的形狀可能與描述不完全匹配。
有關(guān)更多詳細信息,請參閱有關(guān)事件有效負載的完整文檔。
- https://develop.sentry.dev/sdk/event-payloads/
最大 JSON Payload 大小
maxValueLength 的默認值為 250,但如果您的消息較長,您可以根據(jù)需要調(diào)整此值。 請注意,并非每個值都受此選項影響。
CORS 屬性和 Header
要了解從不同來源的腳本引發(fā)的 JavaScript 異常,請執(zhí)行以下兩項操作:
腳本屬性告訴瀏覽器 “anonymously” 獲取目標文件。 請求此文件時,瀏覽器不會將潛在的用戶識別信息(如 cookie 或 HTTP 憑據(jù))傳輸?shù)椒?wù)器。
跨域資源共享 (CORS) 是一組 API(主要是 HTTP header),用于規(guī)定文件應(yīng)該如何跨域下載和提供服務(wù)。
通過設(shè)置 Access-Control-Allow-Origin: *,服務(wù)器向瀏覽器表明任何來源都可以獲取此文件。 或者,您可以將其限制為您控制的已知來源:
Access-Control-Allow-Origin: https://www.example.com大多數(shù)社區(qū) CDN 正確設(shè)置了 Access-Control-Allow-Origin header。
$ curl --head https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.js | \grep -i "access-control-allow-origin"Access-Control-Allow-Origin: *意外的 OPTIONS 請求
如果您的應(yīng)用程序由于執(zhí)行額外的 OPTIONS 請求而開始行為異常,則很可能是不需要的 sentry-trace 請求 header 的問題,當您在瀏覽器 SDK 中為我們的 Tracing Integration 使用過于通用的配置時可能會發(fā)生這種情況。
要解決此問題,請在 SDK 初始化期間更改 trackingOrigins 選項。 有關(guān)更多詳細信息,請參閱我們的性能監(jiān)控文檔中的自動檢測。
- https://docs.sentry.io/platforms/javascript/performance/instrumentation/automatic-instrumentation/#tracingorigins
instrument.js Console Log 語句的行號
如果調(diào)試時在您的控制臺中顯示了 instrument.js,請將 Sentry 添加到您的框架黑盒設(shè)置中,例如:/@sentry/,以便 Chrome 在調(diào)試時忽略 SDK 堆棧幀。
- blackboxing:https://docs.sentry.io/platforms/javascript/guides/react/troubleshooting/
處理廣告攔截器(Ad-Blockers)
當您使用我們的 CDN 時,廣告攔截或腳本攔截擴展可能會阻止我們的 SDK 被正確獲取和初始化。因此,對 SDK API 的任何調(diào)用都將失敗,并可能導(dǎo)致您的應(yīng)用程序出現(xiàn)意外行為。
此外,即使正確下載并初始化 SDK,也可能會阻止需要接收捕獲數(shù)據(jù)的 Sentry 端點。這將阻止任何錯誤報告、會話運行狀況或性能數(shù)據(jù)的傳遞,從而使其在 sentry.io 中實際上不可用。
您可以通過上述多種方式解決第一個 issue 。但是,端點阻塞只能使用隧道解決。
使用 tunnel 選項
隧道是一個 HTTP 端點,充當 Sentry 和您的應(yīng)用程序之間的代理。 由于您控制此服務(wù)器,因此不會有任何發(fā)送到它的請求被阻止的風險。 當端點位于同一個源下時(盡管它不必為了隧道工作),瀏覽器不會將任何對端點的請求視為第三方請求。因此,這些請求將應(yīng)用不同的安全措施,默認情況下不會觸發(fā)廣告攔截器。可以在下面找到流程的快速摘要。
從 JavaScript SDK 6.7.0 版開始,您可以使用 tunnel 選項告訴 SDK 將事件傳送到配置的 URL,而不是使用 DSN。 這允許 SDK 從查詢參數(shù)中刪除 sentry_key,這是廣告攔截器首先阻止發(fā)送事件的主要原因之一。此選項還會阻止 SDK 發(fā)送預(yù)檢請求,這是需要在查詢參數(shù)中發(fā)送 sentry_key 的要求之一。
要啟用 tunnel 選項,請在 Sentry.init 調(diào)用中提供相對或絕對 URL。當您使用相對 URL 時,它是相對于當前來源的,這是我們推薦的形式。使用相對 URL 不會觸發(fā)預(yù)檢 CORS 請求,因此不會阻止任何事件,因為廣告攔截器不會將這些事件視為第三方請求。
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",tunnel: "/tunnel", });配置完成后,所有事件都將發(fā)送到 /tunnel 端點。 但是,此解決方案需要在服務(wù)器上進行額外配置,因為現(xiàn)在需要解析事件并將其重定向到 Sentry。 這是您的服務(wù)器組件的示例:
<?php // Change $host appropriately if you run your own Sentry instance. $host = "sentry.io"; // Set $known_project_ids to an array with your Sentry project IDs which you // want to accept through this proxy. $known_project_ids = array( );$envelope = stream_get_contents(STDIN); $pieces = explode("\n", $envelope, 2); $header = json_decode($pieces[0], true); if (isset($header["dsn"])) {$dsn = parse_url($header["dsn"]);$project_id = intval(trim($dsn["path"], "/"));if (in_array($project_id, $known_project_ids)) {$options = array('http' => array('header' => "Content-type: application/x-sentry-envelope\r\n",'method' => 'POST','content' => $envelope));echo file_get_contents("https://$host/api/$project_id/envelope/",false,stream_context_create($options));} } // Requires .NET Core 3.1 and C# 9 or higher using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text.Json; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http;// Change host appropriately if you run your own Sentry instance. const string host = "sentry.io"; // Set knownProjectIds to a list with your Sentry project IDs which you // want to accept through this proxy. var knownProjectIds = new HashSet<string>() { };var client = new HttpClient(); WebHost.CreateDefaultBuilder(args).Configure(a =>a.Run(async context =>{context.Request.EnableBuffering();using var reader = new StreamReader(context.Request.Body);var header = await reader.ReadLineAsync();var headerJson = JsonSerializer.Deserialize<Dictionary<string, object>>(header);if (headerJson.TryGetValue("dsn", out var dsnString)&& Uri.TryCreate(dsnString.ToString(), UriKind.Absolute, out var dsn)){var projectId = dsn.AbsolutePath.Trim('/');if (knownProjectIds.Contains(projectId) && string.Equals(dsn.Host, host, StringComparison.OrdinalIgnoreCase)) {context.Request.Body.Position = 0;await client.PostAsync($"https://{dsn.Host}/api/{projectId}/envelope/",new StreamContent(context.Request.Body));}}})).Build().Run();查看我們的示例存儲庫以了解更多信息。
- https://github.com/getsentry/examples/tree/master/tunneling
如果您的用例與 SDK 包本身被阻止有關(guān),以下任何一種解決方案都可以幫助您解決此問題。
直接使用 Package
處理腳本阻塞擴展的最佳方法是直接通過 npm 使用 SDK 包并將其與您的應(yīng)用程序捆綁在一起。 這樣,您就可以確保代碼始終如您所愿。
第二種方法是從我們的 CDN 下載 SDK 并自己托管。這樣,SDK 仍將與您的其余代碼分開,但您可以確定它不會被阻止,因為它的來源將與您網(wǎng)站的來源相同。
您可以使用 curl 或任何其他類似工具輕松獲取它:
curl https://browser.sentry-cdn.com/5.20.1/bundle.min.js -o sentry.browser.5.20.1.min.js -s使用 JavaScript Proxy API
最后一個選項是使用 Proxy 保護,這將確保您的代碼不會中斷,即使您調(diào)用我們的 SDK,它被阻止。 除了 Internet Explorer 之外的所有瀏覽器都支持 Proxy。此外,如果 Proxy 不在您用戶的任何瀏覽器中,它將被悄悄跳過,因此您不必擔心它會破壞任何內(nèi)容。
將此代碼段直接放在包含我們的 CDN 包的 <script> 標簽上方。可讀格式的代碼片段如下所示:
if ("Proxy" in window) {var handler = {get: function(_, key) {return new Proxy(function(cb) {if (key === "flush" || key === "close") return Promise.resolve();if (typeof cb === "function") return cb(window.Sentry);return window.Sentry;}, handler);},};window.Sentry = new Proxy({}, handler); }如果您想直接復(fù)制和粘貼代碼段,這里將其 minified:
<script>if ("Proxy" in window) {var n = {get: function(o, e) {return new Proxy(function(n) {return "flush" === e || "close" === e? Promise.resolve(): "function" == typeof n? n(window.Sentry): window.Sentry;}, n);},};window.Sentry = new Proxy({}, n);} </script>直接使用 Client
為了能夠管理多個 Sentry 實例而它們之間沒有任何沖突,您需要創(chuàng)建自己的 Client。 如果您的應(yīng)用程序集成在其中,這也有助于防止跟蹤任何父應(yīng)用程序錯誤。在這個例子中,我們使用 @sentry/browser 但它也適用于 @sentry/node。
import { BrowserClient } from "@sentry/browser";const client = new BrowserClient({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", });client.captureException(new Error("example"));雖然上面的示例應(yīng)該可以正常工作,但 Client 上缺少一些方法,如 configureScope 和 withScope,因為 Hub 負責狀態(tài)管理。這就是為什么創(chuàng)建新 Hub 并將 Client 綁定到它可能更容易的原因。結(jié)果是一樣的,但你也會得到狀態(tài)管理。
import { BrowserClient, Hub } from "@sentry/browser";const client = new BrowserClient({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", });const hub = new Hub(client);hub.configureScope(function(scope) {scope.setTag("a", "b"); });hub.addBreadcrumb({ message: "crumb 1" }); hub.captureMessage("test");try {a = b; } catch (e) {hub.captureException(e); }hub.withScope(function(scope) {hub.addBreadcrumb({ message: "crumb 2" });hub.captureMessage("test2"); });處理集成
集成是在 Client 上設(shè)置的,如果您需要處理多個 Client 和 Hub,您還必須確保正確進行集成處理。這是一個如何使用多個 Client 和多個運行全局集成的 Hub 的工作示例。
import * as Sentry from "@sentry/browser";// Very happy integration that'll prepend and append very happy stick figure to the message class HappyIntegration {constructor() {this.name = "HappyIntegration";}setupOnce() {Sentry.addGlobalEventProcessor(event => {const self = Sentry.getCurrentHub().getIntegration(HappyIntegration);// Run the integration ONLY when it was installed on the current Hubif (self) {event.message = `\\o/ ${event.message} \\o/`;}return event;});} }HappyIntegration.id = "HappyIntegration";const client1 = new Sentry.BrowserClient({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [...Sentry.defaultIntegrations, new HappyIntegration()],beforeSend(event) {console.log("client 1", event);return null; // Returning null does not send the event}, }); const hub1 = new Sentry.Hub(client1);const client2 = new Sentry.BrowserClient({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", // Can be a different DSNintegrations: [...Sentry.defaultIntegrations, new HappyIntegration()],beforeSend(event) {console.log("client 2", event);return null; // Returning null does not send the event}, }); const hub2 = new Sentry.Hub(client2);hub1.run(currentHub => {// The hub.run method makes sure that Sentry.getCurrentHub() returns this hub during the callbackcurrentHub.captureMessage("a");currentHub.configureScope(function(scope) {scope.setTag("a", "b");}); });hub2.run(currentHub => {// The hub.run method makes sure that Sentry.getCurrentHub() returns this hub during the callbackcurrentHub.captureMessage("x");currentHub.configureScope(function(scope) {scope.setTag("c", "d");}); });第三方 Promise 庫
當您包含和配置 Sentry 時,我們的 JavaScript SDK 會自動附加 global handlers 以 capture 未捕獲的 exceptions 和未處理的 promise rejections。 您可以通過在 GlobalHandlers 集成中將 onunhandledrejection 選項更改為 false 并手動掛接到每個事件處理程序,然后直接調(diào)用 Sentry.captureException 或 Sentry.captureMessage 來禁用此默認行為。
如果您使用第三方庫來實現(xiàn) Promise,您可能還需要管理您的配置。 此外,請記住,瀏覽器通常會實施安全措施,在提供來自不同來源的腳本文件時阻止錯誤報告。
具有“非錯誤異常Non-Error Exception”的事件
如果您看到錯誤消息 “Non-Error exception (or promise rejection) captured with keys: x, y, z.”,這會發(fā)生在您 a) 使用 plain object 調(diào)用 Sentry.captureException() 時,b) 拋出一個 plain object,或者 c) 拒絕一個帶有 plain object 的 promise。
您可以在 “Additional Data” 部分的 __serialized__ 條目中查看有問題的非錯誤對象的內(nèi)容。
為了更好地了解這些錯誤事件,我們建議根據(jù) __serialized__ 數(shù)據(jù)的內(nèi)容找到 plain object 被傳遞或拋出到 Sentry 的位置,然后將 plain object 轉(zhuǎn)換為 Error 對象。
支持的瀏覽器
Sentry 的 JavaScript SDK 支持以下瀏覽器:
| 4.4 | latest | latest | IE 10 | iOS12 | latest | latest |
| 5.0 | IE 11 | iOS13 | ||||
| 6.0 | ||||||
| 7.1 | ||||||
| 8.1 | ||||||
| 9.0 | ||||||
| 10.0 |
支持 <= IE 11
在 5.7.0 版本之前,我們的 JavaScript SDK 需要一些 polyfills 用于舊版瀏覽器,如 IE 11 及更低版本。如果您正在使用它,請在加載我們的 SDK 之前升級到最新版本或添加下面的腳本標簽。
<script src="https://polyfill.io/v3/polyfill.min.js?features=Promise%2CObject.assign%2CString.prototype.includes%2CNumber.isNaN"></script>我們需要以下 polyfill:
- Promise
- Object.assign
- Number.isNaN
- String.prototype.includes
此外,請記住在 HTML 頁面頂部定義有效的 HTML doctype,以確保 IE 不會進入兼容模式(compatibility mode)。
公眾號:黑客下午茶總結(jié)
以上是生活随笔為你收集整理的Sentry For Vue 完整接入详解(2021 Sentry v21.8.x)前方高能预警!三万字,慎入!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html正方形符号,HTML特殊字符显示
- 下一篇: 渠道商用假流量冒充真实用户