Structured logging with request-id + custom context data
This repo demonstrates one solution to structured logging in NextJS (compatible with NodeJS middlewares)
userId
is extracted fromreq.user
or JWT token inAuthorization
header.reqId
is forwarded fromX-Request-Id
or generated if not presenturl
,method
,path
,query
is extracted from requestsserviceName
andenv
set in logger/index.tx- Additional fields (
action
/domain
) set by caller
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);
});
When logger is imported in browser, output will be displayed in console.
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')})
yarn
yarn dev
- Visit http://localhost:3000/api/hello?query=value to see API logging
- Visit http://localhost:3000/api/error to see API error handling and logging
- Visit http://localhost:3000/ to see browser logging in console