로깅 및 성능 측정 미들웨어
모든 호출을 기록하고 실행 시간을 측정하는 미들웨어로 tRPC API에 관측 기능을 구축합니다.
로깅 및 성능 측정 미들웨어은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“로깅 및 성능 측정 미들웨어”에서 뭘 배우나요?
모든 호출을 기록하고 실행 시간을 측정하는 미들웨어로 tRPC API에 관측 기능을 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 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 컨텍스트 만들기
- 인증 미들웨어
- 사용자 지정 미들웨어 연결
- 로깅 및 성능 측정 미들웨어