Documentation menuMenu da documentação

$ cat docs/middleware/logger.md

Request loggerLogger de requisições

Emit one structured JSON line per request with method, path, status and duration, without changing the response.Emita uma linha JSON estruturada por requisição com método, caminho, status e duração, sem alterar a resposta.

What it doesO que faz

logger(options?: LoggerOptions): MiddlewareHandler. Emits one JSON line per request, { level: 'info', method, path, status, durationMs, ua? }, through sink ?? console.log, after the pipeline settles. It never alters the response and never throws on its own (a failing sink is ignored). includeHeaders: true adds request headers with authorization, cookie, x-csrf-token, x-api-key, x-auth-token and similar ones redacted (plus your redact list) and cf-connecting-ip/x-forwarded-for/x-real-ip masked (maskIp: false keeps them). A thrown error logs its message by default; errorDetail: 'name' logs only the class and 'stack' adds the stack (outside production).

logger(options?: LoggerOptions): MiddlewareHandler. Emite uma linha JSON por requisição, { level: 'info', method, path, status, durationMs, ua? }, via sink ?? console.log, depois que o pipeline termina. Nunca altera a resposta e nunca lança por conta própria (um sink com falha é ignorado). includeHeaders: true adiciona os headers da requisição com authorization, cookie, x-csrf-token, x-api-key, x-auth-token e similares ocultados (mais a sua lista redact) e cf-connecting-ip/x-forwarded-for/ x-real-ip mascarados (maskIp: false os mantém). Um erro lançado registra a mensagem por padrão; errorDetail: 'name' registra só a classe e 'stack' inclui a stack (fora de produção).

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it with app.use(logger()) before routes so it wraps every matched request, including ones that later fail. Use sink to forward the line to your platform logger instead of console.log.

Registre com app.use(logger()) antes das rotas para envolver toda requisição casada, inclusive as que falham depois. Use sink para encaminhar a linha ao logger da sua plataforma em vez de console.log.

ExampleExemplo

logger.ts
import { logger } from '@tupik/middleware';

app.use(logger({ sink: (line) => console.info(line), includeHeaders: false }));

// {"level":"info","method":"GET","path":"/api/health","status":200,"durationMs":0.21,"ua":"curl/8.5.0"}
// a throwing handler is logged and the error is re-thrown:
// {"level":"error","method":"GET","path":"/e","status":500,"durationMs":0.11,"error":"db down"}
import { logger } from '@tupik/middleware';

app.use(logger({ sink: (line) => console.info(line), includeHeaders: false }));

// {"level":"info","method":"GET","path":"/api/health","status":200,"durationMs":0.21,"ua":"curl/8.5.0"}
// um handler que lança é logado e o erro é relançado:
// {"level":"error","method":"GET","path":"/e","status":500,"durationMs":0.11,"error":"db down"}

APIAPI

TypeTipoShapeFormato
LoggerOptions{ sink?: (line: string) => void; includeHeaders?: boolean; redact?: readonly string[]; maskIp?: boolean; errorDetail?: 'name' | 'message' | 'stack' }
LogEntry{ level: 'info' | 'error'; method; path; status; durationMs; ua?; error?; stack?; headers? }

Errors and limitsErros e limites

  • When the handler throws, logger logs level: 'error' with status: 500 before onError runs, then re-throws so the app's error handling still answers.
  • The status in the error line is always 500, even if an onError hook later responds with another code.
  • It logs metadata only: request and response bodies are never captured, and headers stay out unless includeHeaders is on.
  • Quando o handler lança, o logger loga level: 'error' com status: 500 antes do onError rodar, e então relança para que o tratamento de erro do app responda.
  • O status na linha de erro é sempre 500, mesmo que um hook onError responda outro código depois.
  • Ele loga só metadados: bodies de requisição e resposta nunca são capturados, e headers ficam fora a menos que includeHeaders esteja ligado.

When not to use itQuando não usar

Skip it when a platform logger already records every request, or when you need sampled, business-level events: use @tupik/infra's structured logger in handlers for that. It is not an audit trail for sensitive data.

Dispense quando um logger da plataforma já registra todas as requisições, ou quando precisa de eventos de negócio amostrados: use o logger estruturado do @tupik/infra nos handlers para isso. Ele não é uma trilha de auditoria para dados sensíveis.