instrumentation.js
instrumentation.js|ts 檔案用於將可觀測性工具整合到您的應用程式中,允許您跟蹤效能和行為,並除錯生產中的問題。
要使用它,請將檔案放置在應用程式的根目錄或(如果使用)src 資料夾中。
匯出
register(可選)
該檔案匯出一個 register 函式,該函式在新 Next.js 伺服器例項啟動時只調用一次。register 可以是一個非同步函式。
instrumentation.ts
import { registerOTel } from '@vercel/otel'
export function register() {
registerOTel('next-app')
}onRequestError(可選)
您可以選擇匯出一個 onRequestError 函式,用於將伺服器錯誤跟蹤到任何自定義的可觀測性提供商。
- 如果您在
onRequestError中執行任何非同步任務,請確保它們都已等待。當 Next.js 伺服器捕獲到錯誤時,onRequestError將被觸發。 error例項可能不是原始丟擲的錯誤例項,因為它可能會在伺服器元件渲染期間被 React 處理。如果發生這種情況,您可以使用錯誤上的digest屬性來識別實際的錯誤型別。
instrumentation.ts
import { type Instrumentation } from 'next'
export const onRequestError: Instrumentation.onRequestError = async (
err,
request,
context
) => {
await fetch('https://.../report-error', {
method: 'POST',
body: JSON.stringify({
message: err.message,
request,
context,
}),
headers: {
'Content-Type': 'application/json',
},
})
}引數
該函式接受三個引數:error、request 和 context。
型別
export function onRequestError(
error: { digest: string } & Error,
request: {
path: string // resource path, e.g. /blog?name=foo
method: string // request method. e.g. GET, POST, etc
headers: { [key: string]: string | string[] }
},
context: {
routerKind: 'Pages Router' | 'App Router' // the router type
routePath: string // the route file path, e.g. /app/blog/[dynamic]
routeType: 'render' | 'route' | 'action' | 'proxy' // the context in which the error occurred
renderSource:
| 'react-server-components'
| 'react-server-components-payload'
| 'server-rendering'
revalidateReason: 'on-demand' | 'stale' | undefined // undefined is a normal request without revalidation
renderType: 'dynamic' | 'dynamic-resume' // 'dynamic-resume' for PPR
}
): void | Promise<void>error:捕獲到的錯誤本身(型別始終為Error),以及一個digest屬性,該屬性是錯誤的唯一 ID。request:與錯誤關聯的只讀請求資訊。context:錯誤發生的上下文。這可以是路由器的型別(應用或頁面路由器),和/或(伺服器元件('render')、路由處理程式('route')、伺服器操作('action')或代理('proxy'))。
指定執行時
instrumentation.js 檔案在 Node.js 和 Edge 執行時中都可以工作,但是,您可以使用 process.env.NEXT_RUNTIME 來定位特定的執行時。
instrumentation.js
export function register() {
if (process.env.NEXT_RUNTIME === 'edge') {
return require('./register.edge')
} else {
return require('./register.node')
}
}
export function onRequestError() {
if (process.env.NEXT_RUNTIME === 'edge') {
return require('./on-request-error.edge')
} else {
return require('./on-request-error.node')
}
}版本歷史
| 版本 | 更改 |
|---|---|
v15.0.0 | 引入了 onRequestError,instrumentation 穩定 |
v14.0.4 | Turbopack 支援 instrumentation |
v13.2.0 | instrumentation 作為實驗性功能引入 |
這有幫助嗎?