Sentry是一个开源应用程序监控平台,可帮助您实时识别问题。支持 web 前后端、移动应用以及游戏,支持 Python、OC、Java、Go、Node、Django、RoR 等主流编程语言和框架 ,还提供了 GitHub、Slack、Trello 等常见开发工具的集成。
本文主要讨论的是Sentry在Docker环境下的搭建、Sentry SDK默认集成的功能以及在React应用程序中的使用。
1.Sentry的搭建
1.1、Sentry搭建有两种方式
通过Python安装
通过Docker容器安装
这里我们通过Docker安装(Docker的安装教程较简单,在这里就不重复造轮子)
1.2、安装环境要求
MIN_DOCKER_VERSION='1.10.0'
docker -vMIN_COMPOSE_VERSION='1.17.0'
docker-compose -vMIN_RAM=3072 # MB //你的内存至少3G1.3、搭建步骤
今年7月份的时候Sentry官方更新了一版,将安装的流程写成了一个shell脚本(./install.sh),所以如果要使用所有默认设置,只需拉取onpremise(https://github.com/getsentry/onpremise)并运行./install.sh即可。
如果需要对包含的docker-compose.yml文件进行修改以满足您的需求或环境(例如添加GitHub凭据)。请在运行安装脚本之前执行这些操作。
自定义配置的推荐方法是按以下顺序使用以下文件:
config.yml
sentry.conf.py
.env w /环境变量
如无意外, 一切正常, 端口默认是9000, 本地的话可以直接打开localhost:9000访问;
2.SDK默认集成的功能
Dedupe 自动过滤一些重复的事件
FunctionToString 使SDK能够上报详细的错误函数信息
InboundFilters 便于开发者自行过滤或筛选所需的上报事件
Debug 该集成帮助方便的查看事件发送到Sentry服务器之前的实时信息,可选设置项:
{ debugger: boolean; // 在事件发送前触发开发者工具debugger模式(如果打开了开发者工具) stringify: boolean; // 在事件发送前将事件序列化后通过console.log输出 }root: string; //root指定的路径将被拼接到当前错误帧的basename之前(文件的完整路径被分解为[root, dir, basename, ext]) iteratee: (frame) => frame); //该函数接收frame作为参数处理后再返回 }RewriteFrames 该集成允许你对错误堆栈跟踪的每个帧进行处理
这里重点讲下浏览器端特有的集成功能:
Breadcrumbs 面包屑 包含以下选项,默认全部集成
beacon: boolean; // 记录使用Beacon API完成的HTTP请求 console: boolean; // 捕捉console信息 dom: boolean; // 捕捉所有点击以及键盘事件 fetch: boolean; // 记录使用Fetch API完成的HTTP请求 history: boolean; // 记录history的变化 sentry: boolean; // 记录主动上报的事件 xhr: boolean; // 记录使用XMLHttpRequest API完成的HTTP请求 }GlobalHandlers 全局设置是否需要对所有未捕获错误或未处理的失败响应进行处理
{ onerror: boolean; onunhandledrejection: boolean; }LinkedErrors 递归查询错误堆栈的最深层次数和查询字段
{ key: string; limit: number; }ReportingObserver,以下三类默认都包含
{ types: <'crash'|'deprecation'|'intervention'>[]; }TryCatch 这个默认集成功能使用
try/catch语句来包裹原生的定时及事件相关API来捕获这些可能的异步错误UserAgent 这个功能为上报的信息附加了浏览器的user-agent,帮助我们更好的了解和区分该用户的使用环境
一般不建议修改或删除这些集成,除非是有特别的需求或者冲突,修改方式为
import * as Sentry from '@sentry/browser';
//删除某集成
Sentry.init({
dsn: 'https://<key>@sentry.io/<project>',
integrations: integrations => {
//删除Breadcrumbs集成
return integrations.filter(integration => integration.name !== 'Breadcrumbs');
}
});
//修改某集成
Sentry.init({
dsn: 'https://<key>@sentry.io/<project>',
integrations: integrations => {
//关闭Breadcrumbs集成自动收集console的功能
return [...integrations, new Sentry.Integrations.Breadcrumbs({ console: false })];
}
});3.在React中的应用
3.1、将Sentry集成到你的React应用
要将Sentry与React应用程序一起使用,您需要使用@sentry/browser(Sentry的浏览器JavaScript SDK)
# Using yarn
$ yarn add @sentry/browser
# Using npm
$ npm install @sentry/browser
在Sentry中完成项目设置后,Sentry将为您提供一个我们称之为DSN(Data Source Name)或数据源名称的值。
import * as Sentry from '@sentry/browser';
//DSN由几部分组成,包括协议,公钥,服务器地址和项目标识符。
Sentry.init({dsn: "https://55b49309d120441bb162084e21e8ddbd@sentry.io/1521000"});@sentry/browser将报告从您的应用程序触发的任何未捕获的异常。你也可以手动发送错误信息到sentry。
let errorVariable
try{
console.log(errorVariable.slice(0,3))
}catch(e){
//捕获异常的错误
Sentry.captureException(e,{
tags: {
locale: 'en-us'
}
})
}运行代码,毫无例外,sentry接送到了一个语法错误
细心的小伙伴可能发现了,项目经过打包之后代码变得极其难阅读,这样的报错信息对于我们来说是不友好的。还好的是,Sentry supports un-minifying JavaScript via source maps
3.2、sourceMap
第一步,先安装 @sentry/cli 工具
$ npm install -g @sentry/cli第二步,在项目根目录下创建.sentryclirc文件
查询组织的slug可以访问https://sentry.io/api/0/organizations/
查询项目的slug可以访问https://sentry.io/api/0/organizations/{organization_slug}/projects/
//.sentryclirc
[defaults]
url=https://sentry.io/
org={organization_slug}
project={project_slug}如果是首次配置,我们在需要webpack打包的文件目录下运行sentry-cli login命令进行授权,命令行将会指引我们打开浏览器新建一个authentication token,然后sentry-cli 自动将我们填入的token写入了我们新建的.sentryclirc配置文件中
第三步,安装@sentry/webpack-plugin
$ npm install -S @sentry/webpack-plugin第四步,webpack配置中引入Sentry Webpack Plugin插件,就可以实现在webpack打包过程中自动识别源文件和SourceMap文件并自动上传。
//config-overrides.js
const {
override,
addWebpackPlugin
} = require("customize-cra")
const SentryCliPlugin = require('@sentry/webpack-plugin');
module.exports = override(
addWebpackPlugin(new SentryCliPlugin({
release: 'project20190804',
include: 'build',
urlPrefix: '~/',
ignore: ['node_modules'],
}))
)第五步,判断文件是否上传成功,可以在sentry.io上查看
可以看到文件已经上传成功,其中~代表页面的协议加域名,所以可以检查下具体文件是不是能够访问的,避免SourceMap解析失败。
经过了上面的一系列操作,让我们重新打包运行程序;果然没让baba失望!
顺带提一下,为了避免本地调试的时候也将错误上传上去,我们可以通过Allowed Domains属性进行配置
3.3、sentry的基本配置
Sentry.init({
// Client's DSN.
dsn: 'https://363a337c11a64611be4845ad6e24f3ac@sentry.io/297378',
// An array of strings or regexps that'll be used to ignore specific errors based on their type/message
ignoreErrors: [/PickleRick_\d\d/, 'RangeError'],
// An array of strings or regexps that'll be used to ignore specific errors based on their origin url
blacklistUrls: ['external-lib.js'],
// An array of strings or regexps that'll be used to allow specific errors based on their origin url
whitelistUrls: ['http://localhost:5000', 'https://browser.sentry-cdn'],
// Debug mode with valuable initialization/lifecycle informations.
debug: true,
// Whether SDK should be enabled or not.
enabled: true,
// Custom integrations callback
integrations(integrations) {
return [new HappyIntegration(), ...integrations];
},
// A release identifier.
release: '1537345109360',
// An environment identifier.
environment: 'staging',
// Custom event transport that will be used to send things to Sentry
transport: HappyTransport,
// Method called for every captured event
async beforeSend(event, hint) {
// Because beforeSend and beforeBreadcrumb are async, user can fetch some data
// return a promise, or whatever he wants
// Our CustomError defined in errors.js has `someMethodAttachedToOurCustomError`
// which can mimick something like a network request to grab more detailed error info or something.
// hint is original exception that was triggered, so we check for our CustomError name
if (hint.originalException.name === 'CustomError') {
const serverData = await hint.originalException.someMethodAttachedToOurCustomError();
event.extra = {
...event.extra,
serverData,
};
}
console.log(event);
return event;
},
// Method called for every captured breadcrumb
beforeBreadcrumb(breadcrumb, hint) {
// We ignore our own logger and rest of the buttons just for presentation purposes
if (breadcrumb.message.startsWith('Sentry Logger')) return null;
if (breadcrumb.category !== 'ui.click' || hint.event.target.id !== 'breadcrumb-hint') return null;
// If we have a `ui.click` type of breadcrumb, eg. clicking on a button we defined in index.html
// We will extract a `data-label` attribute from it and use it as a part of the message
if (breadcrumb.category === 'ui.click') {
const label = hint.event.target.dataset.label;
if (label) {
breadcrumb.message = `User clicked on a button with label "${label}"`;
}
}
console.log(breadcrumb);
return breadcrumb;
},
});4.结语
本文主要围绕如何搭建和使用sentry,解决在线上环境中,因为应用跑在用户浏览器中,发生错误时我们如果要对其进行调试就会显得比较困难。由于本人水平和经验有限,如有纰漏或建议,欢迎留言。如果觉得不错,欢迎关注海致星图,谢谢您的阅读。