为网站接入前端异常监控系统 Sentry

1,869 阅读5分钟

背景

众所周知,现在前端异常监控在实际生产环境中越来越重要了。通过给网站接入前端异常监控系统,我们能获得以下几个好处:

  • 收集页面的错误信息
  • 辅助定位代码错误位置
  • 在用户报障前发现问题

这对于提升线上系统质量,降低线上故障数量,都具有非常重要的意义。相比于等待用户反馈故障,通过接入异常监控系统,能化被动为主动,缩短线上故障处理的流程和时间。

前端异常监控方案

  • badjs
  • fundebug
  • Sentry

目前比较流行的异常监控方案有以上几种,但从易用性、免费与否、以及项目是否开源等方面考虑,个人觉得 Sentry 是个非常不错的选择,服务端部署也非常简单,当然服务端也可以直接使用 Sentry 提供的,网站客户端引入 sentry sdk 并插入初始化 Sentry 的代码就可以实现对页面脚本异常的监控了。

Sentry 部署

安装 Docker
sudo yum remove docker  docker-common docker-selinux docker-engine
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum list docker-ce --showduplicates | sort -r
sudo yum install docker-ce
sudo systemctl start docker
sudo systemctl enable docker

Docker 安装 Sentry
  1. 拉取 Sentry 仓库
git clone https://github.com/getsentry/onpremise.git
  1. 创建 Sentry 服务
cd onpremise

新建docker本地数据库

docker volume create --name=sentry-data && 
docker volume create --name=sentry-postgres &&
docker volume create --name=sentry-redis &&
docker volume create --name=sentry-zookeeper &&
docker volume create --name=sentry-kafka &&
docker volume create --name=sentry-clickhouse &&
docker volume create --name=sentry-symbolicator

创建env配置文件

cp -n .env.example .env
COMPOSE_PROJECT_NAME=sentry_onpremise
SENTRY_EVENT_RETENTION_DAYS=90
# You can either use a port number or an IP:PORT combo for SENTRY_BIND
# See https://docs.docker.com/compose/compose-file/#ports for more
SENTRY_BIND=9000
SENTRY_IMAGE=getsentry/sentry:nightly
SNUBA_IMAGE=getsentry/snuba:nightly
RELAY_IMAGE=getsentry/relay:nightly
SYMBOLICATOR_IMAGE=getsentry/symbolicator:nightly
WAL2JSON_VERSION=latest

构建服务

docker-compose build

如果报错“-bash: docker-compose: command not found”,则需要先安装 docker-compose:

yum -y install epel-release
yum -y install python-pip
pip install docker-compose

生成秘钥

docker-compose run --rm web config generate-secret-key
...
Digest: sha256:de277fb0489fa674e28ce44a790840ece63dbacd696c990b95abdf0135ae5283
Status: Downloaded newer image for getsentry/sentry:nightly
4ghk9%xzwzg#e9yv5(w@rabcq626y&n*fygk=tzah%d!*la!1l

最后一行就是生成的秘钥,将生成的秘钥添加到.env 的 SENTRY_SECRET_KEY

COMPOSE_PROJECT_NAME=sentry_onpremise
SENTRY_EVENT_RETENTION_DAYS=90
SENTRY_SECRET_KEY="4ghk9%xzwzg#e9yv5(w@rabcq626y&n*fygk=tzah%d!*la!1l"
# You can either use a port number or an IP:PORT combo for SENTRY_BIND
# See https://docs.docker.com/compose/compose-file/#ports for more
SENTRY_BIND=9000
SENTRY_IMAGE=getsentry/sentry:nightly
SNUBA_IMAGE=getsentry/snuba:nightly
RELAY_IMAGE=getsentry/relay:nightly
SYMBOLICATOR_IMAGE=getsentry/symbolicator:nightly
WAL2JSON_VERSION=latest

创建数据库,创建超级管理员,作为登入sentry的账号,创建过程按提示一步步来

./install.sh

安装完成后,使用以下命令启动所有服务:

docker-compose up -d

然后在浏览器打开:http://服务器ip:9000 就能看到 Sentry 的服务端登录界面了。

image.png

