Sentry 整合
Sentry 錯誤監控與效能追蹤的使用指南。
例外捕捉
在 try/catch 區塊中使用 Sentry.captureException(error):
try {
await riskyOperation();
} catch (error) {
Sentry.captureException(error);
throw error;
}
效能追蹤
為有意義的動作建立跨度,例如按鈕點擊、API 呼叫與函式呼叫。
使用者介面動作
function handleClick() {
Sentry.startSpan(
{ op: "ui.click", name: "提交表單" },
(span) => {
span.setAttribute("formId", formId);
submitForm();
}
);
}
API 呼叫
async function fetchData(id) {
return Sentry.startSpan(
{ op: "http.client", name: `GET /api/items/${id}` },
async () => {
const response = await fetch(`/api/items/${id}`);
return response.json();
}
);
}
設定 (Next.js)
Sentry 初始化檔案:
sentry.client.config.ts- 客戶端sentry.server.config.ts- 伺服器端sentry.edge.config.ts- Edge 執行環境
使用 import * as Sentry from "@sentry/nextjs" 匯入 - 無需在其他檔案中初始化。
基本設定
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
enableLogs: true,
});
啟用主控台日誌
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
integrations: [
Sentry.consoleLoggingIntegration({ levels: ["log", "warn", "error"] }),
],
});
結構化日誌
對包含變數的範本字串使用 logger.fmt:
const { logger } = Sentry;
logger.trace("開始連線", { database: "users" });
logger.debug(logger.fmt`快取未命中:${userId}`);
logger.info("已更新個人資料", { profileId: 345 });
logger.warn("已達速率限制", { endpoint: "/api/data" });
logger.error("付款失敗", { orderId: "order_123" });
logger.fatal("連線池耗盡", { activeConnections: 100 });