Sentry for vue - Raven.js

10,160 阅读1分钟

在vue官方文档看到这个推荐的错误追踪服务- sentry,去官网看了看觉得挺不错的,就准备用到项目里。
嗯,还有官方集成vue,那太棒了,结果官方文档在vue中的使用说明只有寥寥几行,仅仅说明了如何引入与集成,完全没说在组件中如何使用(可能是我英文水平太low,没看出来)。那么只得靠自己了,自己封装一下。
主要还是看文档,在JavaScript栏目下,如何使用已经说明的很清楚了,我要做的仅仅是封装一个插件,使其在组件内可以直接使用。不多bb,直接上代码。

const Log = function() {};

/**
 * 写普通日志
 * @param {String} title 
 * @param {String} context 
 * @param {String} level 
 * @param {Object} tags 
 */
Log.writeNormalLog = function(title='',context='',level='info',tags={}) {
    Raven.captureMessage(title,{level,tags,extra:{context}});
};

/**
 * 写异常日志
 * @param {String} title 
 * @param {String} context 
 * @param {String} level 
 * @param {Object} tags 
 */
Log.writeExLog = function(ex,context='',level='info',tags={}) {
    Raven.captureException(ex,{level,tags,extra:{context}});
};


Log.Level={
    INFO:'info',
    WARNING:'warning',
    ERROR:'error'
};

export default {
  /**
     * Raven.js 日志记录插件
     * Doc:https://docs.sentry.io/clients/javascript/usage/
     * @param {*} Vue 
     * @param {Object} options 
     */
  install(Vue, options = {}) {
    Raven.config("your dsn")
      .addPlugin(RavenVue, Vue)
      .install();

    Raven.setUserContext({
      user: options.user || ""
    });

    Raven.setTagsContext({ environment: options.env });

    Object.defineProperties(Vue.prototype, {
      $log: { value: Log, writable: true }
    });
  }
};

Log即为封装的日志记录方法,这里只是简单的使用了几个参数。
setUserContext 用来记录用户信息。
setTagsContext 设置全局tag标签,任何记录都会带上这个tag,这里记录了运行环境。

使用中发现一个问题,就是时区不正确,找了半天才发现在哪改



点击左下角的图标,选择账户(Account),在外观(Appearance)中修改时区。



更新一下关于sourcemap的,一般生产环境都会压缩js,异常常常是1行3000列这种情况,这时通过sourcemap可以解决这个问题,这里不细说sourcemap。 想要在sentry上通过sourcemap显示具体信息就需要上传相关脚本的sourcemap,官方文档上表明有2种方法,我使用的sentry-cli来上传的。

具体流程

  1. 安装sentry-cli $ npm install sentry-cli-binary -g
  2. 登录sentry,这里需要用到token $ sentry-cli login
    关于token则是在如图左下角,点击API


    创建一个token,记住要勾选 project:write 开启项目的写权限
  3. 创建一个release $ sentry-cli releases -o MY_ORG -p MY_PROJECT new NAME
  4. $ sentry-cli releases -o MY_ORG -p MY_PROJECT files NAME upload-sourcemaps --url-prefix URL_PREFIX DIR
    MY_ORG 为组织名称,可以使用简称,在组织设置里查看。
    MY_PROJECT 为项目名称
    NAME 为自定义的release名称
    URL_PREFIX 为url前缀,一般是js所在目录地址
    DIR 为需要上传文件所在目录

这是文档中的例子:$ sentry-cli releases -o MY_ORG -p MY_PROJECT files 2da95dfb052f477380608d59d32b4ab9 upload-sourcemaps --url-prefix https://mydomain.invalid/static path/to/assets 上传完后的sourcemap地址为 mydomain.invalid/static/xxxx…

上传完成后只要地址正确就OK了

官方提示

  • Make sure that the URL prefix is correct for your files. This is easy to get wrong.
  • Make sure you upload the matching sourcemaps for your minimized files.
  • Make sure that your minified files you have on your servers actually have references to your files.

附:
sourcemap官方使用说明
Sentry Documentation