[轉] vue前端異常監控sentry實踐

1. 監控原理

1.1 onerror

傳統的前端監控原理分爲異常捕獲和異常上報。通常使用onerror捕獲前端錯誤:javascript

window.onerror = (msg, url, line, col, error) => { console.log('onerror') // TODO }

1.2 promise

可是onerror事件沒法捕獲到網絡異常的錯誤(資源加載失敗、圖片顯示異常等),例如img標籤下圖片url 404 網絡請求異常的時候,onerror沒法捕獲到異常,此時須要監聽unhandledrejection前端

window.addEventListener('unhandledrejection', function(err) { console.log(err) })

1.3 上報

捕獲的異常如何上報?經常使用的發送形式主要有兩種:vue

  1. 經過 ajax 發送數據(xhr、jquery...)
  2. 動態建立 img 標籤的形式
function report(error) { var reportUrl = 'http://xxxx/report' new Image().src = reportUrl + '?error=' + error }

1.4 使用sentry

sentry是一套開源的強大的前端異常監控上報工具,官網地址:https://sentry.io,官方提供瞭如何搭建sentry服務,此處略過安裝流程,直接使用已有的服務。java

1.5 與vue結合

針對vue,sentry官方推薦使用raven配合sentry進行異常捕獲和上報。而在vue中,vue提供了錯誤捕獲方法vue error handler,官方也推薦使用錯誤追蹤服務 sentry 並經過vue error handler選項提供了官方支持。jquery

2. 安裝raven

raven是sentry官方針對vue推薦的插件,yarn安裝raven-js便可。ajax

$ yarn add raven-js

3. 初始化sentry

初始化引入Vue、Raven、RavenVue便可,sentry能主動監聽上報錯誤。promise

import Raven from 'raven-js' import RavenVue from 'raven-js/plugins/vue' const dsn = 'https://<key1>@sentry.io/<key2>' Raven.config(dsn).addPlugin(RavenVue, Vue).install()

4. 手動上報

對於一些其餘信息,如提示日誌等,沒法自動捕獲,須要手動進行上報。網絡

log (data = null, type = 'error', options = {}) { // 添加麪包屑 Raven.captureBreadcrumb({ message: data, category: 'manual message' }) // 異常上報 if (data instanceof Error) { Raven.captureException(data, { level: type, logger: 'manual exception', tags: { options: options } }) } else { Raven.captureException('error', { level: type, logger: 'manual data', extra: { data: data, options: this.options, date: new Date() } }) } }

5. 封裝異常上報類 Report.js

針對上述內容,封裝異常上報類Report,使用單例模式,避免監控類重複實例化。工具

/**
 * by csxiaoyao
 * 2019.03.17
 * sunjianfeng@csxiaoyao.com
 */
import Raven from 'raven-js' import RavenVue from 'raven-js/plugins/vue' class Report { static dsn = 'https://<key1>@sentry.io/<key2>' constructor (Vue, options = {}) { if (process.env.NODE_ENV === 'production') { // TODO } this.Vue = Vue this.options = options } /** * 單例模式 */ static getInstance (Vue, options) { if (!(this.instance instanceof this)) { this.instance = new this(Vue, options) this.instance.install() this.instance.registerError() } return this.instance } /** * init */ install () { Raven.config(Report.dsn, { release: '1.0.0', environment: 'production' // whitelistUrls: [/localhost/, /test\.oa\.com/] }).addPlugin(RavenVue, this.Vue).install() // 記錄用戶信息 Raven.setUserContext({ user: this.options.user || '' }) // 設置全局tag標籤 Raven.setTagsContext({ environment: this.options.env || '' }) } /** * 註冊全局錯誤處理 */ registerError () { // 監聽error window.onerror = (msg, url, line, col, error) => { console.log('onerror') if (msg !== 'Script error.' && !url) { return true } setTimeout(() => { let data = {} col = col || (window.event && window.event.errorCharacter) || 0 data.url = url data.line = line data.col = col data.error = error if (&& error.stack) { data.msg = error.stack.toString() } this.log(data) }, 0) return true } // 監聽promise window.addEventListener('unhandledrejection', err => { console.log('unhandledrejection') setTimeout(() => { this.log(JSON.stringify(err)) }, 0) }) } /** * 主動上報 * type: 'info','warning','error' */ log (data = null, type = 'error', options = {}) { // 添加麪包屑 Raven.captureBreadcrumb({ message: data, category: 'manual message' }) // 異常上報 if (data instanceof Error) { Raven.captureException(data, { level: type, logger: 'manual exception', tags: { options: options } }) } else { Raven.captureException('error', { level: type, logger: 'manual data', extra: { data: data, options: this.options, date: new Date() } }) } } } export default Report

6. 調用 Report.js 類

main.js中引入Report類,並綁定實例化後的sentry實例到Vue上以便全局調用。this

import Report from '@/assets/Report' let sentry = Report.getInstance(Vue, {}) Vue.prototype.$sentry = sentry // 設置全局變量

在其餘的vue組件中手動上報日誌。

this.$sentry.log('test')

7. sourceMap

sentry針對壓縮過的js文件提供了sourceMap分析,只須要上傳版本對應的sourceMap,就能夠在錯誤日誌中查看對應的源碼信息。詳細方法見官方文檔:https://docs.sentry.io/clients/javascript/sourcemaps/(https://docs.sentry.io/clients/javascript/sourcemaps/)

 

轉自:https://cloud.tencent.com/developer/article/1404307

相關文章
相關標籤/搜索