|
| 1 | +import type { LogContext } from "@sonory/utils" |
| 2 | + |
| 3 | +/** |
| 4 | + * Sentry SDK が提供する最小インターフェース。 |
| 5 | + * |
| 6 | + * @description |
| 7 | + * `@sentry/nextjs` 導入後に `window.Sentry` へバインドされる想定。 |
| 8 | + */ |
| 9 | +interface SentryClient { |
| 10 | + addBreadcrumb(breadcrumb: { |
| 11 | + category: string |
| 12 | + message: string |
| 13 | + level?: "debug" | "info" | "warning" | "error" |
| 14 | + data?: Record<string, unknown> |
| 15 | + }): void |
| 16 | + captureException( |
| 17 | + error: unknown, |
| 18 | + context?: { extra?: Record<string, unknown> }, |
| 19 | + ): void |
| 20 | + captureMessage( |
| 21 | + message: string, |
| 22 | + context?: { |
| 23 | + level?: "warning" | "error" |
| 24 | + extra?: Record<string, unknown> |
| 25 | + }, |
| 26 | + ): void |
| 27 | +} |
| 28 | + |
| 29 | +declare global { |
| 30 | + interface Window { |
| 31 | + Sentry?: SentryClient |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function getSentryClient(): SentryClient | undefined { |
| 36 | + if (typeof window === "undefined") { |
| 37 | + return undefined |
| 38 | + } |
| 39 | + |
| 40 | + return window.Sentry |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Sentry 向けのブレッドクラム・エラー転送シンク。 |
| 45 | + * |
| 46 | + * @description |
| 47 | + * DSN 未設定時は no-op。APM 導入後も呼び出し側の変更は不要。 |
| 48 | + */ |
| 49 | +export function createSentrySink(namespace: string): { |
| 50 | + info(message: string, context?: LogContext): void |
| 51 | + warn(message: string, context?: LogContext): void |
| 52 | + error(message: string, context?: LogContext): void |
| 53 | +} { |
| 54 | + const toBreadcrumb = ( |
| 55 | + level: "info" | "warning" | "error", |
| 56 | + message: string, |
| 57 | + context?: LogContext, |
| 58 | + ): void => { |
| 59 | + const sentry = getSentryClient() |
| 60 | + if (!sentry) { |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + sentry.addBreadcrumb({ |
| 65 | + category: namespace, |
| 66 | + message, |
| 67 | + level: level === "warning" ? "warning" : level, |
| 68 | + data: context, |
| 69 | + }) |
| 70 | + } |
| 71 | + |
| 72 | + return { |
| 73 | + info: (message, context) => { |
| 74 | + toBreadcrumb("info", message, context) |
| 75 | + }, |
| 76 | + warn: (message, context) => { |
| 77 | + toBreadcrumb("warning", message, context) |
| 78 | + getSentryClient()?.captureMessage(message, { |
| 79 | + level: "warning", |
| 80 | + extra: context, |
| 81 | + }) |
| 82 | + }, |
| 83 | + error: (message, context) => { |
| 84 | + toBreadcrumb("error", message, context) |
| 85 | + getSentryClient()?.captureMessage(message, { |
| 86 | + level: "error", |
| 87 | + extra: context, |
| 88 | + }) |
| 89 | + }, |
| 90 | + } |
| 91 | +} |
0 commit comments