npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

icinfo-monitor-web

v1.0.5

Published

A SDK For Monitoring Web(React、Vue) Errors

Downloads

11

Readme

icinfo-monitor-web

前端埋点SDK

功能

  • [x] 监听请求错误
  • [x] console
  • [x] 路由跳转
  • [x] 代码报错
  • [x] click
  • [x] 资源加载错误
  • [x] 自定义上报错误
  • [x] 丰富的hooks与配置项支持可高定制化
  • [x] 支持IE8和安卓5以上
  • [x] 持续迭代与更新
  • [x] 支持原生Web
  • [x] 支持Web框架(Vue3、Vue2、React@Next)

安装

使用npm

$ npm i icinfo-monitor-web

Vue

Vue2.6NPM包形式

main.js

import Vue from 'vue'
import * as MITO from 'icinfo-monitor-web'

Vue.use(MITO.MitoVue)
MITO.init({
  dsn: 'http://test.com/error',
  apikey: '123-2223-123-123',
})

Vue3NPM包形式

main.ts

import App from './App.vue';
import {createApp} from 'vue';
import MITO from 'icinfo-monitor-web'
const app = createApp(App);
app.use(MITO.MitoVue)
MITO.init({
  dsn: 'http://test.com/error',
  apikey: '123-2223-123-123',
})
app.mount('#app');

React

NPM包形式

import * as MITO from 'icinfo-monitor-web';
MITO.init({
  // 服务器接口地址
  dsn: 'http://test.com/error',
  // 项目对应apikey
  apikey: '123-2223-123-123',
});

手动上报

MITO.log

有时我们需要在某个业务代码中上报业务信息或者是埋点信息,这时可以用到MITO.log手动上报,下面这个例子就是在获取支付状态的接口是否异常,如果异常就上报异常信息。

import * as MITO from 'icinfo-monitor-web'

$api.getPayStatus().then(res => {
  if (res.success) {
    // 支付正常
  } else {
    // 支付异常 上报异常信息
    MITO.log({
      // 错误信息
      message: res.errMsg,
      // 标签 可以理解为种类
      tag: '支付页面'
      // 错误等级:可选,默认最高等级
      // level: '',
      // 错误信息 Error对象
      // ex: ''
    })
  }
})

还可以统计每个功能的浏览次数(PV)、用户量(UV),比如下面代码中在活动页埋点,UV的统计需要依赖trackerId

import * as MITO from 'icinfo-monitor-web'

/**
 * react hook 活动页
 */
function ActivePage() {
  useEffect(() => {
    //可统计PV、UV
    MITO.log({
      // 可选
      // message: '统计',
      // 可选
      tag: '活动页统计'
    })
  }, [])
  return <div>这是活动页</div>
}

生成errorId规则 主要是根据传入的tag来生成的,所以相同的tag加上不同的message生成相同的errorId,比如:

MITO.log({
  // 可选
  message: '这是测试1',
  // 可选
  tag: '活动页统计'
})
MITO.log({
  // 可选
  message: '这是测试2',
  // 可选
  tag: '活动页统计'
})

上面两个errorId是相同的,但只要tag变一下两个errorId就不一样了

options

options.property

