nestjs-pino 5.3.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -138,6 +138,17 @@ export class MyService {
138
138
  > failure, no warning
139
139
  > ([#3074](https://github.com/iamolegga/nestjs-pino/issues/3074)).
140
140
 
141
+ > [!NOTE]
142
+ > `@InjectPinoLogger(...)` does not work in a module loaded through
143
+ > [`LazyModuleLoader`](https://docs.nestjs.com/fundamentals/lazy-loading-modules),
144
+ > and fails with `Nest can't resolve dependencies of the YourService (?)` for the
145
+ > `PinoLogger:<context>` token. The providers behind those tokens are created by
146
+ > `forRoot(...)` out of the contexts the decorator has registered by then, and a
147
+ > lazy module is only evaluated once it is loaded — too late to be among them.
148
+ > Inject `PinoLogger` and call `setContext(...)`, as in the first constructor
149
+ > above: it needs no token of its own and works everywhere, lazy modules
150
+ > included ([#2069](https://github.com/iamolegga/nestjs-pino/issues/2069)).
151
+
141
152
  ### Drop-in replacement: NativeLogger
142
153
 
143
154
  `NativeLogger` is a **drop-in replacement** for NestJS's built-in `ConsoleLogger`. It produces **identical JSON output** — same field names, same argument handling, same error format — but powered by pino with request context in every log.
@@ -501,6 +512,16 @@ class MyModule {}
501
512
 
502
513
  See [pino.destination](https://github.com/pinojs/pino/blob/master/docs/api.md#pino-destination)
503
514
 
515
+ ### Flushing on shutdown
516
+
517
+ An asynchronous destination, and likewise a [transport](https://github.com/pinojs/pino/blob/master/docs/transports.md), which runs in a worker thread, flushes its buffer on the process `exit` event. NestJS's [shutdown hooks](https://docs.nestjs.com/fundamentals/lifecycle-events#application-shutdown) end the process by re-raising the signal instead, which never emits `exit`: whatever was logged from `beforeApplicationShutdown` and `onApplicationShutdown` is lost, while `console.log` from the same places shows up. Since `@nestjs/core@11.1.10`, ask them to exit through `process.exit()` instead:
518
+
519
+ ```ts
520
+ app.enableShutdownHooks(undefined, { useProcessExit: true });
521
+ ```
522
+
523
+ Mind that this changes the exit code (`0` instead of, say, `143` on `SIGTERM`), which an orchestrator may take into account.
524
+
504
525
  ## Testing a class that uses @InjectPinoLogger
505
526
 
506
527
  This package exposes a `getLoggerToken()` function that returns a prepared injection token based on the provided context.
@@ -1028,6 +1049,17 @@ In NestJS <= 7 and `nestjs-pino@1` when you call `this.logger.log('foo', 'bar');
1028
1049
 
1029
1050
  **A**: check out [genReqId field of pino-http](https://github.com/pinojs/pino-http#pinohttpopts-stream) that are set in `pinoHttp` field of `Params`
1030
1051
 
1052
+ With Fastify, though, that field is never used: Fastify assigns its own `request.id` before any middleware runs, `@fastify/middie` copies it onto the raw request, and `pino-http` keeps an existing `req.id` rather than generating one. Pass the generator to the adapter instead, and both Fastify and the logs use it:
1053
+
1054
+ ```ts
1055
+ const app = await NestFactory.create<NestFastifyApplication>(
1056
+ AppModule,
1057
+ new FastifyAdapter({
1058
+ genReqId: (req) => req.headers['x-request-id']?.toString() ?? randomUUID(),
1059
+ }),
1060
+ );
1061
+ ```
1062
+
1031
1063
  ---
1032
1064
 
1033
1065
  **Q**: _How does it work?_
@@ -1,14 +1,23 @@
1
1
  import { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
3
- import { ApplicationConfig } from '@nestjs/core';
3
+ import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
4
4
  import { type LoggerModuleAsyncParams, type Params } from './params.js';
5
5
  export declare class LoggerModule implements NestModule {
6
6
  private readonly params;
7
7
  private readonly applicationConfig;
8
+ private readonly httpAdapterHost;
8
9
  static forRoot<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params?: Params<IM, SR, CustomLevels>): DynamicModule;
9
10
  static forRootAsync<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule;
10
- constructor(params: Params, applicationConfig: ApplicationConfig);
11
+ constructor(params: Params, applicationConfig: ApplicationConfig, httpAdapterHost: HttpAdapterHost);
11
12
  configure(consumer: MiddlewareConsumer): void;
13
+ /**
14
+ * Fastify hands its headers to the raw response in a single `writeHead`
15
+ * call, and Node keeps no record of headers passed that way: `getHeaders()`,
16
+ * which the `res` serializer reads, stays empty. Setting them on the raw
17
+ * response first makes `writeHead` merge into that record instead, so the
18
+ * request log carries the response headers as it does under Express.
19
+ */
20
+ private exposeFastifyResponseHeaders;
12
21
  /**
13
22
  * A path excluded from the global prefix is served outside of it, while
14
23
  * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a
@@ -39,6 +39,7 @@ const DEFAULT_ROUTES = [{ path: '{/*splat}', method: common_1.RequestMethod.ALL
39
39
  let LoggerModule = LoggerModule_1 = class LoggerModule {
40
40
  params;
41
41
  applicationConfig;
42
+ httpAdapterHost;
42
43
  static forRoot(params) {
43
44
  const paramsProvider = {
44
45
  provide: params_js_1.PARAMS_PROVIDER_TOKEN,
@@ -97,9 +98,10 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
97
98
  ],
98
99
  };
99
100
  }
100
- constructor(params, applicationConfig) {
101
+ constructor(params, applicationConfig, httpAdapterHost) {
101
102
  this.params = params;
102
103
  this.applicationConfig = applicationConfig;
104
+ this.httpAdapterHost = httpAdapterHost;
103
105
  // Microservices have no middleware, so `configure` is never called for
104
106
  // them. The hook is registered here instead, early enough that the message
105
107
  // handlers being built later pick it up.
@@ -120,6 +122,28 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
120
122
  else {
121
123
  consumer.apply(...middlewares).forRoutes(...forRoutes);
122
124
  }
125
+ this.exposeFastifyResponseHeaders();
126
+ }
127
+ /**
128
+ * Fastify hands its headers to the raw response in a single `writeHead`
129
+ * call, and Node keeps no record of headers passed that way: `getHeaders()`,
130
+ * which the `res` serializer reads, stays empty. Setting them on the raw
131
+ * response first makes `writeHead` merge into that record instead, so the
132
+ * request log carries the response headers as it does under Express.
133
+ */
134
+ exposeFastifyResponseHeaders() {
135
+ const adapter = this.httpAdapterHost.httpAdapter;
136
+ if (adapter?.getType() !== 'fastify')
137
+ return;
138
+ adapter
139
+ .getInstance()
140
+ .addHook('onSend', (_req, reply, _payload, done) => {
141
+ for (const [name, value] of Object.entries(reply.getHeaders())) {
142
+ if (value !== undefined)
143
+ reply.raw.setHeader(name, value);
144
+ }
145
+ done();
146
+ });
123
147
  }
124
148
  /**
125
149
  * A path excluded from the global prefix is served outside of it, while
@@ -146,7 +170,7 @@ exports.LoggerModule = LoggerModule = LoggerModule_1 = __decorate([
146
170
  (0, common_1.Global)(),
147
171
  (0, common_1.Module)({ providers: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger], exports: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger] }),
148
172
  __param(0, (0, common_1.Inject)(params_js_1.PARAMS_PROVIDER_TOKEN)),
149
- __metadata("design:paramtypes", [Object, core_1.ApplicationConfig])
173
+ __metadata("design:paramtypes", [Object, core_1.ApplicationConfig, core_1.HttpAdapterHost])
150
174
  ], LoggerModule);
151
175
  /**
152
176
  * Exposes the very hook the module registers on its own, for the one case it
@@ -1 +1 @@
1
- {"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAiD;AAEjD,+DAAoE;AACpE,2CAAqC;AACrC,uDAI2B;AAC3B,uDAAiD;AACjD,mDAA6C;AAC7C,2CAIqB;AACrB,mDAA2E;AAC3E,6CAA8C;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IA7E7B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,iCAAqB;YAC9B,QAA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E,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,oBAAO,CAAC,GAAG,CAAC,IAAI,kBAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
1
+ {"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAkE;AAElE,+DAAoE;AACpE,2CAAqC;AACrC,uDAI2B;AAC3B,uDAAiD;AACjD,mDAA6C;AAC7C,2CAIqB;AACrB,mDAA2E;AAC3E,6CAA8C;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IACjB,eAAe;IA9E3B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,iCAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,IAAA,iDAA2B,GAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;QAE1C,OAAO;YACL,MAAM,gBAAc;YACpB,SAAS,EAAE;gBACT,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;YACD,OAAO,EAAE;gBACP,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;SACF,CAAC;IACJ,CAAC;IAEM,AAAP,MAAM,CAAC,YAAY,CAIjB,MAAqD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AAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAElD,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAChC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,oBAAO,CAAC,GAAG,CAAC,IAAI,kBAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
@@ -1,14 +1,23 @@
1
1
  import { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
3
- import { ApplicationConfig } from '@nestjs/core';
3
+ import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
4
4
  import { type LoggerModuleAsyncParams, type Params } from './params.js';
5
5
  export declare class LoggerModule implements NestModule {
6
6
  private readonly params;
7
7
  private readonly applicationConfig;
8
+ private readonly httpAdapterHost;
8
9
  static forRoot<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params?: Params<IM, SR, CustomLevels>): DynamicModule;
9
10
  static forRootAsync<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule;
10
- constructor(params: Params, applicationConfig: ApplicationConfig);
11
+ constructor(params: Params, applicationConfig: ApplicationConfig, httpAdapterHost: HttpAdapterHost);
11
12
  configure(consumer: MiddlewareConsumer): void;
13
+ /**
14
+ * Fastify hands its headers to the raw response in a single `writeHead`
15
+ * call, and Node keeps no record of headers passed that way: `getHeaders()`,
16
+ * which the `res` serializer reads, stays empty. Setting them on the raw
17
+ * response first makes `writeHead` merge into that record instead, so the
18
+ * request log carries the response headers as it does under Express.
19
+ */
20
+ private exposeFastifyResponseHeaders;
12
21
  /**
13
22
  * A path excluded from the global prefix is served outside of it, while
14
23
  * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a
@@ -12,7 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  };
13
13
  var LoggerModule_1;
14
14
  import { Global, Inject, Module, RequestMethod, } from '@nestjs/common';
15
- import { ApplicationConfig } from '@nestjs/core';
15
+ import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
16
16
  import { createProvidersForDecorated } from './InjectPinoLogger.js';
17
17
  import { Logger } from './Logger.js';
18
18
  import { getMicroserviceHook, PINO_PRE_REQUEST_HOOK, registerMicroserviceHook, } from './microservice.js';
@@ -36,6 +36,7 @@ const DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];
36
36
  let LoggerModule = LoggerModule_1 = class LoggerModule {
37
37
  params;
38
38
  applicationConfig;
39
+ httpAdapterHost;
39
40
  static forRoot(params) {
40
41
  const paramsProvider = {
41
42
  provide: PARAMS_PROVIDER_TOKEN,
@@ -94,9 +95,10 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
94
95
  ],
95
96
  };
96
97
  }
97
- constructor(params, applicationConfig) {
98
+ constructor(params, applicationConfig, httpAdapterHost) {
98
99
  this.params = params;
99
100
  this.applicationConfig = applicationConfig;
101
+ this.httpAdapterHost = httpAdapterHost;
100
102
  // Microservices have no middleware, so `configure` is never called for
101
103
  // them. The hook is registered here instead, early enough that the message
102
104
  // handlers being built later pick it up.
@@ -117,6 +119,28 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
117
119
  else {
118
120
  consumer.apply(...middlewares).forRoutes(...forRoutes);
119
121
  }
122
+ this.exposeFastifyResponseHeaders();
123
+ }
124
+ /**
125
+ * Fastify hands its headers to the raw response in a single `writeHead`
126
+ * call, and Node keeps no record of headers passed that way: `getHeaders()`,
127
+ * which the `res` serializer reads, stays empty. Setting them on the raw
128
+ * response first makes `writeHead` merge into that record instead, so the
129
+ * request log carries the response headers as it does under Express.
130
+ */
131
+ exposeFastifyResponseHeaders() {
132
+ const adapter = this.httpAdapterHost.httpAdapter;
133
+ if (adapter?.getType() !== 'fastify')
134
+ return;
135
+ adapter
136
+ .getInstance()
137
+ .addHook('onSend', (_req, reply, _payload, done) => {
138
+ for (const [name, value] of Object.entries(reply.getHeaders())) {
139
+ if (value !== undefined)
140
+ reply.raw.setHeader(name, value);
141
+ }
142
+ done();
143
+ });
120
144
  }
121
145
  /**
122
146
  * A path excluded from the global prefix is served outside of it, while
@@ -142,7 +166,8 @@ LoggerModule = LoggerModule_1 = __decorate([
142
166
  Global(),
143
167
  Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] }),
144
168
  __param(0, Inject(PARAMS_PROVIDER_TOKEN)),
145
- __metadata("design:paramtypes", [Object, ApplicationConfig])
169
+ __metadata("design:paramtypes", [Object, ApplicationConfig,
170
+ HttpAdapterHost])
146
171
  ], LoggerModule);
147
172
  export { LoggerModule };
148
173
  /**
@@ -1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C,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
1
+ {"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;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,GAAG,CAAC,GAAG,CAAC;QAClB,IAAI,MAAM,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAElD,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAChC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nestjs-pino",
3
- "version": "5.3.0",
3
+ "version": "5.3.1",
4
4
  "description": "Pino logger for NestJS",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "types": "./dist/cjs/index.d.ts",