Be able to extend the request object and middleware / logger instantiation order #2468
-
Problem: I need to include request ID to each of my logs. But in order to implement proper distributed tracing I need to pass it as a http header. However, since the request id header is optional, I would need to generate one, and extend the request object so that this request Id is available in all middlewares and controllers down the pipe. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
import { BuiltinLogger, createConfig, createMiddleware } from "express-zod-api";
// Declaring the logger type in use
declare module "express-zod-api" {
interface LoggerOverrides extends BuiltinLogger {}
}
// Configuring child logger provider
const config = createConfig({
childLoggerProvider: ({ parent }) =>
parent.child({ requestId: randomUUID() }),
});
// Accessing child logger context
createMiddleware({
handler: async ({ logger }) => {
doSomething(logger.ctx.requestId); // <—
},
}); I hope it helps to achieve everything. |
Beta Was this translation helpful? Give feedback.
-
You can do it, @ArtemSkok-Leia |
Beta Was this translation helpful? Give feedback.
@ArtemSkok-Leia ,
what you call "context" is
options
returned and collected from all theMiddleware
connected toEndpointsFactory
you produce theEndpoint
on.So, if you
(which is
childLoggerProvider
config option), then you can do it in a Middleware, like this