| Name | Type | Default | Description | | :----------------------------: | --------- | ---------- | ------------------------------------------------------------ | | dsn | string | "" | dsn服务地址,上报接口的地址,post方法,可选useImgUpload方式 | | trackDsn | string | "" | trackDsn服务地址,埋点上报接口的地址,为空时不上报,post方法 | | disabled | boolean | false | 默认是开启状态,为true时,会将sdk禁用 | | apikey | string | "" | 每个项目对应一个apikey,用于存放错误集合的唯一标识 | | debug | boolean | false | 默认不会在控制台打印用户行为和错误信息,为true时将会在控台打印,推荐本地调试时置为true | | useImgUpload | boolean | false | 为true时,则使用img上报的方式,会在dsn后面追加data=encodeURIComponent(reportData),在服务端接受时需要decodeURIComponent,默认为false。(小程序只能用wx.request上报的方式,也就是xhr,而且走img请求的话,url是有字符长度限制的,所以推荐走xhr) | | enableTraceId | boolean | false | 为true时,页面的所有请求都会生成一个uuid,放入请求头中,和配置项:traceIdFieldName搭配使用 | | throttleDelayTime | number | 0 | 默认会收集click到的标签,该参数可以设置按钮点击节流时间 | | traceIdFieldName | string | Trace-Id | 如果enableTraceId为true时,将会在所有请求头中添加keyTrace-IdvalueuuidtraceId,与includeHttpUrlTraceIdRegExp搭配使用 | | includeHttpUrlTraceIdRegExp | RegExp | null | 如果你开启了enableTraceId,还需要配置该属性,比如将改属性置为:/api/,那么所有包含api的的接口地址都将塞入traceId | | maxBreadcrumbs | number | 20 | 用户行为存放的最大容量,最大是100,当你配置超过100时,最终还是会设置成100,一方面是防止占更多的内存、一方面是保存超过100条用户行为没多大意义 | | filterXhrUrlRegExp | RegExp | null | 默认为空,所有ajax都会被监听,不为空时,filterXhrUrlRegExp.test(xhr.url)为true时过滤 | | silentXhr | boolean | false | 默认会监控xhr,为true时,将不再监控 | | silentFetch | boolean | false | 默认会监控fetch,为true时,将不再监控 | | silentConsole | boolean | false | 默认会监控console,为true时,将不再监控 | | silentDom | boolean | false | 默认会监听click事件,当用户点击的标签不是body时就会被放入breadcrumb,为true,将不在监听 | | silentHistory | boolean | false | 默认会监控popstate、pushState、replaceState,为true时,将不再监控 | | silentError | boolean | false | 默认会监控error,为true时,将不在监控 | | silentUnhandledrejection | boolean | false | 默认会监控unhandledrejection,为true时,将不在监控 | | silentHashchange | boolean | false | 默认会监控hashchange,为true时,将不在监控 | | silentVue | boolean | false | 默认会监控Vue的错误,为true时,将不在监控 | | silentWxOnError | boolean | false | 默认会监控微信小程序App的onError错误,为true时,将不在监控 | | silentWxOnUnhandledRejection | boolean | false | 默认会监控微信小程序App的onUnhandledRejection,为true时,将不在监控 | | silentWxOnPageNotFound | boolean | false | 默认会监控微信小程序App的onPageNotFound,为true时,将不在监控 | | silentWxOnShareAppMessage | boolean | false | 默认会监控微信小程序App的onShareAppMessage,为true时,将不在监控 | | silentMiniRoute | boolean | false | 默认会监控微信小程序App的路由跳转,为true时,将不在监控 | | maxDuplicateCount | number | 2 | 最多可重复上报同一个错误的次数 |

**示例:**用户行为栈最大长度为30

MITO.init({
  ...
  maxBreadcrumbs: 30
})

options.hook

