日志链接
loggerLink
是一个链接,它允许您为您的 tRPC 客户端实现一个日志记录器。它允许您更清楚地看到哪些操作是查询、变异或订阅,以及它们的请求和响应。默认情况下,该链接会将格式化的日志打印到浏览器的控制台。但是,您可以使用自己的实现来定制日志记录行为以及它打印到控制台的方式。
用法
您可以导入并将 loggerLink
添加到 links
数组中,如下所示
client/index.tsts
import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [/*** The function passed to enabled is an example in case you want to the link to* log to your console in development and only log errors in production*/loggerLink({enabled: (opts) =>(process.env.NODE_ENV === 'development' &&typeof window !== 'undefined') ||(opts.direction === 'down' && opts.result instanceof Error),}),httpBatchLink({url: 'http://localhost:3000',}),],});
client/index.tsts
import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [/*** The function passed to enabled is an example in case you want to the link to* log to your console in development and only log errors in production*/loggerLink({enabled: (opts) =>(process.env.NODE_ENV === 'development' &&typeof window !== 'undefined') ||(opts.direction === 'down' && opts.result instanceof Error),}),httpBatchLink({url: 'http://localhost:3000',}),],});
loggerLink
选项
loggerLink
函数接受一个具有 LoggerLinkOptions
形状的选项对象
ts
type LoggerLinkOptions<TRouter extends AnyRouter> = {logger?: LogFn<TRouter>;/*** It is a function that returns a condition that determines whether to enable the logger.* It is true by default.*/enabled?: EnabledFn<TRouter>;/*** Used in the built-in defaultLogger*/console?: ConsoleEsque;/*** Color mode used in the default logger.* @default typeof window === 'undefined' ? 'ansi' : 'css'*/colorMode?: 'ansi' | 'css';};
ts
type LoggerLinkOptions<TRouter extends AnyRouter> = {logger?: LogFn<TRouter>;/*** It is a function that returns a condition that determines whether to enable the logger.* It is true by default.*/enabled?: EnabledFn<TRouter>;/*** Used in the built-in defaultLogger*/console?: ConsoleEsque;/*** Color mode used in the default logger.* @default typeof window === 'undefined' ? 'ansi' : 'css'*/colorMode?: 'ansi' | 'css';};
参考
您可以在 GitHub 上查看此链接的源代码。