nestjs-pino 5.1.0 → 5.2.0
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 +260 -4
- package/dist/LoggerModule.js +42 -2
- package/dist/LoggerModule.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/microservice.d.ts +47 -0
- package/dist/microservice.js +201 -0
- package/dist/microservice.js.map +1 -0
- package/dist/params.d.ts +128 -3
- package/dist/params.js.map +1 -1
- package/dist/rpc.d.ts +35 -0
- package/dist/rpc.js +104 -0
- package/dist/rpc.js.map +1 -0
- package/package.json +11 -10
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
|
|
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
|
|
674
|
-
started preserving the `{/...}` route syntax the default middleware
|
|
675
|
-
relies on
|
|
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.
|
package/dist/LoggerModule.js
CHANGED
|
@@ -18,6 +18,7 @@ const common_1 = require("@nestjs/common");
|
|
|
18
18
|
const core_1 = require("@nestjs/core");
|
|
19
19
|
const InjectPinoLogger_1 = require("./InjectPinoLogger");
|
|
20
20
|
const Logger_1 = require("./Logger");
|
|
21
|
+
const microservice_1 = require("./microservice");
|
|
21
22
|
const NativeLogger_1 = require("./NativeLogger");
|
|
22
23
|
const PinoLogger_1 = require("./PinoLogger");
|
|
23
24
|
const params_1 = require("./params");
|
|
@@ -44,6 +45,7 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
44
45
|
useValue: params || {},
|
|
45
46
|
};
|
|
46
47
|
const decorated = (0, InjectPinoLogger_1.createProvidersForDecorated)();
|
|
48
|
+
const hookProvider = createHookProvider();
|
|
47
49
|
return {
|
|
48
50
|
module: LoggerModule_1,
|
|
49
51
|
providers: [
|
|
@@ -52,8 +54,16 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
52
54
|
...decorated,
|
|
53
55
|
PinoLogger_1.PinoLogger,
|
|
54
56
|
paramsProvider,
|
|
57
|
+
hookProvider,
|
|
58
|
+
],
|
|
59
|
+
exports: [
|
|
60
|
+
Logger_1.Logger,
|
|
61
|
+
NativeLogger_1.NativeLogger,
|
|
62
|
+
...decorated,
|
|
63
|
+
PinoLogger_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) {
|
|
@@ -63,24 +73,40 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
63
73
|
inject: params.inject,
|
|
64
74
|
};
|
|
65
75
|
const decorated = (0, InjectPinoLogger_1.createProvidersForDecorated)();
|
|
76
|
+
const hookProvider = createHookProvider();
|
|
66
77
|
const providers = [
|
|
67
78
|
Logger_1.Logger,
|
|
68
79
|
NativeLogger_1.NativeLogger,
|
|
69
80
|
...decorated,
|
|
70
81
|
PinoLogger_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: [
|
|
90
|
+
exports: [
|
|
91
|
+
Logger_1.Logger,
|
|
92
|
+
NativeLogger_1.NativeLogger,
|
|
93
|
+
...decorated,
|
|
94
|
+
PinoLogger_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_1.ensureRootLogger)(params.pinoHttp);
|
|
108
|
+
(0, microservice_1.registerMicroserviceHook)(applicationConfig, params);
|
|
109
|
+
}
|
|
84
110
|
}
|
|
85
111
|
configure(consumer) {
|
|
86
112
|
const { exclude, forRoutes = this.defaultRoutes(), pinoHttp, useExisting, assignResponse, } = this.params;
|
|
@@ -122,6 +148,20 @@ exports.LoggerModule = LoggerModule = LoggerModule_1 = __decorate([
|
|
|
122
148
|
__param(0, (0, common_1.Inject)(params_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_1.PINO_PRE_REQUEST_HOOK,
|
|
158
|
+
useFactory: (params) => {
|
|
159
|
+
(0, rootLogger_1.ensureRootLogger)(params.pinoHttp);
|
|
160
|
+
return (0, microservice_1.getMicroserviceHook)(params);
|
|
161
|
+
},
|
|
162
|
+
inject: [params_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)];
|
package/dist/LoggerModule.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAiD;AAEjD,yDAAiE;AACjE,qCAAkC;AAClC,iDAA8C;AAC9C,6CAA0C;AAC1C,qCAIkB;AAClB,6CAAsD;AACtD,uCAA2C;AAE3C;;;;;;;;;;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;IA2D2B,MAAM;IACrC,iBAAiB;IA3D7B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,8BAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;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ACpB,uBAAU,CAAC,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC;IAEpC,OAAO,CAAC,UAAU,EAAE,2BAA2B,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,2BAA2B,CAClC,WAAoB,EACpB,cAAuB;IAEvB,OAAO,SAAS,oBAAoB,CAClC,GAAoB,EACpB,GAAmB,EACnB,IAAgB;QAEhB,IAAI,GAAG,GAAG,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,iBAAO,CAAC,GAAG,CAAC,IAAI,eAAK,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';\nimport { Logger } from './Logger';\nimport { NativeLogger } from './NativeLogger';\nimport { PinoLogger } from './PinoLogger';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params';\nimport { ensureLoggerMiddleware } from './rootLogger';\nimport { Store, storage } from './storage';\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\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ],\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\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\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\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\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,uCAAiD;AAEjD,yDAAiE;AACjE,qCAAkC;AAClC,iDAIwB;AACxB,iDAA8C;AAC9C,6CAA0C;AAC1C,qCAIkB;AAClB,6CAAwE;AACxE,uCAA2C;AAE3C;;;;;;;;;;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,8BAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,IAAA,8CAA2B,GAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;QAE1C,OAAO;YACL,MAAM,gBAAc;YACpB,SAAS,EAAE;gBACT,eAAM;gBACN,2BAAY;gBACZ,GAAG,SAAS;gBACZ,uBAAU;gBACV,cAAc;gBACd,YAAY;aACb;YACD,OAAO,EAAE;gBACP,eAAM;gBACN,2BAAY;gBACZ,GAAG,SAAS;gBACZ,uBAAU;gBACV,cAAc;gBACd,YAAY;aACb;SACF,CAAC;IACJ,CAAC;IAEM,AAAP,MAAM,CAAC,YAAY,CAIjB,MAAqD;QACrD,MAAM,cAAc,GAEhB;YACF,OAAO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AAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,6EAA6E;IAC7E,8EAA8E;IAC9E,+DAA+D;IAC/D,MAAM,UAAU,GAAG,IAAA,mCAAsB,EAAC,MAAM,CAAC,CAAC;IAElD,wEAAwE;IACxE,oBAAoB;IACpB,uBAAU,CAAC,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC;IAEpC,OAAO,CAAC,UAAU,EAAE,2BAA2B,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,2BAA2B,CAClC,WAAoB,EACpB,cAAuB;IAEvB,OAAO,SAAS,oBAAoB,CAClC,GAAoB,EACpB,GAAmB,EACnB,IAAgB;QAEhB,IAAI,GAAG,GAAG,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,iBAAO,CAAC,GAAG,CAAC,IAAI,eAAK,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';\nimport { Logger } from './Logger';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice';\nimport { NativeLogger } from './NativeLogger';\nimport { PinoLogger } from './PinoLogger';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger';\nimport { Store, storage } from './storage';\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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,9 @@ export { getLoggerToken, InjectPinoLogger } from './InjectPinoLogger';
|
|
|
2
2
|
export { Logger } from './Logger';
|
|
3
3
|
export { LoggerErrorInterceptor } from './LoggerErrorInterceptor';
|
|
4
4
|
export { LoggerModule } from './LoggerModule';
|
|
5
|
+
export { PINO_PRE_REQUEST_HOOK, type PreRequestHook, registerMicroserviceLogging, } from './microservice';
|
|
5
6
|
export { NativeLogger } from './NativeLogger';
|
|
6
7
|
export { PinoLogger, type RunInContextOptions } from './PinoLogger';
|
|
7
|
-
export { LoggerModuleAsyncParams, PARAMS_PROVIDER_TOKEN, Params, } from './params';
|
|
8
|
+
export { LoggerModuleAsyncParams, MicroserviceParams, PARAMS_PROVIDER_TOKEN, Params, } from './params';
|
|
8
9
|
export { nativeLoggerOptions } from './presets';
|
|
10
|
+
export { getRpcInfo, type RpcInfo, type RpcType } from './rpc';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.nativeLoggerOptions = exports.PARAMS_PROVIDER_TOKEN = exports.PinoLogger = exports.NativeLogger = exports.LoggerModule = exports.LoggerErrorInterceptor = exports.Logger = exports.InjectPinoLogger = exports.getLoggerToken = void 0;
|
|
3
|
+
exports.getRpcInfo = exports.nativeLoggerOptions = exports.PARAMS_PROVIDER_TOKEN = exports.PinoLogger = exports.NativeLogger = exports.registerMicroserviceLogging = exports.PINO_PRE_REQUEST_HOOK = exports.LoggerModule = exports.LoggerErrorInterceptor = exports.Logger = exports.InjectPinoLogger = exports.getLoggerToken = void 0;
|
|
4
4
|
var InjectPinoLogger_1 = require("./InjectPinoLogger");
|
|
5
5
|
Object.defineProperty(exports, "getLoggerToken", { enumerable: true, get: function () { return InjectPinoLogger_1.getLoggerToken; } });
|
|
6
6
|
Object.defineProperty(exports, "InjectPinoLogger", { enumerable: true, get: function () { return InjectPinoLogger_1.InjectPinoLogger; } });
|
|
@@ -10,6 +10,9 @@ var LoggerErrorInterceptor_1 = require("./LoggerErrorInterceptor");
|
|
|
10
10
|
Object.defineProperty(exports, "LoggerErrorInterceptor", { enumerable: true, get: function () { return LoggerErrorInterceptor_1.LoggerErrorInterceptor; } });
|
|
11
11
|
var LoggerModule_1 = require("./LoggerModule");
|
|
12
12
|
Object.defineProperty(exports, "LoggerModule", { enumerable: true, get: function () { return LoggerModule_1.LoggerModule; } });
|
|
13
|
+
var microservice_1 = require("./microservice");
|
|
14
|
+
Object.defineProperty(exports, "PINO_PRE_REQUEST_HOOK", { enumerable: true, get: function () { return microservice_1.PINO_PRE_REQUEST_HOOK; } });
|
|
15
|
+
Object.defineProperty(exports, "registerMicroserviceLogging", { enumerable: true, get: function () { return microservice_1.registerMicroserviceLogging; } });
|
|
13
16
|
var NativeLogger_1 = require("./NativeLogger");
|
|
14
17
|
Object.defineProperty(exports, "NativeLogger", { enumerable: true, get: function () { return NativeLogger_1.NativeLogger; } });
|
|
15
18
|
var PinoLogger_1 = require("./PinoLogger");
|
|
@@ -18,4 +21,6 @@ var params_1 = require("./params");
|
|
|
18
21
|
Object.defineProperty(exports, "PARAMS_PROVIDER_TOKEN", { enumerable: true, get: function () { return params_1.PARAMS_PROVIDER_TOKEN; } });
|
|
19
22
|
var presets_1 = require("./presets");
|
|
20
23
|
Object.defineProperty(exports, "nativeLoggerOptions", { enumerable: true, get: function () { return presets_1.nativeLoggerOptions; } });
|
|
24
|
+
var rpc_1 = require("./rpc");
|
|
25
|
+
Object.defineProperty(exports, "getRpcInfo", { enumerable: true, get: function () { return rpc_1.getRpcInfo; } });
|
|
21
26
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAsE;AAA7D,kHAAA,cAAc,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACzC,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AACf,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,2CAAoE;AAA3D,wGAAA,UAAU,OAAA;AACnB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAsE;AAA7D,kHAAA,cAAc,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACzC,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AACf,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,+CAIwB;AAHtB,qHAAA,qBAAqB,OAAA;AAErB,2HAAA,2BAA2B,OAAA;AAE7B,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,2CAAoE;AAA3D,wGAAA,UAAU,OAAA;AACnB,mCAKkB;AAFhB,+GAAA,qBAAqB,OAAA;AAGvB,qCAAgD;AAAvC,8GAAA,mBAAmB,OAAA;AAC5B,6BAA+D;AAAtD,iGAAA,UAAU,OAAA","sourcesContent":["export { getLoggerToken, InjectPinoLogger } from './InjectPinoLogger';\nexport { Logger } from './Logger';\nexport { LoggerErrorInterceptor } from './LoggerErrorInterceptor';\nexport { LoggerModule } from './LoggerModule';\nexport {\n PINO_PRE_REQUEST_HOOK,\n type PreRequestHook,\n registerMicroserviceLogging,\n} from './microservice';\nexport { NativeLogger } from './NativeLogger';\nexport { PinoLogger, type RunInContextOptions } from './PinoLogger';\nexport {\n LoggerModuleAsyncParams,\n MicroserviceParams,\n PARAMS_PROVIDER_TOKEN,\n Params,\n} from './params';\nexport { nativeLoggerOptions } from './presets';\nexport { getRpcInfo, type RpcInfo, type RpcType } from './rpc';\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
import { Params } from './params';
|
|
4
|
+
/**
|
|
5
|
+
* Structurally identical to `PreRequestHook` from `@nestjs/common`, which only
|
|
6
|
+
* exists in NestJS 12. Declared here rather than imported so that type checking
|
|
7
|
+
* still passes against the NestJS 11 the package also supports.
|
|
8
|
+
*/
|
|
9
|
+
export type PreRequestHook = (context: ExecutionContext, next: () => Observable<unknown>) => Observable<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* Injection token of the pre-request hook that does the microservice logging.
|
|
12
|
+
*
|
|
13
|
+
* Prefer {@link registerMicroserviceLogging}, which registers this and
|
|
14
|
+
* everything else the hook needs. This token is the low-level way in, for an
|
|
15
|
+
* application that wires its microservice up by hand.
|
|
16
|
+
*/
|
|
17
|
+
export declare const PINO_PRE_REQUEST_HOOK = "pino-pre-request-hook";
|
|
18
|
+
type HookParams = Pick<Params<any, any, any>, 'microservice' | 'assignResponse'>;
|
|
19
|
+
export declare function getMicroserviceHook(params: HookParams): PreRequestHook;
|
|
20
|
+
/**
|
|
21
|
+
* Registers the hook on the `ApplicationConfig` the microservice will read it
|
|
22
|
+
* from. Returns whether the running NestJS supports pre-request hooks at all.
|
|
23
|
+
*/
|
|
24
|
+
export declare function registerMicroserviceHook(applicationConfig: unknown, params: HookParams): boolean;
|
|
25
|
+
/** The subset of `INestMicroservice` {@link registerMicroserviceLogging} needs. */
|
|
26
|
+
interface MicroserviceApp {
|
|
27
|
+
get(token: unknown, options?: unknown): unknown;
|
|
28
|
+
/** Optional so that a call still type checks against NestJS 11. */
|
|
29
|
+
registerPreRequestHook?(...hooks: PreRequestHook[]): unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Sets up microservice logging on a microservice NestJS could not hand the hook
|
|
33
|
+
* to by itself — a hybrid application connected without
|
|
34
|
+
* `{ inheritAppConfig: true }`, which gets an `ApplicationConfig` of its own
|
|
35
|
+
* that dependency injection cannot reach:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* const ms = app.connectMicroservice(options, { deferInitialization: true });
|
|
39
|
+
* registerMicroserviceLogging(ms);
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* Must be called before the microservice starts listening, and the module still
|
|
43
|
+
* needs `microservice` in its parameters for the options to apply. On NestJS 11
|
|
44
|
+
* this warns and does nothing, like the parameter itself.
|
|
45
|
+
*/
|
|
46
|
+
export declare function registerMicroserviceLogging(app: MicroserviceApp): void;
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PINO_PRE_REQUEST_HOOK = void 0;
|
|
4
|
+
exports.getMicroserviceHook = getMicroserviceHook;
|
|
5
|
+
exports.registerMicroserviceHook = registerMicroserviceHook;
|
|
6
|
+
exports.registerMicroserviceLogging = registerMicroserviceLogging;
|
|
7
|
+
const common_1 = require("@nestjs/common");
|
|
8
|
+
const rxjs_1 = require("rxjs");
|
|
9
|
+
const rootLogger_1 = require("./rootLogger");
|
|
10
|
+
const rpc_1 = require("./rpc");
|
|
11
|
+
const storage_1 = require("./storage");
|
|
12
|
+
/**
|
|
13
|
+
* Injection token of the pre-request hook that does the microservice logging.
|
|
14
|
+
*
|
|
15
|
+
* Prefer {@link registerMicroserviceLogging}, which registers this and
|
|
16
|
+
* everything else the hook needs. This token is the low-level way in, for an
|
|
17
|
+
* application that wires its microservice up by hand.
|
|
18
|
+
*/
|
|
19
|
+
exports.PINO_PRE_REQUEST_HOOK = 'pino-pre-request-hook';
|
|
20
|
+
// One hook per set of parameters, so that the automatically registered hook and
|
|
21
|
+
// the one behind `PINO_PRE_REQUEST_HOOK` are the same function. Registering the
|
|
22
|
+
// same hook twice would log every message twice.
|
|
23
|
+
const hooks = new WeakMap();
|
|
24
|
+
function getMicroserviceHook(params) {
|
|
25
|
+
let hook = hooks.get(params);
|
|
26
|
+
if (!hook) {
|
|
27
|
+
hook = createMicroserviceHook(params);
|
|
28
|
+
hooks.set(params, hook);
|
|
29
|
+
}
|
|
30
|
+
return hook;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Registers the hook on the `ApplicationConfig` the microservice will read it
|
|
34
|
+
* from. Returns whether the running NestJS supports pre-request hooks at all.
|
|
35
|
+
*/
|
|
36
|
+
function registerMicroserviceHook(applicationConfig, params) {
|
|
37
|
+
const registry = applicationConfig;
|
|
38
|
+
if (typeof registry.registerPreRequestHook !== 'function') {
|
|
39
|
+
warnNoPreRequestHooks();
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const hook = getMicroserviceHook(params);
|
|
43
|
+
if (registry.getGlobalPreRequestHooks?.().includes(hook)) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
registry.registerPreRequestHook(hook);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
function warnNoPreRequestHooks() {
|
|
50
|
+
new common_1.Logger('LoggerModule').warn('Microservice logging needs the pre-request hooks introduced in NestJS ' +
|
|
51
|
+
'12, so microservice messages will be logged without a logging ' +
|
|
52
|
+
'context. Everything else is unaffected.');
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Sets up microservice logging on a microservice NestJS could not hand the hook
|
|
56
|
+
* to by itself — a hybrid application connected without
|
|
57
|
+
* `{ inheritAppConfig: true }`, which gets an `ApplicationConfig` of its own
|
|
58
|
+
* that dependency injection cannot reach:
|
|
59
|
+
*
|
|
60
|
+
* ```ts
|
|
61
|
+
* const ms = app.connectMicroservice(options, { deferInitialization: true });
|
|
62
|
+
* registerMicroserviceLogging(ms);
|
|
63
|
+
* ```
|
|
64
|
+
*
|
|
65
|
+
* Must be called before the microservice starts listening, and the module still
|
|
66
|
+
* needs `microservice` in its parameters for the options to apply. On NestJS 11
|
|
67
|
+
* this warns and does nothing, like the parameter itself.
|
|
68
|
+
*/
|
|
69
|
+
function registerMicroserviceLogging(app) {
|
|
70
|
+
if (typeof app.registerPreRequestHook !== 'function') {
|
|
71
|
+
warnNoPreRequestHooks();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
app.registerPreRequestHook(app.get(exports.PINO_PRE_REQUEST_HOOK));
|
|
75
|
+
}
|
|
76
|
+
function defaultGenReqId() {
|
|
77
|
+
let id = 0;
|
|
78
|
+
return () => ++id;
|
|
79
|
+
}
|
|
80
|
+
function createMicroserviceHook(params) {
|
|
81
|
+
const options = typeof params.microservice === 'object' ? params.microservice : {};
|
|
82
|
+
if (options.useLevel && options.customLogLevel) {
|
|
83
|
+
throw new Error("You can't pass 'useLevel' and 'customLogLevel' together in `microservice`");
|
|
84
|
+
}
|
|
85
|
+
const keys = options.customAttributeKeys ?? {};
|
|
86
|
+
const rpcKey = keys.rpc ?? 'rpc';
|
|
87
|
+
const errKey = keys.err ?? 'err';
|
|
88
|
+
const reqIdKey = keys.reqId ?? 'reqId';
|
|
89
|
+
const responseTimeKey = keys.responseTime ?? 'responseTime';
|
|
90
|
+
const useLevel = options.useLevel ?? 'info';
|
|
91
|
+
const customLogLevel = options.customLogLevel;
|
|
92
|
+
const autoLogging = options.autoLogging !== false;
|
|
93
|
+
const ignore = typeof options.autoLogging === 'object'
|
|
94
|
+
? options.autoLogging.ignore
|
|
95
|
+
: undefined;
|
|
96
|
+
const genReqId = options.genReqId ?? defaultGenReqId();
|
|
97
|
+
const assignResponse = !!params.assignResponse;
|
|
98
|
+
const { customProps, customReceivedMessage, customReceivedObject, customSuccessMessage, customSuccessObject, customErrorMessage, customErrorObject, includePayload, quietRpcLogger, quietResLogger, } = options;
|
|
99
|
+
const logsOnArrival = !!customReceivedMessage || !!customReceivedObject;
|
|
100
|
+
function levelFor(context, error) {
|
|
101
|
+
if (customLogLevel) {
|
|
102
|
+
return customLogLevel(context, error);
|
|
103
|
+
}
|
|
104
|
+
// `pino-http` logs a failed request at `useLevel` too; errors here default
|
|
105
|
+
// to `error` instead, because `useLevel` is routinely lowered to quiet down
|
|
106
|
+
// chatty events and that must not also hide failures. The hook sees the
|
|
107
|
+
// error before any `@Catch()` filter, so an `RpcException` thrown on
|
|
108
|
+
// purpose reaches this as well — `customLogLevel` is the way out.
|
|
109
|
+
return error ? 'error' : useLevel;
|
|
110
|
+
}
|
|
111
|
+
function buildRecord(context, info) {
|
|
112
|
+
const record = {
|
|
113
|
+
type: info.type,
|
|
114
|
+
pattern: info.pattern,
|
|
115
|
+
transport: info.transport,
|
|
116
|
+
controller: info.controller,
|
|
117
|
+
handler: info.handler,
|
|
118
|
+
};
|
|
119
|
+
if (includePayload) {
|
|
120
|
+
record.payload = context.switchToRpc().getData();
|
|
121
|
+
}
|
|
122
|
+
return record;
|
|
123
|
+
}
|
|
124
|
+
return (context, next) => new rxjs_1.Observable((subscriber) => {
|
|
125
|
+
const base = (0, rootLogger_1.getRootLogger)();
|
|
126
|
+
// Only reachable if the hook runs before any `PinoLogger` was built,
|
|
127
|
+
// which the module's own ordering rules out. Log nothing rather than
|
|
128
|
+
// break the message.
|
|
129
|
+
if (!base) {
|
|
130
|
+
return next().subscribe(subscriber);
|
|
131
|
+
}
|
|
132
|
+
const info = (0, rpc_1.getRpcInfo)(context);
|
|
133
|
+
const quiet = base.child({ [reqIdKey]: genReqId(context) });
|
|
134
|
+
let full = quiet.child({
|
|
135
|
+
[rpcKey]: buildRecord(context, info),
|
|
136
|
+
});
|
|
137
|
+
const props = customProps?.(context);
|
|
138
|
+
if (props) {
|
|
139
|
+
full = full.child(props);
|
|
140
|
+
}
|
|
141
|
+
const contextLogger = quietRpcLogger ? quiet : full;
|
|
142
|
+
const closingLogger = quietResLogger ? quiet : full;
|
|
143
|
+
const skip = !autoLogging || (ignore?.(context) ?? false);
|
|
144
|
+
const start = Date.now();
|
|
145
|
+
let result;
|
|
146
|
+
function logCompleted() {
|
|
147
|
+
const level = levelFor(context, undefined);
|
|
148
|
+
if (level === 'silent')
|
|
149
|
+
return;
|
|
150
|
+
const responseTime = Date.now() - start;
|
|
151
|
+
const value = { [responseTimeKey]: responseTime };
|
|
152
|
+
closingLogger[level](customSuccessObject?.(context, result, value) ?? value, customSuccessMessage?.(context, result, responseTime) ??
|
|
153
|
+
`${info.type} completed`);
|
|
154
|
+
}
|
|
155
|
+
function logErrored(error) {
|
|
156
|
+
const level = levelFor(context, error);
|
|
157
|
+
if (level === 'silent')
|
|
158
|
+
return;
|
|
159
|
+
const responseTime = Date.now() - start;
|
|
160
|
+
const value = {
|
|
161
|
+
[errKey]: error,
|
|
162
|
+
[responseTimeKey]: responseTime,
|
|
163
|
+
};
|
|
164
|
+
closingLogger[level](customErrorObject?.(context, error, value) ?? value, customErrorMessage?.(context, error, responseTime) ??
|
|
165
|
+
`${info.type} errored`);
|
|
166
|
+
}
|
|
167
|
+
// `assign` replaces the store's logger with a child of it, so the log
|
|
168
|
+
// that closes the message keeps the fields it started with — unless
|
|
169
|
+
// `assignResponse` asks for the opposite, exactly as over HTTP.
|
|
170
|
+
const store = new storage_1.Store(contextLogger, assignResponse ? closingLogger : undefined);
|
|
171
|
+
let subscription;
|
|
172
|
+
// Subscribing inside `run` is what puts the whole downstream pipeline —
|
|
173
|
+
// guards, interceptors, pipes and the handler — inside the context.
|
|
174
|
+
storage_1.storage.run(store, () => {
|
|
175
|
+
if (!skip && logsOnArrival) {
|
|
176
|
+
const level = levelFor(context, undefined);
|
|
177
|
+
if (level !== 'silent') {
|
|
178
|
+
contextLogger[level](customReceivedObject?.(context) ?? {}, customReceivedMessage?.(context));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
subscription = next().subscribe({
|
|
182
|
+
next: (value) => {
|
|
183
|
+
result = value;
|
|
184
|
+
subscriber.next(value);
|
|
185
|
+
},
|
|
186
|
+
error: (error) => {
|
|
187
|
+
if (!skip)
|
|
188
|
+
logErrored(error);
|
|
189
|
+
subscriber.error(error);
|
|
190
|
+
},
|
|
191
|
+
complete: () => {
|
|
192
|
+
if (!skip)
|
|
193
|
+
logCompleted();
|
|
194
|
+
subscriber.complete();
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
return () => subscription?.unsubscribe();
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=microservice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"microservice.js","sourceRoot":"","sources":["../src/microservice.ts"],"names":[],"mappings":";;;;;;AAA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CAAC,OAAO,CAAC,IAAI,EAAE,EACrC,qBAAqB,EAAE,CAAC,OAAO,CAAC,CACjC,CAAC;gBACJ,CAAC;YACH,CAAC;YAED,YAAY,GAAG,IAAI,EAAE,CAAC,SAAS,CAAC;gBAC9B,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE;oBACd,MAAM,GAAG,KAAK,CAAC;oBACf,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACzB,CAAC;gBACD,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE;oBACf,IAAI,CAAC,IAAI;wBAAE,UAAU,CAAC,KAAc,CAAC,CAAC;oBACtC,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAC1B,CAAC;gBACD,QAAQ,EAAE,GAAG,EAAE;oBACb,IAAI,CAAC,IAAI;wBAAE,YAAY,EAAE,CAAC;oBAC1B,UAAU,CAAC,QAAQ,EAAE,CAAC;gBACxB,CAAC;aACF,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE,CAAC,YAAY,EAAE,WAAW,EAAE,CAAC;IAC3C,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { ExecutionContext, Logger as NestLogger } from '@nestjs/common';\nimport { LevelWithSilent, Logger } from 'pino';\nimport { Observable, Subscription } from 'rxjs';\n\nimport { MicroserviceParams, Params } from './params';\nimport { getRootLogger } from './rootLogger';\nimport { getRpcInfo, RpcInfo } from './rpc';\nimport { Store, storage } from './storage';\n\n/**\n * Structurally identical to `PreRequestHook` from `@nestjs/common`, which only\n * exists in NestJS 12. Declared here rather than imported so that type checking\n * still passes against the NestJS 11 the package also supports.\n */\nexport type PreRequestHook = (\n context: ExecutionContext,\n next: () => Observable<unknown>,\n) => Observable<unknown>;\n\n/**\n * Injection token of the pre-request hook that does the microservice logging.\n *\n * Prefer {@link registerMicroserviceLogging}, which registers this and\n * everything else the hook needs. This token is the low-level way in, for an\n * application that wires its microservice up by hand.\n */\nexport const PINO_PRE_REQUEST_HOOK = 'pino-pre-request-hook';\n\n/**\n * The subset of `ApplicationConfig` this needs, as of NestJS 12.\n *\n * NestJS 12.0.0 and 12.0.1 are deliberately kept out of the peer range: with a\n * pre-request hook registered they flattened a handler's plain return value —\n * a string replied one character at a time, a number failed outright. Fixed in\n * 12.0.2 by https://github.com/nestjs/nest/pull/17644.\n */\ninterface PreRequestHookRegistry {\n registerPreRequestHook?: (...hooks: PreRequestHook[]) => void;\n getGlobalPreRequestHooks?: () => PreRequestHook[];\n}\n\ntype HookParams = Pick<\n Params<any, any, any>,\n 'microservice' | 'assignResponse'\n>;\n\n// One hook per set of parameters, so that the automatically registered hook and\n// the one behind `PINO_PRE_REQUEST_HOOK` are the same function. Registering the\n// same hook twice would log every message twice.\nconst hooks = new WeakMap<object, PreRequestHook>();\n\nexport function getMicroserviceHook(params: HookParams): PreRequestHook {\n let hook = hooks.get(params);\n if (!hook) {\n hook = createMicroserviceHook(params);\n hooks.set(params, hook);\n }\n return hook;\n}\n\n/**\n * Registers the hook on the `ApplicationConfig` the microservice will read it\n * from. Returns whether the running NestJS supports pre-request hooks at all.\n */\nexport function registerMicroserviceHook(\n applicationConfig: unknown,\n params: HookParams,\n): boolean {\n const registry = applicationConfig as PreRequestHookRegistry;\n\n if (typeof registry.registerPreRequestHook !== 'function') {\n warnNoPreRequestHooks();\n return false;\n }\n\n const hook = getMicroserviceHook(params);\n if (registry.getGlobalPreRequestHooks?.().includes(hook)) {\n return true;\n }\n\n registry.registerPreRequestHook(hook);\n return true;\n}\n\nfunction warnNoPreRequestHooks() {\n new NestLogger('LoggerModule').warn(\n 'Microservice logging needs the pre-request hooks introduced in NestJS ' +\n '12, so microservice messages will be logged without a logging ' +\n 'context. Everything else is unaffected.',\n );\n}\n\n/** The subset of `INestMicroservice` {@link registerMicroserviceLogging} needs. */\ninterface MicroserviceApp {\n get(token: unknown, options?: unknown): unknown;\n /** Optional so that a call still type checks against NestJS 11. */\n registerPreRequestHook?(...hooks: PreRequestHook[]): unknown;\n}\n\n/**\n * Sets up microservice logging on a microservice NestJS could not hand the hook\n * to by itself — a hybrid application connected without\n * `{ inheritAppConfig: true }`, which gets an `ApplicationConfig` of its own\n * that dependency injection cannot reach:\n *\n * ```ts\n * const ms = app.connectMicroservice(options, { deferInitialization: true });\n * registerMicroserviceLogging(ms);\n * ```\n *\n * Must be called before the microservice starts listening, and the module still\n * needs `microservice` in its parameters for the options to apply. On NestJS 11\n * this warns and does nothing, like the parameter itself.\n */\nexport function registerMicroserviceLogging(app: MicroserviceApp): void {\n if (typeof app.registerPreRequestHook !== 'function') {\n warnNoPreRequestHooks();\n return;\n }\n app.registerPreRequestHook(app.get(PINO_PRE_REQUEST_HOOK) as PreRequestHook);\n}\n\nfunction defaultGenReqId() {\n let id = 0;\n return () => ++id;\n}\n\nfunction createMicroserviceHook(params: HookParams): PreRequestHook {\n const options: MicroserviceParams<any> =\n typeof params.microservice === 'object' ? params.microservice : {};\n\n if (options.useLevel && options.customLogLevel) {\n throw new Error(\n \"You can't pass 'useLevel' and 'customLogLevel' together in `microservice`\",\n );\n }\n\n const keys = options.customAttributeKeys ?? {};\n const rpcKey = keys.rpc ?? 'rpc';\n const errKey = keys.err ?? 'err';\n const reqIdKey = keys.reqId ?? 'reqId';\n const responseTimeKey = keys.responseTime ?? 'responseTime';\n\n const useLevel = options.useLevel ?? 'info';\n const customLogLevel = options.customLogLevel;\n const autoLogging = options.autoLogging !== false;\n const ignore =\n typeof options.autoLogging === 'object'\n ? options.autoLogging.ignore\n : undefined;\n const genReqId = options.genReqId ?? defaultGenReqId();\n const assignResponse = !!params.assignResponse;\n const {\n customProps,\n customReceivedMessage,\n customReceivedObject,\n customSuccessMessage,\n customSuccessObject,\n customErrorMessage,\n customErrorObject,\n includePayload,\n quietRpcLogger,\n quietResLogger,\n } = options;\n\n const logsOnArrival = !!customReceivedMessage || !!customReceivedObject;\n\n function levelFor(\n context: ExecutionContext,\n error: Error | undefined,\n ): LevelWithSilent {\n if (customLogLevel) {\n return customLogLevel(context, error) as LevelWithSilent;\n }\n // `pino-http` logs a failed request at `useLevel` too; errors here default\n // to `error` instead, because `useLevel` is routinely lowered to quiet down\n // chatty events and that must not also hide failures. The hook sees the\n // error before any `@Catch()` filter, so an `RpcException` thrown on\n // purpose reaches this as well — `customLogLevel` is the way out.\n return error ? 'error' : (useLevel as LevelWithSilent);\n }\n\n function buildRecord(context: ExecutionContext, info: RpcInfo) {\n const record: Record<string, unknown> = {\n type: info.type,\n pattern: info.pattern,\n transport: info.transport,\n controller: info.controller,\n handler: info.handler,\n };\n if (includePayload) {\n record.payload = context.switchToRpc().getData();\n }\n return record;\n }\n\n return (context, next) =>\n new Observable<unknown>((subscriber) => {\n const base = getRootLogger();\n // Only reachable if the hook runs before any `PinoLogger` was built,\n // which the module's own ordering rules out. Log nothing rather than\n // break the message.\n if (!base) {\n return next().subscribe(subscriber);\n }\n\n const info = getRpcInfo(context);\n const quiet = base.child({ [reqIdKey]: genReqId(context) });\n\n let full: Logger = quiet.child({\n [rpcKey]: buildRecord(context, info),\n });\n const props = customProps?.(context);\n if (props) {\n full = full.child(props);\n }\n\n const contextLogger = quietRpcLogger ? quiet : full;\n const closingLogger = quietResLogger ? quiet : full;\n const skip = !autoLogging || (ignore?.(context) ?? false);\n const start = Date.now();\n let result: unknown;\n\n function logCompleted() {\n const level = levelFor(context, undefined);\n if (level === 'silent') return;\n\n const responseTime = Date.now() - start;\n const value = { [responseTimeKey]: responseTime };\n closingLogger[level](\n customSuccessObject?.(context, result, value) ?? value,\n customSuccessMessage?.(context, result, responseTime) ??\n `${info.type} completed`,\n );\n }\n\n function logErrored(error: Error) {\n const level = levelFor(context, error);\n if (level === 'silent') return;\n\n const responseTime = Date.now() - start;\n const value = {\n [errKey]: error,\n [responseTimeKey]: responseTime,\n };\n closingLogger[level](\n customErrorObject?.(context, error, value) ?? value,\n customErrorMessage?.(context, error, responseTime) ??\n `${info.type} errored`,\n );\n }\n\n // `assign` replaces the store's logger with a child of it, so the log\n // that closes the message keeps the fields it started with — unless\n // `assignResponse` asks for the opposite, exactly as over HTTP.\n const store = new Store(\n contextLogger,\n assignResponse ? closingLogger : undefined,\n );\n\n let subscription: Subscription | undefined;\n\n // Subscribing inside `run` is what puts the whole downstream pipeline —\n // guards, interceptors, pipes and the handler — inside the context.\n storage.run(store, () => {\n if (!skip && logsOnArrival) {\n const level = levelFor(context, undefined);\n if (level !== 'silent') {\n contextLogger[level](\n customReceivedObject?.(context) ?? {},\n customReceivedMessage?.(context),\n );\n }\n }\n\n subscription = next().subscribe({\n next: (value) => {\n result = value;\n subscriber.next(value);\n },\n error: (error) => {\n if (!skip) logErrored(error as Error);\n subscriber.error(error);\n },\n complete: () => {\n if (!skip) logCompleted();\n subscriber.complete();\n },\n });\n });\n\n return () => subscription?.unsubscribe();\n });\n}\n"]}
|
package/dist/params.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
-
import { FactoryProvider, MiddlewareConsumer, ModuleMetadata } from '@nestjs/common';
|
|
3
|
-
import { DestinationStream, Logger } from 'pino';
|
|
4
|
-
import { Options } from 'pino-http';
|
|
2
|
+
import { ExecutionContext, FactoryProvider, MiddlewareConsumer, ModuleMetadata } from '@nestjs/common';
|
|
3
|
+
import { DestinationStream, LevelWithSilent, Logger } from 'pino';
|
|
4
|
+
import { Options, ReqId } from 'pino-http';
|
|
5
5
|
export type MiddlewareConfigProxy = ReturnType<MiddlewareConsumer['apply']>;
|
|
6
6
|
export type PassedLogger<CustomLevels extends string = never> = {
|
|
7
7
|
logger: Logger<CustomLevels>;
|
|
@@ -84,6 +84,131 @@ export interface Params<IM = IncomingMessage, SR = ServerResponse, CustomLevels
|
|
|
84
84
|
*/
|
|
85
85
|
flattenParams?: boolean;
|
|
86
86
|
};
|
|
87
|
+
/**
|
|
88
|
+
* Enables `pino-http`-like automatic logging and, more importantly, a logging
|
|
89
|
+
* context for microservice message handlers, so that `PinoLogger.assign` and
|
|
90
|
+
* inherited fields work there the way they do in an HTTP request. Pass `true`
|
|
91
|
+
* for the defaults.
|
|
92
|
+
*
|
|
93
|
+
* Implemented on the NestJS 12 microservices pre-request hooks, which the
|
|
94
|
+
* module registers by itself; 12.0.2 or later, because earlier 12.0.x
|
|
95
|
+
* releases mangled a handler's plain return value once a hook was present.
|
|
96
|
+
* Two caveats follow from how NestJS wires them: on NestJS 11 the API does
|
|
97
|
+
* not exist and this is ignored with a warning, and a hybrid application has
|
|
98
|
+
* to be connected with `{ inheritAppConfig: true }` for the hook to reach its
|
|
99
|
+
* microservice.
|
|
100
|
+
* @see https://docs.nestjs.com/microservices/pre-request-hooks
|
|
101
|
+
*/
|
|
102
|
+
microservice?: boolean | MicroserviceParams<CustomLevels>;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Options for automatic logging of microservice messages, deliberately shaped
|
|
106
|
+
* after `pino-http`'s: every parameter that does not need the request or the
|
|
107
|
+
* response keeps its name and meaning, and the ones that do take an
|
|
108
|
+
* `ExecutionContext` instead. Use {@link getRpcInfo} inside them to reach the
|
|
109
|
+
* pattern, the transport and whether the handler is a `@MessagePattern` or an
|
|
110
|
+
* `@EventPattern`.
|
|
111
|
+
*
|
|
112
|
+
* Everything pino itself is configured with — level, transport, redact,
|
|
113
|
+
* serializers, formatters — stays in `pinoHttp`, which builds the one logger
|
|
114
|
+
* both halves of the application share.
|
|
115
|
+
*
|
|
116
|
+
* @see https://github.com/pinojs/pino-http#pinohttpopts-stream
|
|
117
|
+
*/
|
|
118
|
+
export interface MicroserviceParams<CustomLevels extends string = never> {
|
|
119
|
+
/**
|
|
120
|
+
* Set to `false` to stop logging a line per message. The logging *context*
|
|
121
|
+
* is still established either way, so `PinoLogger.assign` and the inherited
|
|
122
|
+
* fields keep working.
|
|
123
|
+
* @default true
|
|
124
|
+
*/
|
|
125
|
+
autoLogging?: boolean | {
|
|
126
|
+
/** Skip the automatic logs for the messages this returns `true` for. */
|
|
127
|
+
ignore?: (context: ExecutionContext) => boolean;
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Level of the `received` and `completed` logs. Errors default to `error`
|
|
131
|
+
* regardless of this — unlike `pino-http`, where a failed request is logged
|
|
132
|
+
* at `useLevel` too — so that lowering this to quiet down events does not
|
|
133
|
+
* also hide failures. Use `customLogLevel` to change the error level.
|
|
134
|
+
* Cannot be combined with `customLogLevel`.
|
|
135
|
+
* @default 'info'
|
|
136
|
+
*/
|
|
137
|
+
useLevel?: LevelWithSilent | CustomLevels;
|
|
138
|
+
/**
|
|
139
|
+
* Decides the level of every automatic log, including the error one. Note
|
|
140
|
+
* that the hook runs before any `@Catch()` filter, so `error` is set for
|
|
141
|
+
* exceptions the application goes on to handle itself, an `RpcException`
|
|
142
|
+
* thrown on purpose included.
|
|
143
|
+
*/
|
|
144
|
+
customLogLevel?: (context: ExecutionContext, error?: Error) => LevelWithSilent | CustomLevels;
|
|
145
|
+
/**
|
|
146
|
+
* Generates the value bound as `reqId`. Defaults to an incrementing counter,
|
|
147
|
+
* as in `pino-http`; a correlation id off the transport context is usually a
|
|
148
|
+
* better choice.
|
|
149
|
+
*/
|
|
150
|
+
genReqId?: (context: ExecutionContext) => ReqId;
|
|
151
|
+
/**
|
|
152
|
+
* Setting this — or `customReceivedObject` — is what enables the log on
|
|
153
|
+
* arrival. There is no default text, so nothing is logged on arrival unless
|
|
154
|
+
* asked for, exactly as in `pino-http`.
|
|
155
|
+
*/
|
|
156
|
+
customReceivedMessage?: (context: ExecutionContext) => string;
|
|
157
|
+
/** @default `'message completed'`, or `'event completed'` for an `@EventPattern` */
|
|
158
|
+
customSuccessMessage?: (context: ExecutionContext, result: unknown, responseTime: number) => string;
|
|
159
|
+
/** @default `'message errored'`, or `'event errored'` for an `@EventPattern` */
|
|
160
|
+
customErrorMessage?: (context: ExecutionContext, error: Error, responseTime: number) => string;
|
|
161
|
+
/**
|
|
162
|
+
* Fields of the log on arrival, which it enables the same way
|
|
163
|
+
* `customReceivedMessage` does. There is no default object, so what it
|
|
164
|
+
* returns is logged as is.
|
|
165
|
+
*/
|
|
166
|
+
customReceivedObject?: (context: ExecutionContext) => object;
|
|
167
|
+
/**
|
|
168
|
+
* Replaces the fields of the `completed` log. `value` is what would be logged
|
|
169
|
+
* otherwise — `responseTime` under its configured key — and is not merged
|
|
170
|
+
* back in, so spread it if the extra fields should come on top.
|
|
171
|
+
*/
|
|
172
|
+
customSuccessObject?: (context: ExecutionContext, result: unknown, value: object) => object;
|
|
173
|
+
/**
|
|
174
|
+
* Replaces the fields of the `errored` log. `value` holds `err` and
|
|
175
|
+
* `responseTime` under their configured keys and, as with
|
|
176
|
+
* `customSuccessObject`, is not merged back in.
|
|
177
|
+
*/
|
|
178
|
+
customErrorObject?: (context: ExecutionContext, error: Error, value: object) => object;
|
|
179
|
+
/** Extra fields bound to every log made while handling the message. */
|
|
180
|
+
customProps?: (context: ExecutionContext) => object;
|
|
181
|
+
/**
|
|
182
|
+
* Renames the keys this adds to the log record. The `rpc` key is the
|
|
183
|
+
* microservice counterpart of `pino-http`'s `req`/`res`.
|
|
184
|
+
*/
|
|
185
|
+
customAttributeKeys?: {
|
|
186
|
+
/** @default 'rpc' */
|
|
187
|
+
rpc?: string;
|
|
188
|
+
/** @default 'err' */
|
|
189
|
+
err?: string;
|
|
190
|
+
/** @default 'reqId' */
|
|
191
|
+
reqId?: string;
|
|
192
|
+
/** @default 'responseTime' */
|
|
193
|
+
responseTime?: string;
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* Bind only `reqId`, leaving the `rpc` object out of the logs made while
|
|
197
|
+
* handling the message. Mirrors `pino-http`'s `quietReqLogger`.
|
|
198
|
+
*/
|
|
199
|
+
quietRpcLogger?: boolean;
|
|
200
|
+
/**
|
|
201
|
+
* Leave the `rpc` object out of the `completed`/`errored` log, which repeats
|
|
202
|
+
* what the surrounding logs already carry. Mirrors `quietResLogger`.
|
|
203
|
+
*/
|
|
204
|
+
quietResLogger?: boolean;
|
|
205
|
+
/**
|
|
206
|
+
* Log the message payload as `rpc.payload`. Off by default: payloads are
|
|
207
|
+
* unbounded in size and routinely carry personal data. `redact` and a
|
|
208
|
+
* `serializers.rpc` entry in `pinoHttp` apply to it as to anything else.
|
|
209
|
+
* @default false
|
|
210
|
+
*/
|
|
211
|
+
includePayload?: boolean;
|
|
87
212
|
}
|
|
88
213
|
export interface LoggerModuleAsyncParams<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never> extends Pick<ModuleMetadata, 'imports' | 'providers'>, Pick<FactoryProvider<Params<IM, SR, CustomLevels>>, 'useFactory' | 'inject'> {
|
|
89
214
|
}
|
package/dist/params.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"params.js","sourceRoot":"","sources":["../src/params.ts"],"names":[],"mappings":";;;;AA+HA,wBACE,YAAiB;IAEjB,OAAO,CAAC,CAAC,YAAY,IAAI,QAAQ,IAAI,YAAY,CAAC;AACpD,CAAC;AAEY,QAAA,qBAAqB,GAAG,aAAa,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n FactoryProvider,\n MiddlewareConsumer,\n ModuleMetadata,\n} from '@nestjs/common';\nimport { DestinationStream, Logger } from 'pino';\nimport { Options } from 'pino-http';\n\n// The `@nestjs/common/interfaces` subpath stopped resolving in v12, where the\n// package is ESM and its exports map turns `./interfaces` into a missing\n// `interfaces.js`. `MiddlewareConfigProxy` is not re-exported from the root\n// either, so derive it from `MiddlewareConsumer`.\nexport type MiddlewareConfigProxy = ReturnType<MiddlewareConsumer['apply']>;\n\nexport type PassedLogger<CustomLevels extends string = never> = {\n logger: Logger<CustomLevels>;\n};\n\n/**\n * The type parameters are all optional and default to what `pino-http` itself\n * defaults to, so `Params` keeps working unparameterised.\n *\n * @typeParam IM - request type, e.g. express' `Request`\n * @typeParam SR - response type, e.g. express' `Response`\n * @typeParam CustomLevels - union of the `customLevels` keys, if any\n */\nexport interface Params<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n> {\n /**\n * Optional parameters for `pino-http` module\n * @see https://github.com/pinojs/pino-http#pinohttpopts-stream\n */\n pinoHttp?:\n | Options<IM, SR, CustomLevels>\n | DestinationStream\n | [Options<IM, SR, CustomLevels>, DestinationStream];\n\n /**\n * Optional parameter for routing. It should implement interface of\n * parameters of NestJS built-in `MiddlewareConfigProxy['forRoutes']`.\n * @see https://docs.nestjs.com/middleware#applying-middleware\n * It can be used for both disabling automatic req/res logs and\n * removing request context from following logs. It works for all requests by\n * default. If you only need to turn off the automatic request/response\n * logging for some specific (or all) routes but keep request context for app\n * logs use `pinoHttp.autoLogging` field.\n */\n exclude?: Parameters<MiddlewareConfigProxy['exclude']>;\n\n /**\n * Optional parameter for routing. It should implement interface of\n * parameters of NestJS built-in `MiddlewareConfigProxy['forRoutes']`.\n * @see https://docs.nestjs.com/middleware#applying-middleware\n * It can be used for both disabling automatic req/res logs and\n * removing request context from following logs. It works for all requests by\n * default. If you only need to turn off the automatic request/response\n * logging for some specific (or all) routes but keep request context for app\n * logs use `pinoHttp.autoLogging` field.\n */\n forRoutes?: Parameters<MiddlewareConfigProxy['forRoutes']>;\n\n /**\n * Optional parameter to skip pino configuration in case you are using\n * FastifyAdapter, and already configure logger in adapter's config. The Pros\n * and cons of this approach are described in the FAQ section of the\n * documentation:\n * @see https://github.com/iamolegga/nestjs-pino#faq.\n */\n useExisting?: true;\n\n /**\n * Optional parameter to change property name `context` in resulted logs,\n * so logs will be like:\n * {\"level\":30, ... \"RENAME_CONTEXT_VALUE_HERE\":\"AppController\" }\n */\n renameContext?: string;\n\n /**\n * Optional parameter to also assign the response logger during calls to\n * `PinoLogger.assign`. By default, `assign` does not impact response logs\n * (e.g.`Request completed`).\n */\n assignResponse?: boolean;\n\n /**\n * Optional parameters for `NativeLogger`, mirroring the `ConsoleLogger`\n * options of the same name so that an application can move over keeping its\n * existing configuration. Unlike NestJS, both are honoured on every supported\n * NestJS version; only the default of `structuredParams` follows the\n * `ConsoleLogger` that is actually installed.\n */\n nativeLogger?: {\n /**\n * If enabled, plain objects logged after the message are attached to the\n * same entry as `params` instead of being logged as separate entries.\n * @default true on NestJS 12+, false before that\n */\n structuredParams?: boolean;\n\n /**\n * If enabled, params are spread into the root of the record instead of\n * nested under `params`. Keys already used by the log record itself are\n * never overwritten.\n * @default false\n */\n flattenParams?: boolean;\n };\n}\n\nexport interface LoggerModuleAsyncParams<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n> extends Pick<ModuleMetadata, 'imports' | 'providers'>,\n // `provide` is deliberately not picked: `forRootAsync` sets it to\n // `PARAMS_PROVIDER_TOKEN` itself, so a caller-supplied token would only be\n // overwritten.\n Pick<\n FactoryProvider<Params<IM, SR, CustomLevels>>,\n 'useFactory' | 'inject'\n > {}\n\nexport function isPassedLogger(\n pinoHttpProp: any,\n): pinoHttpProp is PassedLogger {\n return !!pinoHttpProp && 'logger' in pinoHttpProp;\n}\n\nexport const PARAMS_PROVIDER_TOKEN = 'pino-params';\n"]}
|
|
1
|
+
{"version":3,"file":"params.js","sourceRoot":"","sources":["../src/params.ts"],"names":[],"mappings":";;;;AAkSA,wBACE,YAAiB;IAEjB,OAAO,CAAC,CAAC,YAAY,IAAI,QAAQ,IAAI,YAAY,CAAC;AACpD,CAAC;AAEY,QAAA,qBAAqB,GAAG,aAAa,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n ExecutionContext,\n FactoryProvider,\n MiddlewareConsumer,\n ModuleMetadata,\n} from '@nestjs/common';\nimport { DestinationStream, LevelWithSilent, Logger } from 'pino';\nimport { Options, ReqId } from 'pino-http';\n\n// The `@nestjs/common/interfaces` subpath stopped resolving in v12, where the\n// package is ESM and its exports map turns `./interfaces` into a missing\n// `interfaces.js`. `MiddlewareConfigProxy` is not re-exported from the root\n// either, so derive it from `MiddlewareConsumer`.\nexport type MiddlewareConfigProxy = ReturnType<MiddlewareConsumer['apply']>;\n\nexport type PassedLogger<CustomLevels extends string = never> = {\n logger: Logger<CustomLevels>;\n};\n\n/**\n * The type parameters are all optional and default to what `pino-http` itself\n * defaults to, so `Params` keeps working unparameterised.\n *\n * @typeParam IM - request type, e.g. express' `Request`\n * @typeParam SR - response type, e.g. express' `Response`\n * @typeParam CustomLevels - union of the `customLevels` keys, if any\n */\nexport interface Params<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n> {\n /**\n * Optional parameters for `pino-http` module\n * @see https://github.com/pinojs/pino-http#pinohttpopts-stream\n */\n pinoHttp?:\n | Options<IM, SR, CustomLevels>\n | DestinationStream\n | [Options<IM, SR, CustomLevels>, DestinationStream];\n\n /**\n * Optional parameter for routing. It should implement interface of\n * parameters of NestJS built-in `MiddlewareConfigProxy['forRoutes']`.\n * @see https://docs.nestjs.com/middleware#applying-middleware\n * It can be used for both disabling automatic req/res logs and\n * removing request context from following logs. It works for all requests by\n * default. If you only need to turn off the automatic request/response\n * logging for some specific (or all) routes but keep request context for app\n * logs use `pinoHttp.autoLogging` field.\n */\n exclude?: Parameters<MiddlewareConfigProxy['exclude']>;\n\n /**\n * Optional parameter for routing. It should implement interface of\n * parameters of NestJS built-in `MiddlewareConfigProxy['forRoutes']`.\n * @see https://docs.nestjs.com/middleware#applying-middleware\n * It can be used for both disabling automatic req/res logs and\n * removing request context from following logs. It works for all requests by\n * default. If you only need to turn off the automatic request/response\n * logging for some specific (or all) routes but keep request context for app\n * logs use `pinoHttp.autoLogging` field.\n */\n forRoutes?: Parameters<MiddlewareConfigProxy['forRoutes']>;\n\n /**\n * Optional parameter to skip pino configuration in case you are using\n * FastifyAdapter, and already configure logger in adapter's config. The Pros\n * and cons of this approach are described in the FAQ section of the\n * documentation:\n * @see https://github.com/iamolegga/nestjs-pino#faq.\n */\n useExisting?: true;\n\n /**\n * Optional parameter to change property name `context` in resulted logs,\n * so logs will be like:\n * {\"level\":30, ... \"RENAME_CONTEXT_VALUE_HERE\":\"AppController\" }\n */\n renameContext?: string;\n\n /**\n * Optional parameter to also assign the response logger during calls to\n * `PinoLogger.assign`. By default, `assign` does not impact response logs\n * (e.g.`Request completed`).\n */\n assignResponse?: boolean;\n\n /**\n * Optional parameters for `NativeLogger`, mirroring the `ConsoleLogger`\n * options of the same name so that an application can move over keeping its\n * existing configuration. Unlike NestJS, both are honoured on every supported\n * NestJS version; only the default of `structuredParams` follows the\n * `ConsoleLogger` that is actually installed.\n */\n nativeLogger?: {\n /**\n * If enabled, plain objects logged after the message are attached to the\n * same entry as `params` instead of being logged as separate entries.\n * @default true on NestJS 12+, false before that\n */\n structuredParams?: boolean;\n\n /**\n * If enabled, params are spread into the root of the record instead of\n * nested under `params`. Keys already used by the log record itself are\n * never overwritten.\n * @default false\n */\n flattenParams?: boolean;\n };\n\n /**\n * Enables `pino-http`-like automatic logging and, more importantly, a logging\n * context for microservice message handlers, so that `PinoLogger.assign` and\n * inherited fields work there the way they do in an HTTP request. Pass `true`\n * for the defaults.\n *\n * Implemented on the NestJS 12 microservices pre-request hooks, which the\n * module registers by itself; 12.0.2 or later, because earlier 12.0.x\n * releases mangled a handler's plain return value once a hook was present.\n * Two caveats follow from how NestJS wires them: on NestJS 11 the API does\n * not exist and this is ignored with a warning, and a hybrid application has\n * to be connected with `{ inheritAppConfig: true }` for the hook to reach its\n * microservice.\n * @see https://docs.nestjs.com/microservices/pre-request-hooks\n */\n microservice?: boolean | MicroserviceParams<CustomLevels>;\n}\n\n/**\n * Options for automatic logging of microservice messages, deliberately shaped\n * after `pino-http`'s: every parameter that does not need the request or the\n * response keeps its name and meaning, and the ones that do take an\n * `ExecutionContext` instead. Use {@link getRpcInfo} inside them to reach the\n * pattern, the transport and whether the handler is a `@MessagePattern` or an\n * `@EventPattern`.\n *\n * Everything pino itself is configured with — level, transport, redact,\n * serializers, formatters — stays in `pinoHttp`, which builds the one logger\n * both halves of the application share.\n *\n * @see https://github.com/pinojs/pino-http#pinohttpopts-stream\n */\nexport interface MicroserviceParams<CustomLevels extends string = never> {\n /**\n * Set to `false` to stop logging a line per message. The logging *context*\n * is still established either way, so `PinoLogger.assign` and the inherited\n * fields keep working.\n * @default true\n */\n autoLogging?:\n | boolean\n | {\n /** Skip the automatic logs for the messages this returns `true` for. */\n ignore?: (context: ExecutionContext) => boolean;\n };\n\n /**\n * Level of the `received` and `completed` logs. Errors default to `error`\n * regardless of this — unlike `pino-http`, where a failed request is logged\n * at `useLevel` too — so that lowering this to quiet down events does not\n * also hide failures. Use `customLogLevel` to change the error level.\n * Cannot be combined with `customLogLevel`.\n * @default 'info'\n */\n useLevel?: LevelWithSilent | CustomLevels;\n\n /**\n * Decides the level of every automatic log, including the error one. Note\n * that the hook runs before any `@Catch()` filter, so `error` is set for\n * exceptions the application goes on to handle itself, an `RpcException`\n * thrown on purpose included.\n */\n customLogLevel?: (\n context: ExecutionContext,\n error?: Error,\n ) => LevelWithSilent | CustomLevels;\n\n /**\n * Generates the value bound as `reqId`. Defaults to an incrementing counter,\n * as in `pino-http`; a correlation id off the transport context is usually a\n * better choice.\n */\n genReqId?: (context: ExecutionContext) => ReqId;\n\n /**\n * Setting this — or `customReceivedObject` — is what enables the log on\n * arrival. There is no default text, so nothing is logged on arrival unless\n * asked for, exactly as in `pino-http`.\n */\n customReceivedMessage?: (context: ExecutionContext) => string;\n\n /** @default `'message completed'`, or `'event completed'` for an `@EventPattern` */\n customSuccessMessage?: (\n context: ExecutionContext,\n result: unknown,\n responseTime: number,\n ) => string;\n\n /** @default `'message errored'`, or `'event errored'` for an `@EventPattern` */\n customErrorMessage?: (\n context: ExecutionContext,\n error: Error,\n responseTime: number,\n ) => string;\n\n /**\n * Fields of the log on arrival, which it enables the same way\n * `customReceivedMessage` does. There is no default object, so what it\n * returns is logged as is.\n */\n customReceivedObject?: (context: ExecutionContext) => object;\n\n /**\n * Replaces the fields of the `completed` log. `value` is what would be logged\n * otherwise — `responseTime` under its configured key — and is not merged\n * back in, so spread it if the extra fields should come on top.\n */\n customSuccessObject?: (\n context: ExecutionContext,\n result: unknown,\n value: object,\n ) => object;\n\n /**\n * Replaces the fields of the `errored` log. `value` holds `err` and\n * `responseTime` under their configured keys and, as with\n * `customSuccessObject`, is not merged back in.\n */\n customErrorObject?: (\n context: ExecutionContext,\n error: Error,\n value: object,\n ) => object;\n\n /** Extra fields bound to every log made while handling the message. */\n customProps?: (context: ExecutionContext) => object;\n\n /**\n * Renames the keys this adds to the log record. The `rpc` key is the\n * microservice counterpart of `pino-http`'s `req`/`res`.\n */\n customAttributeKeys?: {\n /** @default 'rpc' */\n rpc?: string;\n /** @default 'err' */\n err?: string;\n /** @default 'reqId' */\n reqId?: string;\n /** @default 'responseTime' */\n responseTime?: string;\n };\n\n /**\n * Bind only `reqId`, leaving the `rpc` object out of the logs made while\n * handling the message. Mirrors `pino-http`'s `quietReqLogger`.\n */\n quietRpcLogger?: boolean;\n\n /**\n * Leave the `rpc` object out of the `completed`/`errored` log, which repeats\n * what the surrounding logs already carry. Mirrors `quietResLogger`.\n */\n quietResLogger?: boolean;\n\n /**\n * Log the message payload as `rpc.payload`. Off by default: payloads are\n * unbounded in size and routinely carry personal data. `redact` and a\n * `serializers.rpc` entry in `pinoHttp` apply to it as to anything else.\n * @default false\n */\n includePayload?: boolean;\n}\n\nexport interface LoggerModuleAsyncParams<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n> extends Pick<ModuleMetadata, 'imports' | 'providers'>,\n // `provide` is deliberately not picked: `forRootAsync` sets it to\n // `PARAMS_PROVIDER_TOKEN` itself, so a caller-supplied token would only be\n // overwritten.\n Pick<\n FactoryProvider<Params<IM, SR, CustomLevels>>,\n 'useFactory' | 'inject'\n > {}\n\nexport function isPassedLogger(\n pinoHttpProp: any,\n): pinoHttpProp is PassedLogger {\n return !!pinoHttpProp && 'logger' in pinoHttpProp;\n}\n\nexport const PARAMS_PROVIDER_TOKEN = 'pino-params';\n"]}
|
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ExecutionContext } from '@nestjs/common';
|
|
2
|
+
export type RpcType = 'message' | 'event';
|
|
3
|
+
/**
|
|
4
|
+
* What is known about the message being handled. This is also what is logged
|
|
5
|
+
* under the `rpc` key, apart from the payload, which `includePayload` adds.
|
|
6
|
+
*/
|
|
7
|
+
export interface RpcInfo {
|
|
8
|
+
/**
|
|
9
|
+
* `'message'` for `@MessagePattern`, where the caller is waiting for a reply,
|
|
10
|
+
* `'event'` for `@EventPattern`, where nobody is.
|
|
11
|
+
*/
|
|
12
|
+
type: RpcType;
|
|
13
|
+
/** The pattern the handler is registered for, as given to the decorator. */
|
|
14
|
+
pattern: string | number | symbol | Record<string, unknown> | undefined;
|
|
15
|
+
/** Lowercased transport name, e.g. `'rmq'`, `'kafka'`, `'tcp'`. */
|
|
16
|
+
transport: string | undefined;
|
|
17
|
+
controller: string;
|
|
18
|
+
handler: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Describes the message a microservice handler was called with.
|
|
22
|
+
*
|
|
23
|
+
* Every callback of the `microservice` parameters receives an `ExecutionContext`
|
|
24
|
+
* and nothing else, the way `pino-http`'s callbacks receive the request, so
|
|
25
|
+
* this is how they reach the pattern, the transport and — most usefully — the
|
|
26
|
+
* `type`, to tell a `@MessagePattern` from an `@EventPattern`:
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* customLogLevel: (ctx, err) =>
|
|
30
|
+
* err ? 'error' : getRpcInfo(ctx).type === 'event' ? 'debug' : 'info',
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* Never throws: a context it cannot read reports a message with no pattern.
|
|
34
|
+
*/
|
|
35
|
+
export declare function getRpcInfo(context: ExecutionContext): RpcInfo;
|
package/dist/rpc.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getRpcInfo = getRpcInfo;
|
|
4
|
+
/**
|
|
5
|
+
* Read reflectively rather than imported, so that `@nestjs/microservices` stays
|
|
6
|
+
* a dependency of the *application* and never of this package. These keys are
|
|
7
|
+
* part of the metadata `@MessagePattern` and `@EventPattern` write, and are
|
|
8
|
+
* stable across NestJS 11 and 12.
|
|
9
|
+
*/
|
|
10
|
+
const PATTERN_METADATA = 'microservices:pattern';
|
|
11
|
+
const PATTERN_HANDLER_METADATA = 'microservices:handler_type';
|
|
12
|
+
const TRANSPORT_METADATA = 'microservices:transport';
|
|
13
|
+
/** `PatternHandler.EVENT`; `MESSAGE` is 1. */
|
|
14
|
+
const EVENT_HANDLER = 2;
|
|
15
|
+
/** Indexed by the `Transport` enum, for the rare handler that pins one. */
|
|
16
|
+
const TRANSPORT_NAMES = [
|
|
17
|
+
'tcp',
|
|
18
|
+
'redis',
|
|
19
|
+
'nats',
|
|
20
|
+
'mqtt',
|
|
21
|
+
'grpc',
|
|
22
|
+
'rmq',
|
|
23
|
+
'kafka',
|
|
24
|
+
];
|
|
25
|
+
const CONTEXT_SUFFIX = 'Context';
|
|
26
|
+
// The pattern and the kind are fixed for a handler method, so they are read
|
|
27
|
+
// once instead of on every message.
|
|
28
|
+
const staticInfoCache = new WeakMap();
|
|
29
|
+
function readStaticInfo(handler) {
|
|
30
|
+
if (!handler || typeof Reflect.getMetadata !== 'function') {
|
|
31
|
+
return { type: 'message', pattern: undefined, transport: undefined };
|
|
32
|
+
}
|
|
33
|
+
const patterns = Reflect.getMetadata(PATTERN_METADATA, handler);
|
|
34
|
+
const kind = Reflect.getMetadata(PATTERN_HANDLER_METADATA, handler);
|
|
35
|
+
const transport = Reflect.getMetadata(TRANSPORT_METADATA, handler);
|
|
36
|
+
return {
|
|
37
|
+
// A handler with no metadata at all is not necessarily a mistake — a custom
|
|
38
|
+
// transport strategy can register one — so it is reported as a message,
|
|
39
|
+
// which is both the more common kind and the safer default.
|
|
40
|
+
type: kind === EVENT_HANDLER ? 'event' : 'message',
|
|
41
|
+
pattern: Array.isArray(patterns)
|
|
42
|
+
? patterns.length > 1
|
|
43
|
+
? patterns
|
|
44
|
+
: patterns[0]
|
|
45
|
+
: patterns,
|
|
46
|
+
transport: typeof transport === 'number' ? TRANSPORT_NAMES[transport] : undefined,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The transport a message actually arrived on, taken from the class of the
|
|
51
|
+
* per-message context — `RmqContext`, `KafkaContext`, `TcpContext` and so on.
|
|
52
|
+
* More reliable than the decorator metadata, which is only set when a handler
|
|
53
|
+
* explicitly pins a transport.
|
|
54
|
+
*/
|
|
55
|
+
function readTransport(context) {
|
|
56
|
+
let rpcContext;
|
|
57
|
+
try {
|
|
58
|
+
rpcContext = context.switchToRpc().getContext();
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const name = rpcContext?.constructor
|
|
64
|
+
?.name;
|
|
65
|
+
if (typeof name !== 'string' ||
|
|
66
|
+
name === CONTEXT_SUFFIX ||
|
|
67
|
+
!name.endsWith(CONTEXT_SUFFIX)) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
return name.slice(0, -CONTEXT_SUFFIX.length).toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Describes the message a microservice handler was called with.
|
|
74
|
+
*
|
|
75
|
+
* Every callback of the `microservice` parameters receives an `ExecutionContext`
|
|
76
|
+
* and nothing else, the way `pino-http`'s callbacks receive the request, so
|
|
77
|
+
* this is how they reach the pattern, the transport and — most usefully — the
|
|
78
|
+
* `type`, to tell a `@MessagePattern` from an `@EventPattern`:
|
|
79
|
+
*
|
|
80
|
+
* ```ts
|
|
81
|
+
* customLogLevel: (ctx, err) =>
|
|
82
|
+
* err ? 'error' : getRpcInfo(ctx).type === 'event' ? 'debug' : 'info',
|
|
83
|
+
* ```
|
|
84
|
+
*
|
|
85
|
+
* Never throws: a context it cannot read reports a message with no pattern.
|
|
86
|
+
*/
|
|
87
|
+
function getRpcInfo(context) {
|
|
88
|
+
const handler = context.getHandler?.();
|
|
89
|
+
let staticInfo = handler && staticInfoCache.get(handler);
|
|
90
|
+
if (!staticInfo) {
|
|
91
|
+
staticInfo = readStaticInfo(handler);
|
|
92
|
+
if (handler) {
|
|
93
|
+
staticInfoCache.set(handler, staticInfo);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
type: staticInfo.type,
|
|
98
|
+
pattern: staticInfo.pattern,
|
|
99
|
+
transport: readTransport(context) ?? staticInfo.transport,
|
|
100
|
+
controller: context.getClass?.()?.name ?? '',
|
|
101
|
+
handler: handler?.name ?? '',
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=rpc.js.map
|
package/dist/rpc.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,uBAAuB,CAAC;AACjD,MAAM,wBAAwB,GAAG,4BAA4B,CAAC;AAC9D,MAAM,kBAAkB,GAAG,yBAAyB,CAAC;AAErD,8CAA8C;AAC9C,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,2EAA2E;AAC3E,MAAM,eAAe,GAAG;IACtB,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;CACR,CAAC;AAEF,MAAM,cAAc,GAAG,SAAS,CAAC;AA4BjC,4EAA4E;AAC5E,oCAAoC;AACpC,MAAM,eAAe,GAAG,IAAI,OAAO,EAA0C,CAAC;AAE9E,SAAS,cAAc,CACrB,OAA8C;IAE9C,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,CAAC,WAAW,KAAK,UAAU,EAAE,CAAC;QAC1D,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,SA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C,KAAK,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC;AAC7D,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,oBAA2B,OAAyB;IAClD,MAAM,OAAO,GAAG,OAAO,CAAC,UAAU,EAAE,EAEvB,CAAC;IAEd,IAAI,UAAU,GAAG,OAAO,IAAI,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACzD,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;QACrC,IAAI,OAAO,EAAE,CAAC;YACZ,eAAe,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,SAAS,EAAE,aAAa,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,SAAS;QACzD,UAAU,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE;QAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;KAC7B,CAAC;AACJ,CAAC","sourcesContent":["import { ExecutionContext } from '@nestjs/common';\n\n/**\n * Read reflectively rather than imported, so that `@nestjs/microservices` stays\n * a dependency of the *application* and never of this package. These keys are\n * part of the metadata `@MessagePattern` and `@EventPattern` write, and are\n * stable across NestJS 11 and 12.\n */\nconst PATTERN_METADATA = 'microservices:pattern';\nconst PATTERN_HANDLER_METADATA = 'microservices:handler_type';\nconst TRANSPORT_METADATA = 'microservices:transport';\n\n/** `PatternHandler.EVENT`; `MESSAGE` is 1. */\nconst EVENT_HANDLER = 2;\n\n/** Indexed by the `Transport` enum, for the rare handler that pins one. */\nconst TRANSPORT_NAMES = [\n 'tcp',\n 'redis',\n 'nats',\n 'mqtt',\n 'grpc',\n 'rmq',\n 'kafka',\n];\n\nconst CONTEXT_SUFFIX = 'Context';\n\nexport type RpcType = 'message' | 'event';\n\n/**\n * What is known about the message being handled. This is also what is logged\n * under the `rpc` key, apart from the payload, which `includePayload` adds.\n */\nexport interface RpcInfo {\n /**\n * `'message'` for `@MessagePattern`, where the caller is waiting for a reply,\n * `'event'` for `@EventPattern`, where nobody is.\n */\n type: RpcType;\n\n /** The pattern the handler is registered for, as given to the decorator. */\n pattern: string | number | symbol | Record<string, unknown> | undefined;\n\n /** Lowercased transport name, e.g. `'rmq'`, `'kafka'`, `'tcp'`. */\n transport: string | undefined;\n\n controller: string;\n\n handler: string;\n}\n\ntype StaticRpcInfo = Pick<RpcInfo, 'type' | 'pattern' | 'transport'>;\n\n// The pattern and the kind are fixed for a handler method, so they are read\n// once instead of on every message.\nconst staticInfoCache = new WeakMap<(...args: any[]) => any, StaticRpcInfo>();\n\nfunction readStaticInfo(\n handler: ((...args: any[]) => any) | undefined,\n): StaticRpcInfo {\n if (!handler || typeof Reflect.getMetadata !== 'function') {\n return { type: 'message', pattern: undefined, transport: undefined };\n }\n\n const patterns = Reflect.getMetadata(PATTERN_METADATA, handler);\n const kind = Reflect.getMetadata(PATTERN_HANDLER_METADATA, handler);\n const transport = Reflect.getMetadata(TRANSPORT_METADATA, handler);\n\n return {\n // A handler with no metadata at all is not necessarily a mistake — a custom\n // transport strategy can register one — so it is reported as a message,\n // which is both the more common kind and the safer default.\n type: kind === EVENT_HANDLER ? 'event' : 'message',\n pattern: Array.isArray(patterns)\n ? patterns.length > 1\n ? patterns\n : patterns[0]\n : patterns,\n transport:\n typeof transport === 'number' ? TRANSPORT_NAMES[transport] : undefined,\n };\n}\n\n/**\n * The transport a message actually arrived on, taken from the class of the\n * per-message context — `RmqContext`, `KafkaContext`, `TcpContext` and so on.\n * More reliable than the decorator metadata, which is only set when a handler\n * explicitly pins a transport.\n */\nfunction readTransport(context: ExecutionContext): string | undefined {\n let rpcContext: unknown;\n try {\n rpcContext = context.switchToRpc().getContext();\n } catch {\n return undefined;\n }\n\n const name = (rpcContext as { constructor?: { name?: string } })?.constructor\n ?.name;\n if (\n typeof name !== 'string' ||\n name === CONTEXT_SUFFIX ||\n !name.endsWith(CONTEXT_SUFFIX)\n ) {\n return undefined;\n }\n return name.slice(0, -CONTEXT_SUFFIX.length).toLowerCase();\n}\n\n/**\n * Describes the message a microservice handler was called with.\n *\n * Every callback of the `microservice` parameters receives an `ExecutionContext`\n * and nothing else, the way `pino-http`'s callbacks receive the request, so\n * this is how they reach the pattern, the transport and — most usefully — the\n * `type`, to tell a `@MessagePattern` from an `@EventPattern`:\n *\n * ```ts\n * customLogLevel: (ctx, err) =>\n * err ? 'error' : getRpcInfo(ctx).type === 'event' ? 'debug' : 'info',\n * ```\n *\n * Never throws: a context it cannot read reports a message with no pattern.\n */\nexport function getRpcInfo(context: ExecutionContext): RpcInfo {\n const handler = context.getHandler?.() as\n | ((...args: any[]) => any)\n | undefined;\n\n let staticInfo = handler && staticInfoCache.get(handler);\n if (!staticInfo) {\n staticInfo = readStaticInfo(handler);\n if (handler) {\n staticInfoCache.set(handler, staticInfo);\n }\n }\n\n return {\n type: staticInfo.type,\n pattern: staticInfo.pattern,\n transport: readTransport(context) ?? staticInfo.transport,\n controller: context.getClass?.()?.name ?? '',\n handler: handler?.name ?? '',\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nestjs-pino",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.0",
|
|
4
4
|
"description": "Pino logger for NestJS",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -45,17 +45,18 @@
|
|
|
45
45
|
"homepage": "https://github.com/iamolegga/nestjs-pino#readme",
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@biomejs/biome": "^2.5.11",
|
|
48
|
-
"@nestjs/common": "^12.0.
|
|
49
|
-
"@nestjs/core": "^12.0.
|
|
50
|
-
"@nestjs/
|
|
51
|
-
"@nestjs/platform-
|
|
52
|
-
"@nestjs/
|
|
48
|
+
"@nestjs/common": "^12.0.2",
|
|
49
|
+
"@nestjs/core": "^12.0.2",
|
|
50
|
+
"@nestjs/microservices": "^12.0.2",
|
|
51
|
+
"@nestjs/platform-express": "^12.0.2",
|
|
52
|
+
"@nestjs/platform-fastify": "^12.0.2",
|
|
53
|
+
"@nestjs/testing": "^12.0.2",
|
|
53
54
|
"@swc/core": "^1.16.1",
|
|
54
55
|
"@types/express": "^5.0.6",
|
|
55
56
|
"@types/memorystream": "^0.3.4",
|
|
56
57
|
"@types/node": "^26.4.0",
|
|
57
58
|
"@types/supertest": "^7.2.1",
|
|
58
|
-
"@vitest/coverage-v8": "^
|
|
59
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
59
60
|
"memorystream": "^0.3.1",
|
|
60
61
|
"pino": "^10.3.1",
|
|
61
62
|
"pino-http": "^11.0.0",
|
|
@@ -65,11 +66,11 @@
|
|
|
65
66
|
"supertest": "^7.2.2",
|
|
66
67
|
"typescript": "^7.0.2",
|
|
67
68
|
"unplugin-swc": "^1.5.11",
|
|
68
|
-
"vitest": "^
|
|
69
|
+
"vitest": "^5.0.0"
|
|
69
70
|
},
|
|
70
71
|
"peerDependencies": {
|
|
71
|
-
"@nestjs/common": "^11.0.8 || ^12.0.
|
|
72
|
-
"@nestjs/core": "^11.0.8 || ^12.0.
|
|
72
|
+
"@nestjs/common": "^11.0.8 || ^12.0.2",
|
|
73
|
+
"@nestjs/core": "^11.0.8 || ^12.0.2",
|
|
73
74
|
"pino": "^10.0.0",
|
|
74
75
|
"pino-http": "^11.0.0",
|
|
75
76
|
"rxjs": "^7.1.0"
|