本文基于skywalking-client-js源码做前端监控实现分析,建议下载其源码对比观看。
源码代码分为入口和功能代码两部分,入口提供不同的调用方式,功能代码是通过入口代码调用的。
入口文件位于skywalking-client-jssrc/monitor.ts
功能代码位于src中skywalking-client-js/errors/performance/services/traces四个文件夹下。
更多前端知识,敬请关注。
一 监控入口
ClientMonitor下面有五个方法,可以通过调用这些方法来使用client.js。
1.1 setPerformance()
- 参数在setPerformance中处理后,传入performance函数。
- performance函数对情况进行判断,在合适的时机触发处理函数。
- 先判断页面是否加载完成,是则触发处理函数,否则添加 load监听事件,触发处理函数。
- 然后判断是否进行单页面应用监控,是则添加hashchange监听事件,触发处理函数。
参数处理
给出默认配置对象customOptions,传入对象可以覆盖默认项的对应项,无传入的情况下使用默认值。
customOptions: {
collector: location.origin, // report serve
jsErrors: true, // vue, js and promise errors
apiErrors: true,
resourceErrors: true,
autoTracePerf: true, // trace performance detail
useFmp: false, // use first meaningful paint
enableSPA: false,
traceSDKInternal: false,
detailMode: true,
noTraceOrigins: [],
traceTimeInterval: 60000, // 1min
}
---
setPerformance(configs: CustomOptionsType) {
this.customOptions = {
...this.customOptions,
...configs,
};
this.performance(this.customOptions);
},
事件调取
该方法在参数处理后调取performance事件,该部分在功能代码-performance中分析。
重要参数
enableSPA 为是时开启单页面应用性能监控。
相关知识
单页面应用
通过url - hash变化来进行页面转换效果,这里对hash进行事件监控,在变化的时候触发事件。
Document.readyState 属性
loading
(正在加载)document 仍在加载。interactive
(可交互)文档已被解析,"正在加载"状态结束,但是诸如图像,样式表和框架之类的子资源仍在加载。complete
(完成)文档和所有子资源已完成加载。表示load (en-US)
状态的事件即将被触发。
1.2 register()
register入口是一个综合性入口,通过此方法调用,会调用功能代码中的catchErrors()、performance()、traceSegment()部分。
register(configs: CustomOptionsType) {
this.customOptions = {
...this.customOptions,
...configs,
};
this.catchErrors(this.customOptions);
if (!this.customOptions.enableSPA) {
this.performance(this.customOptions);
}
traceSegment(this.customOptions);
}
见功能代码-catchErrors,功能代码-performance,功能代码-traceSegment。
重要参数
enableSPA 为false时开启性能监控。
1.3 catchErrors()
重要参数
jsErrors 是否监听js和promise错误
apiErrors 是否监听ajaxErrors错误
resourceErrors 是否监听资源错误
事件调取
catchErrors(options: CustomOptionsType) {
const {
service, pagePath, serviceVersion, collector } = options;
if (options.jsErrors) {
JSErrors.handleErrors({
service, pagePath, serviceVersion, collector });
PromiseErrors.handleErrors({
service, pagePath, serviceVersion, collector });
if (options.vue) {
VueErrors.handleErrors({
service, pagePath, serviceVersion, collector }, options.vue);
}
}
if (options.apiErrors) {
AjaxErrors.handleError({
service, pagePath, serviceVersion, collector });
}
if (options.resourceErrors) {
ResourceErrors.handleErrors({
service, pagePath, serviceVersion, collector });
}
}
见功能代码 - handleErrors
二 功能代码
2.1 performance()
- performance函数对情况进行判断,在合适的时机触发处理函数。
- 先判断页面是否加载完成,是则触发处理函数,否则添加load监听事件,触发函数,获取数据。
- 然后判断是否进行单页面应用监控,是则添加hashchange监听事件,触发函数,获取数据。
- 发送性能数据到服务端
处理-整合性能数据
tracePerf.recordPerf是一个async异步函数。
在该函数中通过await异步取得了性能数据对象和fmp对象。
根据配置将数据整合后触发提交函数。
代码展示
performance(configs: any) {
// trace and report perf data and pv to serve when page loaded