Logger 链接
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
loggerLink 是一个用于为 tRPC 客户端实现日志记录功能的链接。它能清晰展示查询、变更或订阅操作及其请求和响应。默认情况下,该链接会在浏览器控制台输出格式化的日志。但您可以通过自定义实现来调整日志记录行为和输出方式。
用法
您可以通过以下方式导入并将 loggerLink 添加到 links 数组:
client/index.tstsimport {createTRPCClient ,httpBatchLink ,loggerLink } from '@trpc/client';import type {AppRouter } from './server';constclient =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' &&typeofwindow !== 'undefined') ||(opts .direction === 'down' &&opts .result instanceofError ),}),httpBatchLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchLink ,loggerLink } from '@trpc/client';import type {AppRouter } from './server';constclient =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' &&typeofwindow !== 'undefined') ||(opts .direction === 'down' &&opts .result instanceofError ),}),httpBatchLink ({url : 'http://localhost:3000',}),],});
loggerLink 配置项
loggerLink 函数接收一个符合 LoggerLinkOptions 结构的配置对象:
tstypeLoggerLinkOptions <TRouter extendsAnyRouter > = {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' | 'none';/*** Include context in the log - defaults to false unless colorMode is 'css'*/withContext ?: boolean;};
tstypeLoggerLinkOptions <TRouter extendsAnyRouter > = {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' | 'none';/*** Include context in the log - defaults to false unless colorMode is 'css'*/withContext ?: boolean;};
参考文档
您可以在 GitHub 上查看该链接的源码实现。