ロギングとパフォーマンス計測ミドルウェア
すべての呼び出しを記録し実行時間を計測するミドルウェアを使い、tRPC APIに可観測性を組み込みます。
「ロギングとパフォーマンス計測ミドルウェア」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはtRPC End-to-End Type Safe APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Observe Every Call?
You already use middleware for auth. Middleware is also perfect for cross-cutting concerns like logging and timing that should apply to many procedures.
Middleware Recap
A tRPC middleware wraps a procedure: it runs code, calls next(), then can run code after the result.
const mw = t.middleware(async (opts) => {
// before
const result = await opts.next();
// after
return result;
});A Simple Logger
Log the procedure type and path on every call.
const logger = t.middleware(async ({ path, type, next }) => {
console.log("-> " + type + " " + path);
return next();
});Measuring Duration
Capture the time before and after next() to compute how long the call took.
const timing = t.middleware(async ({ path, next }) => {
const start = Date.now();
const result = await next();
const ms = Date.now() - start;
console.log(path + " took " + ms + "ms");
return result;
});Inspecting the Result
The result tells you whether the call succeeded, useful for logging error rates.
const result = await next();
console.log(result.ok ? "ok" : "error");
return result;Attaching to a Procedure
Use .use() to apply middleware when defining a base procedure.
const loggedProcedure = t.procedure.use(logger).use(timing);Reusing Across Routers
Export the enhanced procedure and build all routers from it so logging applies everywhere automatically.
export const appRouter = router({
ping: loggedProcedure.query(() => "pong"),
});Adding Request IDs
Generate a unique id per call to correlate logs across services.
const withId = t.middleware(async ({ next, ctx }) => {
const reqId = crypto.randomUUID();
return next({ ctx: { ...ctx, reqId } });
});Structured Logging
Emit JSON instead of plain text so logs are searchable in tools like Datadog or ELK.
console.log(JSON.stringify({ path, type, ms, level: "info" }));Order of Middleware
Middleware runs in the order added. Put timing outermost so it includes the work of inner middleware.
Sampling Logs
In high-traffic APIs, logging every call is costly. Sample a percentage of requests so you keep visibility without overwhelming your log pipeline.
if (Math.random() < 0.1) console.log(path);Quick Check
Test your middleware knowledge.
Recap
You added observability with middleware:
- Middleware runs code before and after next()
- Use it for logging, timing, and request IDs
- Build a shared base procedure so it applies everywhere
Good observability makes a tRPC API far easier to debug in production.
よくある質問
「ロギングとパフォーマンス計測ミドルウェア」レッスンは無料ですか?
はい。「ロギングとパフォーマンス計測ミドルウェア」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、tRPC End-to-End Type Safe APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。
「ロギングとパフォーマンス計測ミドルウェア」で何を学びますか?
すべての呼び出しを記録し実行時間を計測するミドルウェアを使い、tRPC APIに可観測性を組み込みます。 ブラウザで直接実行するハンズオンコードでtRPC End-to-End Type Safe APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
tRPC End-to-End Type Safe APIsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのtRPC End-to-End Type Safe APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「ロギングとパフォーマンス計測ミドルウェア」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このtRPC End-to-End Type Safe APIsレッスンでコードを書いて実行できますか?
はい。すべてのtRPC End-to-End Type Safe APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- tRPCコンテキストの作成
- 認証ミドルウェア
- カスタムミドルウェアチェーン
- ロギングとパフォーマンス計測ミドルウェア