Skip to main content

2 posts tagged with "sentry"

View All Tags

· 4 min read

Thêm @sentry/node vào package.json:

npm install --save @sentry/node

Sentry nên được khởi tạo càng sớm trong ứng dụng của bạn càng tốt:

import express from "express";
import * as Sentry from "@sentry/node";

// or using CommonJS
// const express = require('express');
// const Sentry = require('@sentry/node');

const app = express();

Sentry.init({ dsn: "https://examplePublicKey@o0.ingest.sentry.io/0" });

// The request handler must be the first middleware on the app
app.use(Sentry.Handlers.requestHandler());

// All controllers should live here
app.get("/", function rootHandler(req, res) {
res.end("Hello world!");
});

// The error handler must be before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());

// Optional fallthrough error handler
app.use(function onError(err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + "\n");
});

app.listen(3000);

Cách để kiểm thử sentry với một api và trả về lỗi :

app.get("/debug-sentry", function mainHandler(req, res) {
throw new Error("My first Sentry error!");
});

requestHandler Tùy biến một số tùy chọn cho phép bạn quyết định dữ liệu nào sẽ được đưa vào sự kiện được gửi tới Sentry.

Các tùy chọn có thể là:

// keys to be extracted from req
request?: boolean | string[]; // default: true = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']

// server name
serverName?: boolean; // default: true

// generate transaction name
// path == request.path (eg. "/foo")
// methodPath == request.method + request.path (eg. "GET|/foo")
// handler == function name (eg. "fooHandler")
transaction?: boolean | 'path' | 'methodPath' | 'handler'; // default: true = 'methodPath'

// keys to be extracted from req.user
user?: boolean | string[]; // default: true = ['id', 'username', 'email']

// client ip address
ip?: boolean; // default: false

// node version
version?: boolean; // default: true

// timeout for fatal route errors to be delivered
flushTimeout?: number; // default: undefined

Ví dụ: nếu bạn muốn bỏ qua tên máy chủ và chỉ thêm người dùng, bạn sẽ sử dụng requestHandler như sau:

app.use(
Sentry.Handlers.requestHandler({
serverName: false,
user: ["email"],
})
);

Mặc định thì errorHandler sẽ chỉ nắm bắt các lỗi với mã trạng thái là 500 hoặc cao hơn. Nếu bạn muốn thay đổi nó, hãy cung cấp cho nó shouldHandleError , chấp nhận error làm đối số của nó và quyết định xem có nên gửi lỗi hay không bằng cách trả về một giá trị boolean thích hợp.

app.use(
Sentry.Handlers.errorHandler({
shouldHandleError(error) {
// Capture all 404 and 500 errors
if (error.status === 404 || error.status === 500) {
return true;
}
return false;
},
})
);

Nếu bạn sử dụng TypeScript, bạn cần truyền trình xử lý của chúng tôi để thể hiện các loại cụ thể. Chúng hoàn toàn tương thích, vì vậy điều duy nhất bạn cần thay đổi là:

// from
const express = require('express');
// to
import * as express from 'express';


// from
app.use(Sentry.Handlers.requestHandler());
// to
app.use(Sentry.Handlers.requestHandler() as express.RequestHandler);


// from
app.use(Sentry.Handlers.errorHandler());
// to
app.use(Sentry.Handlers.errorHandler() as express.ErrorRequestHandler);

Monitor Performance

Có thể thêm theo dõi quá trình ghi nhật ký các sự kiện diễn ra trong một yêu cầu, thường là trên nhiều dịch vụ cho tất cả các khuôn khổ phổ biến. Tuy nhiên, chúng tôi chỉ cung cấp các trình xử lý mặc định cho Express.

const Sentry = require("@sentry/node");
const express = require("express");
const app = express();

Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
// enable Express.js middleware tracing
new Sentry.Integrations.Express({
// to trace all requests to the default router
app,
// alternatively, you can specify the routes you want to trace:
// router: someRouter,
}),
],

// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

// RequestHandler creates a separate execution context using domains, so that every
// transaction/span/breadcrumb is attached to its own Hub instance
app.use(Sentry.Handlers.requestHandler());
// TracingHandler creates a trace for every incoming request
app.use(Sentry.Handlers.tracingHandler());

// the rest of your app

app.use(Sentry.Handlers.errorHandler());
app.listen(3000);

Các bước được cung cấp cho các hoạt động sau trong một sentry:

  • Yêu cầu HTTP được thực hiện với request
  • get cuộc gọi sử dụng httphttps
  • Middleware (Express.js only)

Troubleshooting

Khi chụp lỗi cục bộ, hãy đảm bảo rằng bộ lọc dữ liệu của dự án để lọc các sự kiện máy chủ cục bộ đã được tắt:

express data filters

Điều này đảm bảo rằng các lỗi do trình duyệt của bạn tạo ra (chẳng hạn như lỗi do các phương thức HTTP tạo ra) được ghi lại đúng cách.

· 2 min read

I.Cài đặt

Sentry thu thập dữ liệu bằng cách sử dụng SDK trong thời gian chạy ứng dụng của bạn.

# Using npm
npm install --save @sentry/react

# Using yarn
yarn add @sentry/react

II.Cấu hình

Cấu hình càng sớm càng tốt trong ứng dụng của bạn :

import { createRoot } from "react-dom/client";
import React from "react";
import * as Sentry from "@sentry/react";
import App from "./App";

Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [new Sentry.BrowserTracing()],

// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

const container = document.getElementById(“app”);
const root = createRoot(container);
root.render(<App />);

Khi điều này được thực hiện, tất cả các ngoại lệ chưa được xử lý sẽ được Sentry tự động ghi lại.

III.Thêm lỗi

Nếu đang sử dụng React 16 trở lên, bạn có thể sử dụng thành phần error boundary để tự động gửi lỗi Javascript từ bên trong cây thành phần tới Sentry và đặt giao diện người dùng dự phòng.

IV.Cài đặt React Router

Tích hợp React Router được thiết kế để hoạt động với tính năng theo dõi của chúng tôi. Quá trình ghi nhật ký các sự kiện diễn ra trong một yêu cầu, thường xuyên trên nhiều gói dịch vụ.

V.Xác thực

Đoạn mã này bao gồm một lỗi cố ý, vì vậy bạn có thể kiểm tra xem mọi thứ có hoạt động ngay khi bạn thiết lập không:

return <button onClick={() => methodDoesNotExist()}>Break the world</button>;

Để xem và giải quyết lỗi đã ghi, hãy đăng nhập và mở dự án của bạn. Nhấp vào tiêu đề của lỗi sẽ mở ra một trang nơi bạn có thể xem thông tin chi tiết và đánh dấu nó là đã giải quyết.

VI. Ngăn chứa lỗi

Tùy thuộc vào cách bạn đã thiết lập dự án JavaScript của mình, dấu vết ngăn xếp trong các lỗi Sentry của bạn có thể không giống mã thực của bạn.