1.0.13 • Published 2 years ago

mmp-client-js v1.0.13

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

mmp-client-js

参考自 Apache SkyWalkingskywalking-client-js项目。

Client-side JavaScript exception and tracing library.

  • Provide metrics and error collection to SkyWalking backend.
  • Lightweight
  • Make browser as a start of whole distributed tracing

Usage

Install

npm install mmp-client-js --save

Quick Start

mmp-client-js requires SkyWalking 8.2+

User could use register method to load and report data automatically.

import ClientMonitor from 'mmp-client-js';
// Report collected data to `http:// + window.location.host + /browser/perfData` in default
ClientMonitor.register({
  collector: 'http://127.0.0.1:8080',
  service: 'test-ui',
  pagePath: '/current/page/name',
  serviceVersion: 'v1.0.0',
});

Parameters

The register method supports the following parameters.

ParameterTypeDescriptionRequiredDefault Value
collectorStringIn default, the collected data would be reported to current domain(/browser/perfData. Then, typically, we recommend you use a Gateway/proxy to redirect the data to the OAP(resthost:restport). If you set this, the data could be reported to another domain, NOTE the Cross-Origin Resource Sharing (CORS) issuse and solution.false-
serviceStringproject id. NOTE, in tracing data requests, the service parameter is service + '<browser>'.true-
serviceVersionStringproject verisontrue-
pagePathStringproject pathtrue-
jsErrorsBooleanSupport js errors monitoringfalsetrue
apiErrorsBooleanSupport API errors monitoringfalsetrue
resourceErrorsBooleanSupport resource errors monitoringfalsetrue
useFmpBooleanCollect FMP (first meaningful paint) data of the first screenfalsefalse
enableSPABooleanMonitor the page hashchange event and report PV, which is suitable for single page application scenariosfalsefalse
autoTracePerfBooleanSupport sending of performance data automatically.falsetrue
vueVueSupport vue errors monitoringfalseundefined
traceSDKInternalBooleanSupport tracing SDK internal RPC.falsefalse
detailModeBooleanSupport tracing http method and url as tags in spans.falsetrue
traceTimeIntervalNumberSupport setting time interval to report segments.false60000
noTraceOrigins(string | RegExp)[]调用链上报需要忽略的服务主机/域名(Origin).false[]
noTraceUrlMatcherfunction(url:URL) :Boolean调用链上报需要忽略的URL匹配方法, 返回true表示忽略此URL.false-
traceTagParserfunction(requestBody,responseBody) :JSONObject调用链上报时标签解析方法,返回上报时追加的标签信息, 如function({requestBody,responseBody,...}){ ... return {cus:'',errCode:'',errMsg:'',...} }.false-
encryptfunction(data,collectorPath) :JSONObject信息上报时的加密/编码方法,返回包装后的新的请求体.false-
decryptfunction(data,collectorPath) :JSONObject信息上报后的响应体的解密/解码方法,调试时打印在控制台.false-
collectorPathModeString信息上报时不同类型接口路径的请求模式: url-路径追加在请求地址; header-路径追加在请求头; encode-在自定义编码方法中处理,附加在请求体中.falseURL
traceRequestInclude是否上报请求体falsefalse
traceResponseInclude是否上报响应体falsefalse
traceTagSupplier上报自定义标签的方法(一般从会话信息中提取而与请求无关,以xTrace开头的是跨调用链的标签)如: function(){return {xTraceUser:sessionStorage.userId,xTraceCus:sessionStorage.cusId,userName:sessionStorage.userName}}false-
traceRequestMaxLength上报请求体的最大长度false2000
traceResponseMaxLength上报响应体的最大长度false2000

Collect Metrics Manually

Use the setPerformance method to report metrics at the moment of page loaded or any other moment meaningful.

  1. Set the SDK configuration item autoTracePerf to false to turn off automatic reporting performance metrics and wait for manual triggering of escalation.
  2. Call ClientMonitor.setPerformance(object) method to report
  • Examples
import ClientMonitor from 'mmp-client-js';

ClientMonitor.setPerformance({
  collector: 'http://127.0.0.1:8080',
  service: 'browser-app',
  serviceVersion: '1.0.0',
  pagePath: location.href,
  useFmp: true
});

Special scene

SPA Page

In spa (single page application) single page application, the page will be refreshed only once. The traditional method only reports PV once after the page loading, but cannot count the PV of each sub-page, and can't make other types of logs aggregate by sub-page. The SDK provides two processing methods for spa pages:

  1. Enable spa automatic parsing This method is suitable for most single page application scenarios with URL hash as the route. In the initialized configuration item, set enableSPA to true, which will turn on the page's hashchange event listening (trigger re reporting PV), and use URL hash as the page field in other data reporting.
  2. Manual reporting This method can be used in all single page application scenarios. This method can be used if the first method is invalid. The SDK provides a set page method to manually update the page name when data is reported. When this method is called, the page PV will be re reported by default. For details, see setPerformance().
app.on('routeChange', function (next) {
  ClientMonitor.setPerformance({
    collector: 'http://127.0.0.1:8080',
    service: 'browser-app',
    serviceVersion: '1.0.0',
    pagePath: location.href,
    useFmp: true
  });
});

Tracing range of data requests in the browser

Support tracking these(XMLHttpRequest and Fetch API) two modes of data requests. At the same time, Support tracking libraries and tools that base on XMLHttpRequest and fetch, such as Axios, SuperAgent, OpenApi and so on.

Catching errors in frames, including React, Angular, Vue.

// Angular
import { ErrorHandler } from '@angular/core';
import ClientMonitor from 'mmp-client-js';
export class AppGlobalErrorhandler implements ErrorHandler {
  handleError(error) {
    ClientMonitor.reportFrameErrors({
      collector: 'http://127.0.0.1',
      service: 'angular-demo',
      pagePath: '/app',
      serviceVersion: 'v1.0.0',
    }, error);
  }
}
@NgModule({
  ...
  providers: [{provide: ErrorHandler, useClass: AppGlobalErrorhandler}]
})
class AppModule {}
// React
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    ClientMonitor.reportFrameErrors({
      collector: 'http://127.0.0.1',
      service: 'react-demo',
      pagePath: '/app',
      serviceVersion: 'v1.0.0',
    }, error);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}
<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
// Vue
Vue.config.errorHandler = (error) => {
  ClientMonitor.reportFrameErrors({
    collector: 'http://127.0.0.1',
    service: 'vue-demo',
    pagePath: '/app',
    serviceVersion: 'v1.0.0',
  }, error);
}

Demo project

Demo project provides instrumented web application with necessary environment, you could just simple use it to see the data SkyWalking collected and how SkyWalking visualizes on the UI. See more information, click here.

Contact Us

  • Submit an issue
  • Mail list: dev@skywalking.apache.org. Mail to dev-subscribe@skywalking.apache.org, follow the reply to subscribe the mail list.
  • Join #skywalking channel at Apache Slack. If the linke is not working, find the latest one at Apache INFRA WIKI.
  • QQ Group: 392443393, 901167865

Release Guide

All committers should follow Release Guide to publish the official release.

License

Apache 2.0