nestjs-pino 5.1.0 → 5.2.0-alpha.f9be0f

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.
Files changed (95) hide show
  1. package/README.md +260 -4
  2. package/dist/{InjectPinoLogger.d.ts → cjs/InjectPinoLogger.d.ts} +1 -1
  3. package/dist/{InjectPinoLogger.js → cjs/InjectPinoLogger.js} +2 -2
  4. package/dist/cjs/InjectPinoLogger.js.map +1 -0
  5. package/dist/{Logger.d.ts → cjs/Logger.d.ts} +2 -2
  6. package/dist/{Logger.js → cjs/Logger.js} +4 -4
  7. package/dist/cjs/Logger.js.map +1 -0
  8. package/dist/cjs/LoggerErrorInterceptor.js.map +1 -0
  9. package/dist/{LoggerModule.d.ts → cjs/LoggerModule.d.ts} +1 -1
  10. package/dist/{LoggerModule.js → cjs/LoggerModule.js} +64 -24
  11. package/dist/cjs/LoggerModule.js.map +1 -0
  12. package/dist/{NativeLogger.d.ts → cjs/NativeLogger.d.ts} +2 -2
  13. package/dist/{NativeLogger.js → cjs/NativeLogger.js} +4 -4
  14. package/dist/cjs/NativeLogger.js.map +1 -0
  15. package/dist/{PinoLogger.d.ts → cjs/PinoLogger.d.ts} +1 -1
  16. package/dist/{PinoLogger.js → cjs/PinoLogger.js} +12 -12
  17. package/dist/cjs/PinoLogger.js.map +1 -0
  18. package/dist/cjs/index.d.ts +10 -0
  19. package/dist/cjs/index.js +26 -0
  20. package/dist/cjs/index.js.map +1 -0
  21. package/dist/cjs/microservice.d.ts +47 -0
  22. package/dist/cjs/microservice.js +201 -0
  23. package/dist/cjs/microservice.js.map +1 -0
  24. package/dist/cjs/params.d.ts +216 -0
  25. package/dist/cjs/params.js.map +1 -0
  26. package/dist/cjs/presets.js.map +1 -0
  27. package/dist/cjs/rootLogger.js.map +1 -0
  28. package/dist/cjs/rpc.d.ts +35 -0
  29. package/dist/cjs/rpc.js +104 -0
  30. package/dist/cjs/rpc.js.map +1 -0
  31. package/dist/cjs/storage.js.map +1 -0
  32. package/dist/esm/InjectPinoLogger.d.ts +5 -0
  33. package/dist/esm/InjectPinoLogger.js +25 -0
  34. package/dist/esm/InjectPinoLogger.js.map +1 -0
  35. package/dist/esm/Logger.d.ts +34 -0
  36. package/dist/esm/Logger.js +100 -0
  37. package/dist/esm/Logger.js.map +1 -0
  38. package/dist/esm/LoggerErrorInterceptor.d.ts +5 -0
  39. package/dist/esm/LoggerErrorInterceptor.js +32 -0
  40. package/dist/esm/LoggerErrorInterceptor.js.map +1 -0
  41. package/dist/esm/LoggerModule.d.ts +22 -0
  42. package/dist/esm/LoggerModule.js +188 -0
  43. package/dist/esm/LoggerModule.js.map +1 -0
  44. package/dist/esm/NativeLogger.d.ts +22 -0
  45. package/dist/esm/NativeLogger.js +196 -0
  46. package/dist/esm/NativeLogger.js.map +1 -0
  47. package/dist/esm/PinoLogger.d.ts +81 -0
  48. package/dist/esm/PinoLogger.js +152 -0
  49. package/dist/esm/PinoLogger.js.map +1 -0
  50. package/dist/esm/index.d.ts +10 -0
  51. package/dist/esm/index.js +11 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/microservice.d.ts +47 -0
  54. package/dist/esm/microservice.js +195 -0
  55. package/dist/esm/microservice.js.map +1 -0
  56. package/dist/esm/package.json +1 -0
  57. package/dist/esm/params.d.ts +216 -0
  58. package/dist/esm/params.js +5 -0
  59. package/dist/esm/params.js.map +1 -0
  60. package/dist/esm/presets.d.ts +20 -0
  61. package/dist/esm/presets.js +33 -0
  62. package/dist/esm/presets.js.map +1 -0
  63. package/dist/esm/rootLogger.d.ts +16 -0
  64. package/dist/esm/rootLogger.js +46 -0
  65. package/dist/esm/rootLogger.js.map +1 -0
  66. package/dist/esm/rpc.d.ts +35 -0
  67. package/dist/esm/rpc.js +101 -0
  68. package/dist/esm/rpc.js.map +1 -0
  69. package/dist/esm/storage.d.ts +8 -0
  70. package/dist/esm/storage.js +11 -0
  71. package/dist/esm/storage.js.map +1 -0
  72. package/package.json +22 -15
  73. package/dist/InjectPinoLogger.js.map +0 -1
  74. package/dist/Logger.js.map +0 -1
  75. package/dist/LoggerErrorInterceptor.js.map +0 -1
  76. package/dist/LoggerModule.js.map +0 -1
  77. package/dist/NativeLogger.js.map +0 -1
  78. package/dist/PinoLogger.js.map +0 -1
  79. package/dist/index.d.ts +0 -8
  80. package/dist/index.js +0 -21
  81. package/dist/index.js.map +0 -1
  82. package/dist/params.d.ts +0 -91
  83. package/dist/params.js.map +0 -1
  84. package/dist/presets.js.map +0 -1
  85. package/dist/rootLogger.js.map +0 -1
  86. package/dist/storage.js.map +0 -1
  87. /package/dist/{LoggerErrorInterceptor.d.ts → cjs/LoggerErrorInterceptor.d.ts} +0 -0
  88. /package/dist/{LoggerErrorInterceptor.js → cjs/LoggerErrorInterceptor.js} +0 -0
  89. /package/dist/{params.js → cjs/params.js} +0 -0
  90. /package/dist/{presets.d.ts → cjs/presets.d.ts} +0 -0
  91. /package/dist/{presets.js → cjs/presets.js} +0 -0
  92. /package/dist/{rootLogger.d.ts → cjs/rootLogger.d.ts} +0 -0
  93. /package/dist/{rootLogger.js → cjs/rootLogger.js} +0 -0
  94. /package/dist/{storage.d.ts → cjs/storage.d.ts} +0 -0
  95. /package/dist/{storage.js → cjs/storage.js} +0 -0