export interface HooksTypes {
  /**
   * 钩子函数,配置发送到服务端的xhr
   * 可以对当前xhr实例做一些配置:xhr.setRequestHeader()、xhr.withCredentials
   * 会在xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8')、
   * xhr.withCredentials = true,后面调用该函数
   * ../param xhr XMLHttpRequest的实例
   */
  configReportXhr?(xhr: XMLHttpRequest): void
  /**
   * 钩子函数,在每次发送事件前会调用
   *
   * ../param event 有SDK生成的错误事件
   * ../returns 如果返回 null | undefined | boolean 时,将忽略本次上传
   */
  beforeDataReport?(event: TransportDataType): Promise<TransportDataType | null | CANCEL> | TransportDataType | CANCEL | null
  /**
   * 钩子函数,每次发送前都会调用,设置上报到服务端的地址
   *
   * @param {string} url 上报到服务端的地址
   * @returns {(string | null)} 返回string
   * @memberof HooksTypes
   */
  configReportUrl?(url: string): string
  /**
   * 钩子函数,在每次添加用户行为事件前都会调用
   *
   * ../param breadcrumb 由SDK生成的breacrumb事件栈
   * ../param hint 当次的生成的breadcrumb数据
   * ../returns 如果返回 null | undefined | boolean 时,将忽略本次的push
   */
  beforePushBreadcrumb?(breadcrumb: Breadcrumb, hint: BreadcrumbPushData): BreadcrumbPushData | CANCEL
  /**
   * 在状态小于400并且不等于0的时候回调用当前hook
   * ../param data 请求状态为200时返回的响应体
   * ../returns 如果返回 null | undefined | boolean 时,将忽略本次的上传
   */
  // afterSuccessHttp?<T>(data: T): string | CANCEL
  /**
   * 钩子函数,拦截用户页面的ajax请求,并在ajax请求发送前执行该hook,可以对用户发送的ajax请求做xhr.setRequestHeader
   * ../param config 当前请求的
   */
  beforeAppAjaxSend?(config: IRequestHeaderConfig, setRequestHeader: IBeforeAppAjaxSendConfig): void
  /**
   * 钩子函数,在beforeDataReport后面调用,在整合上报数据和本身SDK信息数据前调用,当前函数执行完后立即将数据错误信息上报至服务端
   * trackerId表示用户唯一键(可以理解成userId),需要trackerId的意义可以区分每个错误影响的用户数量
   */
  backTrackerId?(): string | number
}

configReportXhr

示例:上报服务端(你配置的dsn或trackDsn接口)时,可以自定义设置请求头,如下所示,设置了Content-Type

MITO.init({
  ...
  configReportXhr(xhr){
  	xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8')
	}
})

beforeDataReport

function(event: TransportDataType): Promise<TransportDataType | null | CANCEL> | TransportDataType | CANCEL | null
interface TransportDataType{
  authInfo: AuthInfo
  breadcrumb: BreadcrumbPushData[]
  data: ReportDataType
  record?: any[]
}
interface ReportDataType {
  type?: ERRORTYPES
  message?: string
  url: string
  name?: string
  stack?: any
  time?: number
  errorId?: number
  level: number
  // ajax
  elapsedTime?: number
  request?: {
    httpType?: string
    method: string
    url: string
    data: any
  }
  response?: {
    status: number
    statusText: string
    description: string
  }
  // vue
  componentName?: string
  propsData?: any
  // logerror
  customTag?: string
}

示例:如果错误事件发生在test.com/test地址下则不上报服务端

MITO.init({
  ...
  async beforeDataReport(event){
  	if (event.data.url === 'test.com/test') return false
    // 注意:判断是否调用dsn还是trackDsn的规则
    // (event.data.actionType === undefined || !event.data.isTrackData) 为true那么认为此次上报的类型是错误上报,否则是埋点上报
	}
})

beforePushBreadcrumb

function(breadcrumb: Breadcrumb, hint: BreadcrumbPushData)
interface BreadcrumbPushData {
  type: string
  data: any
}
export class Breadcrumb{
  private maxBreadcrumbs:number
  private stack:BreadcrumbPushData[]
  push()
  getStack()
}

示例:如果typeConsole的就过滤,不会push到当前用户行为栈中

MITO.init({
  ...
  beforePushBreadcrumb(breadcrumb, hint){
  	if (hint.type === 'Console') return false
	}
})

beforeAppAjaxSend

示例:拦截用户页面的ajax请求,并在ajax请求发送前执行该hook。在页面所有ajax请求时添加请求头,类似axios的request拦截器,

MITO.init({
  ...
  beforeAppAjaxSend({method, url}, setRequestHeader){
  	if (method === 'GET') {
  		setRequestHeader('Content-Type', 'text/plain;charset=UTF-8')
  	}
	}
})

backTrackerId

示例:trackerId表示用户唯一键(可以理解成userId),可以用uuid生成或用直接用userId,为了方便区分每个错误的用户数,会放入authInfo对象中

MITO.init({
  ...
  backTrackerId(){
  	// 比如userId在localStorage中
  	return localStorage.getItem('userId')
	}
})