メインコンテンツへスキップ
バージョン: 11.x

ロガーリンク

loggerLink は、tRPC クライアントにロガーを実装するためのリンクです。これにより、どの操作がクエリ、ミューテーション、またはサブスクリプションなのか、そのリクエストとレスポンスなどをより明確に確認できます。このリンクは、既定でブラウザのコンソールに整形されたログを出力します。ただし、ロギングの動作やコンソールへの出力方法は、独自のインプリメンテーションでカスタマイズできます。

使用

loggerLinklinks 配列に次のようにインポートして追加できます

client/index.ts
ts
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.ts
ts
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 関数は、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で確認できます。