Skip to content

tomfa/nextjs-pino-logging

Repository files navigation

NextJS logging using Pino

Structured logging with request-id + custom context data

This repo demonstrates one solution to structured logging in NextJS (compatible with NodeJS middlewares)

API logging

  • userId is extracted from req.user or JWT token in Authorization header.
  • reqId is forwarded from X-Request-Id or generated if not present
  • url, method, path, query is extracted from requests
  • serviceName and env set in logger/index.tx
  • Additional fields (action/domain) set by caller

API logging with pino-pretty

Example: pages/api/hello.tsx – the output above is formatted with pino-pretty.

const handler = baseHandler().get((req, res) => {
  const user = { id: "123", name: "John Doe " };
  Logger.info("Hi there", {
    action: "USER_LOGIN",
    domain: "AUTH",
  });

  res.status(200).json(user);
});

Browser logging

When logger is imported in browser, output will be displayed in console.

Browser logging

Example: pages/index.tsx

Logger.info('Something meaningful happened')
Logger.warning('I do not like this', { action: 'VIEW_PAGE'})
Logger.error('Auch, this will break', { error: new Error('Something went wrong')})

Local setup

yarn
yarn dev