网站端接入 Sentry
<script src="${staticDomain}/statics/lib/sentry/bundle.tracing.min.js?v=1.0" crossorigin="anonymous"></script>
<script>
    Sentry.init({
        dsn: "http://054e5400ae8d407eb8927804f0011e70@192.168.4.60:9000/2",
        // this assumes your build process sets "npm_package_version" in the env
        // release: "my-project-name@" + process.env.npm_package_version,
        integrations: [new Sentry.Integrations.BrowserTracing()],

        // We recommend adjusting this value in production, or using tracesSampler
        // for finer control
        // tracesSampleRate: 1.0,
        release: "0.0.1",
    });
</script>

页面可以写一行测试异常代码,验证 Sentry 能否接收到错误,正常接收的异常上报是这样的 image

到这里虽然能监控到脚本异常错误,但是我们通常发布到生产环境的代码是经过压缩混淆的,如果我们还想要监控到具体是哪一行代码引起的脚本错误,那就还需要上传 sourcemaps 到 Sentry 服务器。

Sentry 上传 sourcemaps

Sentry 上传 sourcemaps 的方式有两种,一种是通过 webpack 插件上传,另一种是通过 sentry cli 上传。两种方式配置都不复杂 ,取决于你的项目使用的是什么构建工具,如果你的项目是使用webpack打包的自然是使用webpack插件上传会方便一点,如果是使用 gulp 等其他构建工具的,那就是使用 sentry cli 会方便一点。

  • webpack 插件上传 sourcemaps

安装 @sentry/webpack-plugin 和 clean-webpack-plugin

npm install @sentry/webpack-plugin clean-webpack-plugin -D

获取 authToken

API keys -> Auth Tokens -> Create New Token

在 webpack.config.js 中添加以下代码:

const SentryWebpackPlugin = require("@sentry/webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
  plugins: [
      new SentryWebpackPlugin({
          url: "http://192.168.4.60:9000/",
          authToken: "9d332444a2804384b38cce5d11664294c9eea7a41aea4e71ae2daaa4c9b5bd7f",
          org: "sentry",
          project: "pc-web",
          // 本地 sourcemap 所在目录
          include: ".",
          // js 访问路径,如果使用了cdn,则需要写上完整域名和路径
          urlPrefix: "http://src.test.com/statics/js/dist"
      }),
  ],
};
  • sentry cli 上传 sourcemaps

安装 sentry cli

npm install @sentry/cli@16.7.1 -D

如果安装失败,报如下错误:

Downloading from https://downloads.sentry-cdn.com/sentry-cli/1.67.1/sentry-cli-Windows-x86_64.exe Error: Unable to download sentry-cli binary from https://downloads.sentry-cdn.com/sentry-cli/1.67.1/sentry-cli-Windows-x86_64.exe. Error code: ECONNRESET

可以修改拉取地址为淘宝镜像地址:

npm config set sentrycli_cdnurl https://npm.taobao.org/mirrors/sentry-cli/

配置代码打包时生成 sourcemaps, 我的项目是基于 gulp 打包的,所以使用 gulp-sourcemaps 插件生成 sourcemaps:

var sourcemaps = require('gulp-sourcemaps');
// 省略其他代码
pump([
    gulp.src(path.join(build_path, paths.optimize + '/' + dir + '/' + versiondir + '/*.js')),
    sourcemaps.init(),
    babel(),
    concat(versiondir + '.js'),
    uglify(),
    sourcemaps.write('./'),
    gulp.dest(distPath)
])
// 省略其他代码

执行构建任务后,就会在 dist 目录同时生成 sourcemap 文件。

上传 Sourcemaps 到 Sentry,先在项目根目录新建一个.sentryclirc文件,代码如下:

[defaults]
url = http://192.168.4.60:9000/
org = sentry
project = pc-web
 
[auth]
token = 9d332444a2804384b38cce5d11664294c9eea7a41aea4e71ae2daaa4c9b5bd7f

然后在生产打包的脚本增加 上传 sourcemaps 的命令:

gulp js --env pro // 生产打包
sentry-cli releases -o sentry -p pc-web new 0.0.1
sentry-cli releases files 0.0.1 upload-sourcemaps statics/js/dist --url-prefix http://src.test.com/statics/js/dist

这里有个要注意的地方,就是 sourcemaps 的版本号(前文示例的 0.0.1)一定要与网站初始化 sentry 时的 release 参数一致,否则 Sentry 监控到报错脚本也无法定位到具体的源码的。

下面看看监控脚本报错的效果: image

结语

到这里,就完成了网站前端异常监控系统 Sentry 的接入,本文也只是演示了 Sentry 最基本的功能,还有其他比较高级用法计划在后续逐步引入,包括网站 404 页面监控,接口性能监控等等。