0Pricing
tRPC End-to-End Type Safe APIs · Lezione

Middleware per logging e misurazione delle prestazioni

Aggiunga osservabilità alla sua API tRPC con middleware che registra ogni chiamata e ne misura il tempo di esecuzione.

Middleware per logging e misurazione delle prestazioni è una lezione tRPC End-to-End Type Safe APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento tRPC End-to-End Type Safe APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Middleware per logging e misurazione delle prestazioni» è gratuita?

Sì — il testo completo di «Middleware per logging e misurazione delle prestazioni» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso tRPC End-to-End Type Safe APIs, passa a CoddyKit PRO. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.

Cosa imparerò in «Middleware per logging e misurazione delle prestazioni»?

Aggiunga osservabilità alla sua API tRPC con middleware che registra ogni chiamata e ne misura il tempo di esecuzione. Eserciti tRPC End-to-End Type Safe APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare tRPC End-to-End Type Safe APIs?

Non è richiesta alcuna esperienza precedente. tRPC End-to-End Type Safe APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Middleware per logging e misurazione delle prestazioni»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione tRPC End-to-End Type Safe APIs?

Sì. Ogni lezione tRPC End-to-End Type Safe APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Creare il context tRPC
  2. Middleware di autenticazione
  3. Catene di middleware personalizzate
  4. Middleware per logging e misurazione delle prestazioni
← Torna a tRPC End-to-End Type Safe APIs