package/README.md CHANGED
@@ -44,7 +44,7 @@
44
44
 
45
45
  | nestjs-pino | NestJS | pino | pino-http | Node.js |
46
46
  | ----------- | ------------ | ------------ | ----------------------------- | -------- |
47
- | v5 | 11.0.8+, 12 | 10 | 11 | >=22.12 |
47
+ | v5 | 11.0.8+, 12.0.2+ | 10 | 11 | >=22.12 |
48
48
  | [v4](https://github.com/iamolegga/nestjs-pino/tree/v4.6.1#readme) | 8, 9, 10, 11 | 7.5+, 8, 9, 10 | 6.4+, 7, 8, 9, 10, 11 | >=14 |
49
49
  | [v1](https://github.com/iamolegga/nestjs-pino/tree/v1.4.0#readme) | < 8 | | | |
50
50
 
@@ -343,6 +343,12 @@ interface Params<
343
343
  */
344
344
  assignResponse?: boolean;
345
345
 
346
+ /**
347
+ * Optional parameters for automatic logging of microservice messages, and
348
+ * for a logging context in message handlers. See the "Microservices"
349
+ * section below. Pass `true` for the defaults.
350
+ */
351
+ microservice?: boolean | MicroserviceParams<CustomLevels>;
346
352
  }
347
353
  ```
348
354
 
@@ -594,6 +600,254 @@ class MyService {
594
600
 
595
601
  By default, this does not extend `Request completed` logs. Set the `assignResponse` parameter to `true` to also enrich response logs automatically emitted by `pino-http`.
596
602
 
603
+ ## Microservices
604
+
605
+ Message handlers get the same treatment HTTP requests do: every log made while
606
+ handling a message carries the message's context, `assign` works, and a line per
607
+ message is logged automatically. Add the `microservice` parameter:
608
+
609
+ ```ts
610
+ LoggerModule.forRoot({
611
+ pinoHttp: { level: 'debug' }, // as before: level, transport, redact, ...
612
+ microservice: true, // that's all
613
+ });
614
+ ```
615
+
616
+ Nothing changes in `main.ts` — the module registers a [pre-request
617
+ hook](https://docs.nestjs.com/microservices/pre-request-hooks) by itself:
618
+
619
+ ```ts
620
+ const app = await NestFactory.createMicroservice(AppModule, {
621
+ transport: Transport.RMQ,
622
+ options: { urls: ['amqp://localhost'], queue: 'users' },
623
+ bufferLogs: true,
624
+ });
625
+ app.useLogger(app.get(Logger));
626
+ await app.listen();
627
+ ```
628
+
629
+ ```ts
630
+ @Controller()
631
+ export class UserController {
632
+ constructor(private readonly logger: PinoLogger) {}
633
+
634
+ @EventPattern('user.created')
635
+ async handle(@Payload() data: UserCreated) {
636
+ this.logger.assign({ userId: data.id });
637
+ this.logger.info('provisioning');
638
+ await this.provision(data);
639
+ }
640
+ }
641
+ ```
642
+
643
+ ```json
644
+ {"level":30,"reqId":1,"rpc":{"type":"event","pattern":"user.created","transport":"rmq","controller":"UserController","handler":"handle"},"userId":"u_42","msg":"provisioning"}
645
+ {"level":30,"reqId":1,"rpc":{"type":"event","pattern":"user.created","transport":"rmq","controller":"UserController","handler":"handle"},"userId":"u_42","responseTime":37,"msg":"event completed"}
646
+ ```
647
+
648
+ The automatic messages are `message completed`/`message errored` for a
649
+ `@MessagePattern`, where the caller is waiting for a reply, and `event
650
+ completed`/`event errored` for an `@EventPattern`, where nobody is. As in
651
+ `pino-http`, nothing is logged on arrival unless `customReceivedMessage` or
652
+ `customReceivedObject` says so. Unlike `pino-http`, a failed message defaults to
653
+ `error` rather than to `useLevel`, so that lowering `useLevel` to quiet down
654
+ events does not also hide failures. Note that the hook sees the error before
655
+ any `@Catch()` filter, so an `RpcException` thrown on purpose and mapped to a
656
+ client response arrives here too — reach for `customLogLevel` if that should
657
+ not be an `error`. No counterpart of `LoggerErrorInterceptor` is needed: the
658
+ hook receives the error directly.
659
+
660
+ **Requirements.** Pre-request hooks arrived in NestJS 12, and 12.0.2 is the
661
+ first release on which a hook leaves a handler's plain return value alone
662
+ ([nestjs/nest#17644](https://github.com/nestjs/nest/pull/17644)) — hence the
663
+ lower bound of the peer range. On NestJS 11 the parameter is ignored with a
664
+ warning and everything else keeps working.
665
+
666
+ ### Hybrid applications
667
+
668
+ A hybrid application must be connected with `inheritAppConfig`, because without
669
+ it NestJS gives the microservice an `ApplicationConfig` of its own that
670
+ dependency injection cannot reach:
671
+
672
+ ```ts
673
+ app.connectMicroservice(
674
+ { transport: Transport.RMQ, options: { urls: ['amqp://localhost'], queue: 'users' } },
675
+ { inheritAppConfig: true },
676
+ );
677
+ ```
678
+
679
+ If that does not suit you, wire it up by hand instead:
680
+
681
+ ```ts
682
+ import { registerMicroserviceLogging } from 'nestjs-pino';
683
+
684
+ const ms = app.connectMicroservice(options, { deferInitialization: true });
685
+ registerMicroserviceLogging(ms);
686
+ ```
687
+
688
+ ### Microservice configuration params
689
+
690
+ Shaped after `pino-http`'s: every parameter that does not need the request or
691
+ the response keeps its name and meaning, and the ones that do take an
692
+ `ExecutionContext` instead. Everything pino itself is configured with — level,
693
+ transport, redact, serializers — stays in `pinoHttp`, which builds the one
694
+ logger both halves of the application share.
695
+
696
+ ```ts
697
+ interface MicroserviceParams<CustomLevels extends string = never> {
698
+ /**
699
+ * Set to `false` to stop logging a line per message. The logging *context*
700
+ * is still established either way, so `PinoLogger.assign` and the inherited
701
+ * fields keep working.
702
+ * @default true
703
+ */
704
+ autoLogging?:
705
+ | boolean
706
+ | {
707
+ /** Skip the automatic logs for the messages this returns `true` for. */
708
+ ignore?: (context: ExecutionContext) => boolean;
709
+ };
710
+
711
+ /**
712
+ * Level of the `received` and `completed` logs. Errors default to `error`
713
+ * regardless of this — unlike `pino-http`, where a failed request is logged
714
+ * at `useLevel` too — so that lowering this to quiet down events does not
715
+ * also hide failures. Use `customLogLevel` to change the error level.
716
+ * Cannot be combined with `customLogLevel`.
717
+ * @default 'info'
718
+ */
719
+ useLevel?: LevelWithSilent | CustomLevels;
720
+
721
+ /**
722
+ * Decides the level of every automatic log, including the error one. Note
723
+ * that the hook runs before any `@Catch()` filter, so `error` is set for
724
+ * exceptions the application goes on to handle itself, an `RpcException`
725
+ * thrown on purpose included.
726
+ */
727
+ customLogLevel?: (
728
+ context: ExecutionContext,
729
+ error?: Error,
730
+ ) => LevelWithSilent | CustomLevels;
731
+
732
+ /**
733
+ * Generates the value bound as `reqId`. Defaults to an incrementing counter,
734
+ * as in `pino-http`; a correlation id off the transport context is usually a
735
+ * better choice.
736
+ */
737
+ genReqId?: (context: ExecutionContext) => ReqId;
738
+
739
+ /**
740
+ * Setting this — or `customReceivedObject` — is what enables the log on
741
+ * arrival. There is no default text, so nothing is logged on arrival unless
742
+ * asked for, exactly as in `pino-http`.
743
+ */
744
+ customReceivedMessage?: (context: ExecutionContext) => string;
745
+
746
+ /** @default `'message completed'`, or `'event completed'` for an `@EventPattern` */
747
+ customSuccessMessage?: (
748
+ context: ExecutionContext,
749
+ result: unknown,
750
+ responseTime: number,
751
+ ) => string;
752
+
753
+ /** @default `'message errored'`, or `'event errored'` for an `@EventPattern` */
754
+ customErrorMessage?: (
755
+ context: ExecutionContext,
756
+ error: Error,
757
+ responseTime: number,
758
+ ) => string;
759
+
760
+ /**
761
+ * Fields of the log on arrival, which it enables the same way
762
+ * `customReceivedMessage` does. There is no default object, so what it
763
+ * returns is logged as is.
764
+ */
765
+ customReceivedObject?: (context: ExecutionContext) => object;
766
+
767
+ /**
768
+ * Replaces the fields of the `completed` log. `value` is what would be logged
769
+ * otherwise — `responseTime` under its configured key — and is not merged
770
+ * back in, so spread it if the extra fields should come on top.
771
+ */
772
+ customSuccessObject?: (
773
+ context: ExecutionContext,
774
+ result: unknown,
775
+ value: object,
776
+ ) => object;
777
+
778
+ /**
779
+ * Replaces the fields of the `errored` log. `value` holds `err` and
780
+ * `responseTime` under their configured keys and, as with
781
+ * `customSuccessObject`, is not merged back in.
782
+ */
783
+ customErrorObject?: (
784
+ context: ExecutionContext,
785
+ error: Error,
786
+ value: object,
787
+ ) => object;
788
+
789
+ /** Extra fields bound to every log made while handling the message. */
790
+ customProps?: (context: ExecutionContext) => object;
791
+
792
+ /**
793
+ * Renames the keys this adds to the log record. The `rpc` key is the
794
+ * microservice counterpart of `pino-http`'s `req`/`res`.
795
+ */
796
+ customAttributeKeys?: {
797
+ /** @default 'rpc' */
798
+ rpc?: string;
799
+ /** @default 'err' */
800
+ err?: string;
801
+ /** @default 'reqId' */
802
+ reqId?: string;
803
+ /** @default 'responseTime' */
804
+ responseTime?: string;
805
+ };
806
+
807
+ /**
808
+ * Bind only `reqId`, leaving the `rpc` object out of the logs made while
809
+ * handling the message. Mirrors `pino-http`'s `quietReqLogger`.
810
+ */
811
+ quietRpcLogger?: boolean;
812
+
813
+ /**
814
+ * Leave the `rpc` object out of the `completed`/`errored` log, which repeats
815
+ * what the surrounding logs already carry. Mirrors `quietResLogger`.
816
+ */
817
+ quietResLogger?: boolean;
818
+
819
+ /**
820
+ * Log the message payload as `rpc.payload`. Off by default: payloads are
821
+ * unbounded in size and routinely carry personal data. `redact` and a
822
+ * `serializers.rpc` entry in `pinoHttp` apply to it as to anything else.
823
+ * @default false
824
+ */
825
+ includePayload?: boolean;
826
+ }
827
+ ```
828
+
829
+ Use `getRpcInfo(ctx)` inside any of these to reach the pattern, the transport
830
+ and the kind of handler. It returns what is logged under `rpc`, and never
831
+ throws:
832
+
833
+ ```ts
834
+ import { getRpcInfo } from 'nestjs-pino';
835
+
836
+ LoggerModule.forRoot({
837
+ microservice: {
838
+ // events are noisy, replies are not
839
+ customLogLevel: (ctx, err) =>
840
+ err ? 'error' : getRpcInfo(ctx).type === 'event' ? 'debug' : 'info',
841
+
842
+ autoLogging: { ignore: (ctx) => getRpcInfo(ctx).handler === 'healthcheck' },
843
+
844
+ genReqId: (ctx) =>
845
+ ctx.switchToRpc().getContext<RmqContext>().getMessage()
846
+ .properties.correlationId ?? randomUUID(),
847
+ },
848
+ });
849
+ ```
850
+
597
851
  ## Logging context anywhere else
598
852
 
599
853
  Queue processors, cron jobs, CLI commands, standalone scripts, tests and
@@ -670,9 +924,11 @@ app.useGlobalInterceptors(new LoggerErrorInterceptor());
670
924
 
671
925
  ### v5
672
926
 
673
- - **Requirements changed.** NestJS `11.0.8+` or `12` (11.0.8 is where NestJS
674
- started preserving the `{/...}` route syntax the default middleware route
675
- relies on), `pino@10`, `pino-http@11`, Node.js `>=22.12`. Support for NestJS
927
+ - **Requirements changed.** NestJS `11.0.8+` or `12.0.2+` (11.0.8 is where
928
+ NestJS started preserving the `{/...}` route syntax the default middleware
929
+ route relies on; 12.0.2 is where a microservice pre-request hook stopped
930
+ corrupting a handler's plain return value), `pino@10`, `pino-http@11`,
931
+ Node.js `>=22.12`. Support for NestJS
676
932
  8-10, pino 7-9 and pino-http 6-10 is dropped. `@nestjs/core` is now a peer
677
933
  dependency alongside `@nestjs/common`; every NestJS application already has
678
934
  it installed.
@@ -1,5 +1,5 @@
1
1
  import { Provider } from '@nestjs/common';
2
- import { PinoLogger } from './PinoLogger';
2
+ import { PinoLogger } from './PinoLogger.js';
3
3
  export declare function InjectPinoLogger(context?: string): PropertyDecorator & ParameterDecorator;
4
4
  export declare function createProvidersForDecorated(): Array<Provider<PinoLogger>>;
5
5
  export declare function getLoggerToken(context: string): string;
@@ -4,7 +4,7 @@ exports.InjectPinoLogger = InjectPinoLogger;
4
4
  exports.createProvidersForDecorated = createProvidersForDecorated;
5
5
  exports.getLoggerToken = getLoggerToken;
6
6
  const common_1 = require("@nestjs/common");
7
- const PinoLogger_1 = require("./PinoLogger");
7
+ const PinoLogger_js_1 = require("./PinoLogger.js");
8
8
  const decoratedTokenPrefix = 'PinoLogger:';
9
9
  const decoratedLoggers = new Set();
10
10
  function InjectPinoLogger(context = '') {
@@ -18,7 +18,7 @@ function createDecoratedLoggerProvider(context) {
18
18
  logger.setContext(context);
19
19
  return logger;
20
20
  },
21
- inject: [PinoLogger_1.PinoLogger],
21
+ inject: [PinoLogger_js_1.PinoLogger],
22
22
  };
23
23
  }
24
24
  function createProvidersForDecorated() {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InjectPinoLogger.js","sourceRoot":"","sources":["../../src/InjectPinoLogger.ts"],"names":[],"mappings":";;;;;AAAA,2CAAkD;AAElD,mDAA6C;AAE7C,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAE3C,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;AAE3C,0BAAiC,OAAO,GAAG,EAAE;IAC3C,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC9B,OAAO,IAAA,eAAM,EAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;AACzC,CAAC;AAED,SAAS,6BAA6B,CAAC,OAAe;IACpD,OAAO;QACL,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC;QAChC,UAAU,EAAE,CAAC,MAAkB,EAAE,EAAE;YACjC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;YAC3B,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,MAAM,EAAE,CAAC,0BAAU,CAAC;KACrB,CAAC;AACJ,CAAC;AAED;IACE,OAAO,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;AAC3E,CAAC;AAED,wBAA+B,OAAe;IAC5C,OAAO,GAAG,oBAAoB,GAAG,OAAO,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Inject, Provider } from '@nestjs/common';\n\nimport { PinoLogger } from './PinoLogger.js';\n\nconst decoratedTokenPrefix = 'PinoLogger:';\n\nconst decoratedLoggers = new Set<string>();\n\nexport function InjectPinoLogger(context = '') {\n decoratedLoggers.add(context);\n return Inject(getLoggerToken(context));\n}\n\nfunction createDecoratedLoggerProvider(context: string): Provider<PinoLogger> {\n return {\n provide: getLoggerToken(context),\n useFactory: (logger: PinoLogger) => {\n logger.setContext(context);\n return logger;\n },\n inject: [PinoLogger],\n };\n}\n\nexport function createProvidersForDecorated(): Array<Provider<PinoLogger>> {\n return [...decoratedLoggers.values()].map(createDecoratedLoggerProvider);\n}\n\nexport function getLoggerToken(context: string): string {\n return `${decoratedTokenPrefix}${context}`;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { LoggerService } from '@nestjs/common';
2
- import { PinoLogger } from './PinoLogger';
3
- import { Params } from './params';
2
+ import { PinoLogger } from './PinoLogger.js';
3
+ import { Params } from './params.js';
4
4
  export declare class Logger implements LoggerService {
5
5
  protected readonly logger: PinoLogger;
6
6
  private readonly contextName;
@@ -14,8 +14,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.Logger = void 0;
16
16
  const common_1 = require("@nestjs/common");
17
- const PinoLogger_1 = require("./PinoLogger");
18
- const params_1 = require("./params");
17
+ const PinoLogger_js_1 = require("./PinoLogger.js");
18
+ const params_js_1 = require("./params.js");
19
19
  let Logger = class Logger {
20
20
  logger;
21
21
  contextName;
@@ -97,7 +97,7 @@ let Logger = class Logger {
97
97
  exports.Logger = Logger;
98
98
  exports.Logger = Logger = __decorate([
99
99
  (0, common_1.Injectable)(),
100
- __param(1, (0, common_1.Inject)(params_1.PARAMS_PROVIDER_TOKEN)),
101
- __metadata("design:paramtypes", [PinoLogger_1.PinoLogger, Object])
100
+ __param(1, (0, common_1.Inject)(params_js_1.PARAMS_PROVIDER_TOKEN)),
101
+ __metadata("design:paramtypes", [PinoLogger_js_1.PinoLogger, Object])
102
102
  ], Logger);
103
103
  //# sourceMappingURL=Logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Logger.js","sourceRoot":"","sources":["../../src/Logger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAmE;AAEnE,mDAA6C;AAC7C,2CAA4D;AAGrD,IAAM,MAAM,GAAZ,MAAM,MAAM;IAII,MAAM;IAHV,WAAW,CAAS;IAErC,YACqB,MAAkB,EACN,EAAE,aAAa,EAAU;sBADrC,MAAM;QAGzB,IAAI,CAAC,WAAW,GAAG,aAAa,IAAI,SAAS,CAAC;IAChD,CAAC;IAED,OAAO,CAAC,OAAY,EAAE,GAAG,cAAqB;QAC5C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,OAAY,EAAE,GAAG,cAAqB;QAC1C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACjD,CAAC;IAED,GAAG,CAAC,OAAY,EAAE,GAAG,cAAqB;QACxC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IAChD,CAAC;IAED,IAAI,CAAC,OAAY,EAAE,GAAG,cAAqB;QACzC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,OAAY,EAAE,GAAG,cAAqB;QAC1C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CA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AAO,EAAE,GAAG,MAAM,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACK,gCAAgC,CACtC,KAAY,EACZ,OAAY,EACZ,MAAa;QAEb,OAAO,CACL,KAAK,KAAK,OAAO;YACjB,OAAO,OAAO,KAAK,QAAQ;YAC3B,MAAM,CAAC,MAAM,KAAK,CAAC;YACnB,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,QAAQ;YAC7B,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAC3B,CAAC;IACJ,CAAC;CACF,CAAA;;iBA5FY,MAAM;IADlB,IAAA,mBAAU,GAAE;IAMR,WAAA,IAAA,eAAM,EAAC,iCAAqB,CAAC,CAAA;qCADH,0BAAU;GAJ5B,MAAM,CA4FlB","sourcesContent":["import { Inject, Injectable, LoggerService } from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n@Injectable()\nexport class Logger implements LoggerService {\n private readonly contextName: string;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext }: Params,\n ) {\n this.contextName = renameContext || 'context';\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.call('error', message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n this.call('fatal', message, ...optionalParams);\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const objArg: Record<string, any> = {};\n\n // optionalParams contains extra params passed to logger\n // context name is the last item\n let params: any[] = [];\n if (optionalParams.length !== 0) {\n objArg[this.contextName] = optionalParams[optionalParams.length - 1];\n params = optionalParams.slice(0, -1);\n }\n\n if (typeof message === 'object') {\n if (message instanceof Error) {\n objArg.err = message;\n } else {\n Object.assign(objArg, message);\n }\n this.logger[level](objArg, ...params);\n } else if (this.isWrongExceptionsHandlerContract(level, message, params)) {\n objArg.err = new Error(message);\n objArg.err.stack = params[0];\n this.logger[level](objArg);\n } else {\n this.logger[level](objArg, message, ...params);\n }\n }\n\n /**\n * Unfortunately built-in (not only) `^.*Exception(s?)Handler$` classes call `.error`\n * method with not supported contract:\n *\n * - ExceptionsHandler\n * @see https://github.com/nestjs/nest/blob/35baf7a077bb972469097c5fea2f184b7babadfc/packages/core/exceptions/base-exception-filter.ts#L60-L63\n *\n * - ExceptionHandler\n * @see https://github.com/nestjs/nest/blob/99ee3fd99341bcddfa408d1604050a9571b19bc9/packages/core/errors/exception-handler.ts#L9\n *\n * - WsExceptionsHandler\n * @see https://github.com/nestjs/nest/blob/9d0551ff25c5085703bcebfa7ff3b6952869e794/packages/websockets/exceptions/base-ws-exception-filter.ts#L47-L50\n *\n * - RpcExceptionsHandler @see https://github.com/nestjs/nest/blob/9d0551ff25c5085703bcebfa7ff3b6952869e794/packages/microservices/exceptions/base-rpc-exception-filter.ts#L26-L30\n *\n * - all of them\n * @see https://github.com/search?l=TypeScript&q=org%3Anestjs+logger+error+stack&type=Code\n */\n private isWrongExceptionsHandlerContract(\n level: Level,\n message: any,\n params: any[],\n ): params is [string] {\n return (\n level === 'error' &&\n typeof message === 'string' &&\n params.length === 1 &&\n typeof params[0] === 'string' &&\n /\\n\\s*at /.test(params[0])\n );\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LoggerErrorInterceptor.js","sourceRoot":"","sources":["../../src/LoggerErrorInterceptor.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAKwB;AACxB,+BAA0D;AAGnD,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IACjC,SAAS,CACP,OAAyB,EACzB,IAAiB;QAEjB,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CACvB,IAAA,iBAAU,EAAC,CAAC,KAAK,EAAE,EAAE;YACnB,OAAO,IAAA,iBAAU,EAAC,GAAG,EAAE;gBACrB,MAAM,QAAQ,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,WAAW,EAAE,CAAC;gBAEtD,IAAI,QAAQ,EAAE,CAAC;oBACb,MAAM,iBAAiB,GAAG,QAAQ,CAAC,GAAG,KAAK,SAAS,CAAC;oBAErD,IAAI,iBAAiB,EAAE,CAAC;wBACtB,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,KAAK,CAAC;oBAC3B,CAAC;yBAAM,CAAC;wBACN,QAAQ,CAAC,GAAG,GAAG,KAAK,CAAC;oBACvB,CAAC;gBACH,CAAC;gBAED,OAAO,KAAK,CAAC;YACf,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF,CAAA;;iCAzBY,sBAAsB;IADlC,IAAA,mBAAU,GAAE;GACA,sBAAsB,CAyBlC","sourcesContent":["import {\n type CallHandler,\n type ExecutionContext,\n Injectable,\n type NestInterceptor,\n} from '@nestjs/common';\nimport { catchError, Observable, throwError } from 'rxjs';\n\n@Injectable()\nexport class LoggerErrorInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable<any> | Promise<Observable<any>> {\n return next.handle().pipe(\n catchError((error) => {\n return throwError(() => {\n const response = context.switchToHttp().getResponse();\n\n if (response) {\n const isFastifyResponse = response.raw !== undefined;\n\n if (isFastifyResponse) {\n response.raw.err = error;\n } else {\n response.err = error;\n }\n }\n\n return error;\n });\n }),\n );\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
3
3
  import { ApplicationConfig } from '@nestjs/core';
4
- import { type LoggerModuleAsyncParams, type Params } from './params';
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;
@@ -16,13 +16,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.LoggerModule = void 0;
17
17
  const common_1 = require("@nestjs/common");
18
18
  const core_1 = require("@nestjs/core");
19
- const InjectPinoLogger_1 = require("./InjectPinoLogger");
20
- const Logger_1 = require("./Logger");
21
- const NativeLogger_1 = require("./NativeLogger");
22
- const PinoLogger_1 = require("./PinoLogger");
23
- const params_1 = require("./params");
24
- const rootLogger_1 = require("./rootLogger");
25
- const storage_1 = require("./storage");
19
+ const InjectPinoLogger_js_1 = require("./InjectPinoLogger.js");
20
+ const Logger_js_1 = require("./Logger.js");
21
+ const microservice_js_1 = require("./microservice.js");
22
+ const NativeLogger_js_1 = require("./NativeLogger.js");
23
+ const PinoLogger_js_1 = require("./PinoLogger.js");
24
+ const params_js_1 = require("./params.js");
25
+ const rootLogger_js_1 = require("./rootLogger.js");
26
+ const storage_js_1 = require("./storage.js");
26
27
  /**
27
28
  * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts
28
29
  * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so
@@ -40,47 +41,72 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
40
41
  applicationConfig;
41
42
  static forRoot(params) {
42
43
  const paramsProvider = {
43
- provide: params_1.PARAMS_PROVIDER_TOKEN,
44
+ provide: params_js_1.PARAMS_PROVIDER_TOKEN,
44
45
  useValue: params || {},
45
46
  };
46
- const decorated = (0, InjectPinoLogger_1.createProvidersForDecorated)();
47
+ const decorated = (0, InjectPinoLogger_js_1.createProvidersForDecorated)();
48
+ const hookProvider = createHookProvider();
47
49
  return {
48
50
  module: LoggerModule_1,
49
51
  providers: [
50
- Logger_1.Logger,
51
- NativeLogger_1.NativeLogger,
52
+ Logger_js_1.Logger,
53
+ NativeLogger_js_1.NativeLogger,
52
54
  ...decorated,
53
- PinoLogger_1.PinoLogger,
55
+ PinoLogger_js_1.PinoLogger,
54
56
  paramsProvider,
57
+ hookProvider,
58
+ ],
59
+ exports: [
60
+ Logger_js_1.Logger,
61
+ NativeLogger_js_1.NativeLogger,
62
+ ...decorated,
63
+ PinoLogger_js_1.PinoLogger,
64
+ paramsProvider,
65
+ hookProvider,
55
66
  ],
56
- exports: [Logger_1.Logger, NativeLogger_1.NativeLogger, ...decorated, PinoLogger_1.PinoLogger, paramsProvider],
57
67
  };
58
68
  }
59
69
  static forRootAsync(params) {
60
70
  const paramsProvider = {
61
- provide: params_1.PARAMS_PROVIDER_TOKEN,
71
+ provide: params_js_1.PARAMS_PROVIDER_TOKEN,
62
72
  useFactory: params.useFactory,
63
73
  inject: params.inject,
64
74
  };
65
- const decorated = (0, InjectPinoLogger_1.createProvidersForDecorated)();
75
+ const decorated = (0, InjectPinoLogger_js_1.createProvidersForDecorated)();
76
+ const hookProvider = createHookProvider();
66
77
  const providers = [
67
- Logger_1.Logger,
68
- NativeLogger_1.NativeLogger,
78
+ Logger_js_1.Logger,
79
+ NativeLogger_js_1.NativeLogger,
69
80
  ...decorated,
70
- PinoLogger_1.PinoLogger,
81
+ PinoLogger_js_1.PinoLogger,
71
82
  paramsProvider,
83
+ hookProvider,
72
84
  ...(params.providers || []),
73
85
  ];
74
86
  return {
75
87
  module: LoggerModule_1,
76
88
  imports: params.imports,
77
89
  providers,
78
- exports: [Logger_1.Logger, NativeLogger_1.NativeLogger, ...decorated, PinoLogger_1.PinoLogger, paramsProvider],
90
+ exports: [
91
+ Logger_js_1.Logger,
92
+ NativeLogger_js_1.NativeLogger,
93
+ ...decorated,
94
+ PinoLogger_js_1.PinoLogger,
95
+ paramsProvider,
96
+ hookProvider,
97
+ ],
79
98
  };
80
99
  }
81
100
  constructor(params, applicationConfig) {
82
101
  this.params = params;
83
102
  this.applicationConfig = applicationConfig;
103
+ // Microservices have no middleware, so `configure` is never called for
104
+ // them. The hook is registered here instead, early enough that the message
105
+ // handlers being built later pick it up.
106
+ if (params.microservice) {
107
+ (0, rootLogger_js_1.ensureRootLogger)(params.pinoHttp);
108
+ (0, microservice_js_1.registerMicroserviceHook)(applicationConfig, params);
109
+ }
84
110
  }
85
111
  configure(consumer) {
86
112
  const { exclude, forRoutes = this.defaultRoutes(), pinoHttp, useExisting, assignResponse, } = this.params;
@@ -118,10 +144,24 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
118
144
  exports.LoggerModule = LoggerModule;
119
145
  exports.LoggerModule = LoggerModule = LoggerModule_1 = __decorate([
120
146
  (0, common_1.Global)(),
121
- (0, common_1.Module)({ providers: [Logger_1.Logger, NativeLogger_1.NativeLogger], exports: [Logger_1.Logger, NativeLogger_1.NativeLogger] }),
122
- __param(0, (0, common_1.Inject)(params_1.PARAMS_PROVIDER_TOKEN)),
147
+ (0, common_1.Module)({ providers: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger], exports: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger] }),
148
+ __param(0, (0, common_1.Inject)(params_js_1.PARAMS_PROVIDER_TOKEN)),
123
149
  __metadata("design:paramtypes", [Object, core_1.ApplicationConfig])
124
150
  ], LoggerModule);
151
+ /**
152
+ * Exposes the very hook the module registers on its own, for the one case it
153
+ * cannot reach: a hybrid application connected without `inheritAppConfig`.
154
+ */
155
+ function createHookProvider() {
156
+ return {
157
+ provide: microservice_js_1.PINO_PRE_REQUEST_HOOK,
158
+ useFactory: (params) => {
159
+ (0, rootLogger_js_1.ensureRootLogger)(params.pinoHttp);
160
+ return (0, microservice_js_1.getMicroserviceHook)(params);
161
+ },
162
+ inject: [params_js_1.PARAMS_PROVIDER_TOKEN],
163
+ };
164
+ }
125
165
  function createLoggerMiddlewares(params, useExisting = false, assignResponse = false) {
126
166
  if (useExisting) {
127
167
  return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];
@@ -129,10 +169,10 @@ function createLoggerMiddlewares(params, useExisting = false, assignResponse = f
129
169
  // The same instance the rest of the application already logs through, rather
130
170
  // than a second one built here: one `transport`, and a `PinoLogger.root` that
131
171
  // governs every log in the application, request-scoped or not.
132
- const middleware = (0, rootLogger_1.ensureLoggerMiddleware)(params);
172
+ const middleware = (0, rootLogger_js_1.ensureLoggerMiddleware)(params);
133
173
  // @ts-expect-error: root is readonly field, but this is the place where
134
174
  // it's set actually
135
- PinoLogger_1.PinoLogger.root = middleware.logger;
175
+ PinoLogger_js_1.PinoLogger.root = middleware.logger;
136
176
  return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];
137
177
  }
138
178
  function bindLoggerMiddlewareFactory(useExisting, assignResponse) {
@@ -145,7 +185,7 @@ function bindLoggerMiddlewareFactory(useExisting, assignResponse) {
145
185
  if (assignResponse && !useExisting && res.allLogs) {
146
186
  resLog = res.allLogs[res.allLogs.length - 1];
147
187
  }
148
- storage_1.storage.run(new storage_1.Store(log, resLog), next);
188
+ storage_js_1.storage.run(new storage_js_1.Store(log, resLog), next);
149
189
  };
150
190
  }
151
191
  //# sourceMappingURL=LoggerModule.js.map
@@ -0,0 +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,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AC,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 } 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,6 +1,6 @@
1
1
  import { type LoggerService } from '@nestjs/common';
2
- import { PinoLogger } from './PinoLogger';
3
- import { Params } from './params';
2
+ import { PinoLogger } from './PinoLogger.js';
3
+ import { Params } from './params.js';
4
4
  export declare class NativeLogger implements LoggerService {
5
5
  protected readonly logger: PinoLogger;
6
6
  private readonly contextName;
@@ -14,8 +14,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.NativeLogger = void 0;
16
16
  const common_1 = require("@nestjs/common");
17
- const PinoLogger_1 = require("./PinoLogger");
18
- const params_1 = require("./params");
17
+ const PinoLogger_js_1 = require("./PinoLogger.js");
18
+ const params_js_1 = require("./params.js");
19
19
  /**
20
20
  * NestJS v12 collects plain objects passed after the message into a single
21
21
  * `params` field instead of logging each of them as its own entry
@@ -193,7 +193,7 @@ let NativeLogger = class NativeLogger {
193
193
  exports.NativeLogger = NativeLogger;
194
194
  exports.NativeLogger = NativeLogger = __decorate([
195
195
  (0, common_1.Injectable)(),
196
- __param(1, (0, common_1.Inject)(params_1.PARAMS_PROVIDER_TOKEN)),
197
- __metadata("design:paramtypes", [PinoLogger_1.PinoLogger, Object])
196
+ __param(1, (0, common_1.Inject)(params_js_1.PARAMS_PROVIDER_TOKEN)),
197
+ __metadata("design:paramtypes", [PinoLogger_js_1.PinoLogger, Object])
198
198
  ], NativeLogger);
199
199
  //# sourceMappingURL=NativeLogger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NativeLogger.js","sourceRoot":"","sources":["../../src/NativeLogger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I,CAAC,CAAC;QAC1C,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YACzB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,WAAW,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAClD,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;YAC1E,OAAO;gBACL,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;gBAChD,OAAO;gBACP,MAAM;aACP,CAAC;QACJ,CAAC;QACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;IAEO,aAAa,CAAC,KAAc;QAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,yBAAyB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5E,CAAC;CACF,CAAA;;uBA3LY,YAAY;IADxB,IAAA,mBAAU,GAAE;IAQR,WAAA,IAAA,eAAM,EAAC,iCAAqB,CAAC,CAAA;qCADH,0BAAU;GAN5B,YAAY,CA2LxB","sourcesContent":["import {\n ConsoleLogger,\n Inject,\n Injectable,\n type LoggerService,\n} from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n/**\n * NestJS v12 collects plain objects passed after the message into a single\n * `params` field instead of logging each of them as its own entry\n * (`ConsoleLoggerOptions.structuredParams`, on by default). NativeLogger exists\n * to match whichever `ConsoleLogger` the application actually has, so detect\n * the capability rather than the version: `stringifyParams` is the method v12\n * added for exactly this, and NestJS exposes no version at runtime.\n *\n * This only decides the *default*; the collecting itself is implemented here\n * and works on every supported NestJS version when asked for explicitly.\n */\nconst HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;\n\n/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */\nfunction isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto === null) {\n return true;\n }\n const ctor =\n Object.hasOwn(proto, 'constructor') &&\n (proto as { constructor: unknown }).constructor;\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n );\n}\n\n@Injectable()\nexport class NativeLogger implements LoggerService {\n private readonly contextName: string;\n private readonly structuredParams: boolean;\n private readonly flattenParams: boolean;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext, nativeLogger }: Params,\n ) {\n this.contextName = renameContext || 'context';\n this.structuredParams =\n nativeLogger?.structuredParams ?? HAS_STRUCTURED_PARAMS;\n this.flattenParams = nativeLogger?.flattenParams ?? false;\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.callError(message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n this.call('fatal', message, ...optionalParams);\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage(level, msg, context, undefined, params);\n }\n }\n\n private callError(message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, stack, params } =\n this.getContextAndStackAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage('error', msg, context, stack, params);\n }\n }\n\n private logSingleMessage(\n level: Level,\n message: unknown,\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n ) {\n // Flattened params go in first so that this logger's own fields win on a\n // key collision. Collisions with pino's fields (the level, the timestamp,\n // the message key, the base bindings) are not handled: pino does not\n // deduplicate keys either, and their names depend on the pino options, so\n // any guard here would be guesswork.\n const objArg: Record<string, any> =\n params && this.flattenParams ? { ...params } : {};\n\n if (context) {\n objArg[this.contextName] = context;\n }\n\n if (stack) {\n objArg.stack = stack;\n }\n\n if (params && !this.flattenParams) {\n objArg.params = params;\n }\n\n if (typeof message === 'object' && message !== null) {\n if (message instanceof Error) {\n this.logger[level](objArg, message.stack || message.message);\n } else {\n this.logger[level](objArg, message as unknown as string);\n }\n } else {\n this.logger[level](objArg, String(message));\n }\n }\n\n private getContextAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n params?: Record<string, any>;\n } {\n if (args.length <= 1) {\n return { messages: args, context: undefined };\n }\n const lastElement = args[args.length - 1];\n const isContext = typeof lastElement === 'string';\n const context = isContext ? lastElement : undefined;\n const remainingArgs = isContext ? args.slice(0, args.length - 1) : args;\n\n if (!this.structuredParams) {\n return { messages: remainingArgs, context };\n }\n\n // The first argument is always the message; only plain objects after it\n // become params, everything else stays a message of its own.\n const messages: unknown[] = [remainingArgs[0]];\n const paramObjects: Record<string, any>[] = [];\n for (const arg of remainingArgs.slice(1)) {\n if (isPlainObject(arg)) {\n paramObjects.push(arg as Record<string, any>);\n } else {\n messages.push(arg);\n }\n }\n\n return {\n messages,\n context,\n params: paramObjects.length\n ? Object.assign({}, ...paramObjects)\n : undefined,\n };\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n stack?: string;\n params?: Record<string, any>;\n } {\n if (args.length === 2) {\n if (this.isStackFormat(args[1])) {\n return {\n messages: [args[0]],\n stack: args[1] as string,\n context: undefined,\n };\n }\n if (typeof args[1] === 'string') {\n return {\n messages: [args[0]],\n context: args[1],\n };\n }\n }\n\n const trailingArg = args[args.length - 1];\n if (args.length > 2 && this.isStackFormat(trailingArg)) {\n const { messages, context, params } = this.getContextAndMessagesToPrint(\n args.slice(0, -1),\n );\n return { messages, context, stack: trailingArg as string, params };\n }\n\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n if (messages.length <= 1) {\n return { messages, context, params };\n }\n\n const lastMessage = messages[messages.length - 1];\n if (typeof lastMessage === 'string' || typeof lastMessage === 'undefined') {\n return {\n stack: lastMessage,\n messages: messages.slice(0, messages.length - 1),\n context,\n params,\n };\n }\n return { messages, context, params };\n }\n\n private isStackFormat(value: unknown): boolean {\n if (typeof value !== 'string' && typeof value !== 'undefined') {\n return false;\n }\n return typeof value === 'string' && /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(value);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import pino from 'pino';
2
- import { Params } from './params';
2
+ import { Params } from './params.js';
3
3
  type PinoMethods<CustomLevels extends string = never> = Pick<pino.Logger<CustomLevels>, 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'>;
4
4
  /**
5
5
  * This is copy of pino.LogFn but with possibilty to make method override.