Sentry 統合
Next.js アプリケーションにおけるエラーモニタリングとパフォーマンストレーシングのための Sentry 利用ガイドライン。
例外キャッチ
try/catch ブロック内で Sentry.captureException(error) を使用します:
try {
await riskyOperation();
} catch (error) {
Sentry.captureException(error);
throw error;
}
パフォーマンストレーシング
ボタンクリック、API コール、関数呼び出しなどの意味のあるアクションに対してスパンを作成します。
UI アクション
function handleClick() {
Sentry.startSpan(
{ op: "ui.click", name: "Submit Form" },
(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("Starting connection", { database: "users" });
logger.debug(logger.fmt`Cache miss for: ${userId}`);
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached", { endpoint: "/api/data" });
logger.error("Payment failed", { orderId: "order_123" });
logger.fatal("Connection pool exhausted", { activeConnections: 100 });