在项目中集成Sentry实践

351 阅读2分钟

1、首先访问sentry.io,注册个账号,创建个项目

image.png

我这里用的react项目,所以我创建的是react,项目名称自己随意。

2、在项目中配置Sentry

在项目中安装依赖

npm install --save @sentry/react

在项目入口处改造,初始化sentry

import React from 'react';
import ReactDOM from 'react-dom/client';
import { useLocation, useNavigationType, matchRoutes, createRoutesFromChildren } from 'react-router-dom'
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/locale/zh_CN'

import * as Sentry from '@sentry/react'

import App from './App'
import ErrorPage from './pages/ErrorPage';


Sentry.init({
  dsn: "****", // 这里换成第一步中创建的项目的dsn
  integrations: [
    new Sentry.BrowserTracing({
      // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
      // tracePropagationTargets: ["localhost", /^https:\/\/yourserver\.io\/api/],
      // 这里我的react-router版本> 6
      routingInstrumentation: Sentry.reactRouterV6Instrumentation(
        React.useEffect,
        useLocation,
        useNavigationType,
        createRoutesFromChildren,
        matchRoutes
      ),
    }),
    new Sentry.Replay(),
  ],
  // Performance Monitoring
  tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!

  // Session Replay
  replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
  replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
})

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <ConfigProvider locale={zh_CN}>
    <React.StrictMode>
      <Sentry.ErrorBoundary fallback={<ErrorPage />}>
        <App />
      </Sentry.ErrorBoundary>
    </React.StrictMode>
  </ConfigProvider>
);

改造路由

由于我用的是hash路由,

    import { lazy, Suspense } from 'react'
import { useRoutes, RouteObject } from 'react-router-dom'

import { HomeOutlined } from '@ant-design/icons'
import * as Sentry from '@sentry/react'

import { MyMenuItem } from '../types/menu'

// cesium 入门
const Induction = lazy(() => import('../pages/Cesium/Induction'))
// cesium 进阶
const Advance = lazy(() => import('../pages/Cesium/Advance'))

function LazyLoad(element: React.ReactNode) {
  return <Suspense fallback={null}>{element}</Suspense>
}

// 菜单列表
export const menuItems: MyMenuItem[] = [
  {
    label: '三维地图入门',
    key: '/cesium/induction', // 正常情况 相当于route中path, 路由的 path 唯一,特殊情况: 子路由配置时 key 得是全路径
    path: '/cesium/induction',
    icon: <HomeOutlined />,
    children: null,
    element: LazyLoad(<Induction />),
  },
  {
    key: '/cesium/advance',
    path: '/cesium/advance',
    label: '三维地图进阶',
    icon: <HomeOutlined />,
    element: LazyLoad(<Advance />),
  },
]

function generateRoute(menuList: MyMenuItem[], parentPath?: string): RouteObject[] {
  let items = []
  for (const menu of menuList) {
    if (menu.key) {
      // const currentPath = `${
      //   parentPath?.endsWith('/') ? parentPath.slice(0, -1) : parentPath
      // }${(menu.key as string)?.startsWith('/') ? menu.key : '/' + menu.key}`
      items.push({
        path: menu.path,
        // path: currentPath,
        element: menu.element,
        children: Array.isArray(menu.children)
          ? generateRoute(menu.children)
          : null,
      })
    }
  }
  return items as RouteObject[]
}

export const routeList = generateRoute(menuItems, '')


const sentryUseRouter = Sentry.wrapUseRoutes(useRoutes)

const AppRoutes = () => {
  return sentryUseRouter(routeList)
}

export default AppRoutes

至此页面的改造也完成了

3、测试是否生效,在页面中故意添加个报错

image.png 在sentry控制台中的确捕获到报错了

image.png

4、上传sourcemap

npx @sentry/wizard\@latest -i sourcemaps