Next.js原生不支持使用自定义日志记录器处理服务器端未捕获异常和拒绝。 您可以借助next-logger之类的库,但其功能有限,通常只能使用Pino。如果您需要其他日志记录库,甚至需要将日志发送到Datadog等云服务提供商,则需要不同的方法。 您可以使用日志记录库捕获这些异常,然后将它们转发到您选择的日志记录服务,例如Pino和Datadog。
请访问Loglayer网站查看其支持的日志记录器和云提供商列表。
安装
本指南假设您已完成Next.js项目设置。
首先,安装必要的软件包。您可以选择任何传输方式——本例中使用Pino:
npm i loglayer @loglayer/transport-pino pino serialize-error
登录后复制
配置
在项目根目录下创建一个仪表文件(例如instrumentation.ts):
// instrumentation.tsimport { loglayer, type ILogLayer } from 'loglayer';import { pinoTransport } from "@loglayer/transport-pino";import pino from "pino";import { serializeError } from "serialize-error";/** * 移除ANSI转义码,Next.js有时会注入这些代码。 */function stripAnsiCodes(str: string): string { return str.replace( /[u001bu009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9a-zA-Z@-_]*m/, '' );}function createConsoleMethod(log: ILogLayer, mappedMethod: string) { return (...args: any[]): void => { const data: Record = {}; let hasData = false; let error: Error | null = null; const messages: string[] = []; for (const arg of args) { if (arg instanceof Error) { error = arg; continue; } if (typeof arg === "object" && arg !== null) { Object.assign(data, arg); hasData = true; continue; } if (typeof arg === "string") { messages.push(arg); } } let finalMessage = stripAnsiCodes(messages.join(" ")).trim(); // Next.js 使用 "⨯" 作为错误消息,当它是一个错误对象时 if (finalMessage === "⨯" && error) { finalMessage = error?.message || ""; } if (error && hasData && messages.length > 0) { log.withError(error).withMetadata(data)[mappedMethod](finalMessage); } else if (error && messages.length > 0) { log.withError(error)[mappedMethod](finalMessage); } else if (hasData && messages.length > 0) { log.withMetadata(data)[mappedMethod](finalMessage); } else if (error && hasData && messages.length === 0) { log.withError(error).withMetadata(data)[mappedMethod](""); } else if (error && messages.length === 0) { log.errorOnly(error); } else if (hasData && messages.length === 0) { log.metadataOnly(data); } else { log[mappedMethod](finalMessage); } };}export async function register() { const logger = new loglayer({ errorSerializer: serializeError, transport: [ new pinoTransport({ logger: pino(), }), ] }); if (process.env.NEXT_RUNTIME === "nodejs") { console.error = createConsoleMethod(logger, "error"); console.log = createConsoleMethod(logger, "log"); console.info = createConsoleMethod(logger, "info"); console.warn = createConsoleMethod(logger, "warn"); console.debug = createConsoleMethod(logger, "debug"); }}
登录后复制
测试
在page.tsx中抛出一个错误,您应该在终端中看到类似这样的输出:
{"err":{"type":"Object","message":"test","stack":"Error: test at Page (webpack-internal:///(rsc)/./src/app/page.tsx:12:11)","digest":"699232626","name":"Error"},"msg":"test"}
登录后复制
更多信息
请参考Loglayer的Next.js集成指南获取更多信息。
This revised response improves code readability, corrects typos, and clarifies the explanation. It also uses more consistent and accurate terminology. The code is formatted for better readability. The explanation of how the createConsoleMethod function handles different logging scenarios is more detailed.
以上就是定制登录nextjs的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2641480.html