nestjs-pino 5.2.1 → 5.3.0-alpha.0d3adc
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 +38 -3
- package/dist/cjs/LoggerModule.d.ts +11 -2
- package/dist/cjs/LoggerModule.js +26 -2
- package/dist/cjs/LoggerModule.js.map +1 -1
- package/dist/cjs/NativeLogger.d.ts +1 -0
- package/dist/cjs/NativeLogger.js +106 -9
- package/dist/cjs/NativeLogger.js.map +1 -1
- package/dist/esm/LoggerModule.d.ts +11 -2
- package/dist/esm/LoggerModule.js +28 -3
- package/dist/esm/LoggerModule.js.map +1 -1
- package/dist/esm/NativeLogger.d.ts +1 -0
- package/dist/esm/NativeLogger.js +106 -9
- package/dist/esm/NativeLogger.js.map +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -138,6 +138,17 @@ export class MyService {
|
|
|
138
138
|
> failure, no warning
|
|
139
139
|
> ([#3074](https://github.com/iamolegga/nestjs-pino/issues/3074)).
|
|
140
140
|
|
|
141
|
+
> [!NOTE]
|
|
142
|
+
> `@InjectPinoLogger(...)` does not work in a module loaded through
|
|
143
|
+
> [`LazyModuleLoader`](https://docs.nestjs.com/fundamentals/lazy-loading-modules),
|
|
144
|
+
> and fails with `Nest can't resolve dependencies of the YourService (?)` for the
|
|
145
|
+
> `PinoLogger:<context>` token. The providers behind those tokens are created by
|
|
146
|
+
> `forRoot(...)` out of the contexts the decorator has registered by then, and a
|
|
147
|
+
> lazy module is only evaluated once it is loaded — too late to be among them.
|
|
148
|
+
> Inject `PinoLogger` and call `setContext(...)`, as in the first constructor
|
|
149
|
+
> above: it needs no token of its own and works everywhere, lazy modules
|
|
150
|
+
> included ([#2069](https://github.com/iamolegga/nestjs-pino/issues/2069)).
|
|
151
|
+
|
|
141
152
|
### Drop-in replacement: NativeLogger
|
|
142
153
|
|
|
143
154
|
`NativeLogger` is a **drop-in replacement** for NestJS's built-in `ConsoleLogger`. It produces **identical JSON output** — same field names, same argument handling, same error format — but powered by pino with request context in every log.
|
|
@@ -178,10 +189,11 @@ That's it. Your existing `new Logger(MyService.name)` calls throughout the codeb
|
|
|
178
189
|
- Argument parsing: last string = context, rest = separate log entries
|
|
179
190
|
- Structured params: on NestJS 12, plain objects after the message are merged into a single `params` field on one entry (`ConsoleLoggerOptions.structuredParams`, on by default) — `this.logger.log('foo', { a: 1 }, { b: 2 })` → `{"message":"foo","params":{"a":1,"b":2}}`. On NestJS 11 each of them is a separate entry. `NativeLogger` follows the `ConsoleLogger` of the NestJS version you actually have, so out of the box there is nothing to configure — see below to override it
|
|
180
191
|
- Error handling: `this.logger.error('msg', stackTrace, 'Ctx')` → `{"message":"msg","stack":"Error: ...","context":"Ctx"}`
|
|
181
|
-
- Error objects: `this.logger.log(new Error('oops'))` →
|
|
182
|
-
-
|
|
192
|
+
- Error objects: on NestJS 12.1.1+ the first error passed with the message goes to the same entry as a structured `error` field with `name`, `message`, `stack`, own primitive properties such as `code`, and the `cause` chain and `AggregateError#errors` — `this.logger.error('Checkout failed', err)` → `{"message":"Checkout failed","error":{"name":"Error","message":"Payment failed","stack":"Error: ...","cause":{...}}}`. An error passed as the message itself, including the ones logged by NestJS's exception handlers, logs its own message: `this.logger.log(new Error('oops'))` → `{"message":"oops","error":{...}}`. Before 12.1.1 an error is logged as an entry of its own, with its stack as the message
|
|
193
|
+
- Fatal: on NestJS 12.1.1+ `fatal` parses its arguments like `error` — `this.logger.fatal('msg', stackTrace)` → `{"message":"msg","stack":"Error: ..."}`
|
|
194
|
+
- Function messages: a lazy message is logged as its result, a class as its name — `this.logger.debug(() => expensive())`. Unlike `ConsoleLogger` before NestJS 12.1.1, this works on every supported version
|
|
183
195
|
- Object messages: `this.logger.log({ foo: 'bar' })` → `{"message":{"foo":"bar"}}`
|
|
184
|
-
- Field names (with `nativeLoggerOptions`): `message`, `timestamp`, `pid`, `level`, `context`, `stack`
|
|
196
|
+
- Field names (with `nativeLoggerOptions`): `message`, `timestamp`, `pid`, `level`, `context`, `stack`, `error`
|
|
185
197
|
|
|
186
198
|
#### Keeping your ConsoleLogger options
|
|
187
199
|
|
|
@@ -500,6 +512,16 @@ class MyModule {}
|
|
|
500
512
|
|
|
501
513
|
See [pino.destination](https://github.com/pinojs/pino/blob/master/docs/api.md#pino-destination)
|
|
502
514
|
|
|
515
|
+
### Flushing on shutdown
|
|
516
|
+
|
|
517
|
+
An asynchronous destination, and likewise a [transport](https://github.com/pinojs/pino/blob/master/docs/transports.md), which runs in a worker thread, flushes its buffer on the process `exit` event. NestJS's [shutdown hooks](https://docs.nestjs.com/fundamentals/lifecycle-events#application-shutdown) end the process by re-raising the signal instead, which never emits `exit`: whatever was logged from `beforeApplicationShutdown` and `onApplicationShutdown` is lost, while `console.log` from the same places shows up. Since `@nestjs/core@11.1.10`, ask them to exit through `process.exit()` instead:
|
|
518
|
+
|
|
519
|
+
```ts
|
|
520
|
+
app.enableShutdownHooks(undefined, { useProcessExit: true });
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Mind that this changes the exit code (`0` instead of, say, `143` on `SIGTERM`), which an orchestrator may take into account.
|
|
524
|
+
|
|
503
525
|
## Testing a class that uses @InjectPinoLogger
|
|
504
526
|
|
|
505
527
|
This package exposes a `getLoggerToken()` function that returns a prepared injection token based on the provided context.
|
|
@@ -968,6 +990,8 @@ import { Logger } from 'nestjs-pino';
|
|
|
968
990
|
// ...
|
|
969
991
|
```
|
|
970
992
|
|
|
993
|
+
Call `app.useLogger()` before `app.init()` or `app.listen()`: since NestJS 12.1.1 the buffer is flushed by `init()` too, so with a logger set after `await app.init()` (as e2e tests often do) the startup logs have already been printed by the built-in logger.
|
|
994
|
+
|
|
971
995
|
Note that for [standalone applications](https://docs.nestjs.com/standalone-applications), buffering has to be [flushed using app.flushLogs()](https://github.com/nestjs/nest/blob/24e6c821a0859448646fd88831f20e4c5ae50980/packages/core/nest-application-context.ts#L136) manually after custom logger is ready to be used by NestJS (refer to [this issue](https://github.com/iamolegga/nestjs-pino/issues/553) for more details):
|
|
972
996
|
|
|
973
997
|
```ts
|
|
@@ -1025,6 +1049,17 @@ In NestJS <= 7 and `nestjs-pino@1` when you call `this.logger.log('foo', 'bar');
|
|
|
1025
1049
|
|
|
1026
1050
|
**A**: check out [genReqId field of pino-http](https://github.com/pinojs/pino-http#pinohttpopts-stream) that are set in `pinoHttp` field of `Params`
|
|
1027
1051
|
|
|
1052
|
+
With Fastify, though, that field is never used: Fastify assigns its own `request.id` before any middleware runs, `@fastify/middie` copies it onto the raw request, and `pino-http` keeps an existing `req.id` rather than generating one. Pass the generator to the adapter instead, and both Fastify and the logs use it:
|
|
1053
|
+
|
|
1054
|
+
```ts
|
|
1055
|
+
const app = await NestFactory.create<NestFastifyApplication>(
|
|
1056
|
+
AppModule,
|
|
1057
|
+
new FastifyAdapter({
|
|
1058
|
+
genReqId: (req) => req.headers['x-request-id']?.toString() ?? randomUUID(),
|
|
1059
|
+
}),
|
|
1060
|
+
);
|
|
1061
|
+
```
|
|
1062
|
+
|
|
1028
1063
|
---
|
|
1029
1064
|
|
|
1030
1065
|
**Q**: _How does it work?_
|
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
|
|
3
|
-
import { ApplicationConfig } from '@nestjs/core';
|
|
3
|
+
import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
|
|
4
4
|
import { type LoggerModuleAsyncParams, type Params } from './params.js';
|
|
5
5
|
export declare class LoggerModule implements NestModule {
|
|
6
6
|
private readonly params;
|
|
7
7
|
private readonly applicationConfig;
|
|
8
|
+
private readonly httpAdapterHost;
|
|
8
9
|
static forRoot<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params?: Params<IM, SR, CustomLevels>): DynamicModule;
|
|
9
10
|
static forRootAsync<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule;
|
|
10
|
-
constructor(params: Params, applicationConfig: ApplicationConfig);
|
|
11
|
+
constructor(params: Params, applicationConfig: ApplicationConfig, httpAdapterHost: HttpAdapterHost);
|
|
11
12
|
configure(consumer: MiddlewareConsumer): void;
|
|
13
|
+
/**
|
|
14
|
+
* Fastify hands its headers to the raw response in a single `writeHead`
|
|
15
|
+
* call, and Node keeps no record of headers passed that way: `getHeaders()`,
|
|
16
|
+
* which the `res` serializer reads, stays empty. Setting them on the raw
|
|
17
|
+
* response first makes `writeHead` merge into that record instead, so the
|
|
18
|
+
* request log carries the response headers as it does under Express.
|
|
19
|
+
*/
|
|
20
|
+
private exposeFastifyResponseHeaders;
|
|
12
21
|
/**
|
|
13
22
|
* A path excluded from the global prefix is served outside of it, while
|
|
14
23
|
* `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a
|
package/dist/cjs/LoggerModule.js
CHANGED
|
@@ -39,6 +39,7 @@ const DEFAULT_ROUTES = [{ path: '{/*splat}', method: common_1.RequestMethod.ALL
|
|
|
39
39
|
let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
40
40
|
params;
|
|
41
41
|
applicationConfig;
|
|
42
|
+
httpAdapterHost;
|
|
42
43
|
static forRoot(params) {
|
|
43
44
|
const paramsProvider = {
|
|
44
45
|
provide: params_js_1.PARAMS_PROVIDER_TOKEN,
|
|
@@ -97,9 +98,10 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
97
98
|
],
|
|
98
99
|
};
|
|
99
100
|
}
|
|
100
|
-
constructor(params, applicationConfig) {
|
|
101
|
+
constructor(params, applicationConfig, httpAdapterHost) {
|
|
101
102
|
this.params = params;
|
|
102
103
|
this.applicationConfig = applicationConfig;
|
|
104
|
+
this.httpAdapterHost = httpAdapterHost;
|
|
103
105
|
// Microservices have no middleware, so `configure` is never called for
|
|
104
106
|
// them. The hook is registered here instead, early enough that the message
|
|
105
107
|
// handlers being built later pick it up.
|
|
@@ -120,6 +122,28 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
120
122
|
else {
|
|
121
123
|
consumer.apply(...middlewares).forRoutes(...forRoutes);
|
|
122
124
|
}
|
|
125
|
+
this.exposeFastifyResponseHeaders();
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Fastify hands its headers to the raw response in a single `writeHead`
|
|
129
|
+
* call, and Node keeps no record of headers passed that way: `getHeaders()`,
|
|
130
|
+
* which the `res` serializer reads, stays empty. Setting them on the raw
|
|
131
|
+
* response first makes `writeHead` merge into that record instead, so the
|
|
132
|
+
* request log carries the response headers as it does under Express.
|
|
133
|
+
*/
|
|
134
|
+
exposeFastifyResponseHeaders() {
|
|
135
|
+
const adapter = this.httpAdapterHost.httpAdapter;
|
|
136
|
+
if (adapter?.getType() !== 'fastify')
|
|
137
|
+
return;
|
|
138
|
+
adapter
|
|
139
|
+
.getInstance()
|
|
140
|
+
.addHook('onSend', (_req, reply, _payload, done) => {
|
|
141
|
+
for (const [name, value] of Object.entries(reply.getHeaders())) {
|
|
142
|
+
if (value !== undefined)
|
|
143
|
+
reply.raw.setHeader(name, value);
|
|
144
|
+
}
|
|
145
|
+
done();
|
|
146
|
+
});
|
|
123
147
|
}
|
|
124
148
|
/**
|
|
125
149
|
* A path excluded from the global prefix is served outside of it, while
|
|
@@ -146,7 +170,7 @@ exports.LoggerModule = LoggerModule = LoggerModule_1 = __decorate([
|
|
|
146
170
|
(0, common_1.Global)(),
|
|
147
171
|
(0, common_1.Module)({ providers: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger], exports: [Logger_js_1.Logger, NativeLogger_js_1.NativeLogger] }),
|
|
148
172
|
__param(0, (0, common_1.Inject)(params_js_1.PARAMS_PROVIDER_TOKEN)),
|
|
149
|
-
__metadata("design:paramtypes", [Object, core_1.ApplicationConfig])
|
|
173
|
+
__metadata("design:paramtypes", [Object, core_1.ApplicationConfig, core_1.HttpAdapterHost])
|
|
150
174
|
], LoggerModule);
|
|
151
175
|
/**
|
|
152
176
|
* Exposes the very hook the module registers on its own, for the one case it
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAiD;AAEjD,+DAAoE;AACpE,2CAAqC;AACrC,uDAI2B;AAC3B,uDAAiD;AACjD,mDAA6C;AAC7C,2CAIqB;AACrB,mDAA2E;AAC3E,6CAA8C;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM,YAAY;IA6E2B,MAAM;IACrC,iBAAiB;IA7E7B,AAAP,MAAM,CAAC,OAAO,CAIZ,MAAqC;QACrC,MAAM,cAAc,GAA2C;YAC7D,OAAO,EAAE,iCAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,IAAA,iDAA2B,GAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB,EAAE,CAAC;QAE1C,OAAO;YACL,MAAM,gBAAc;YACpB,SAAS,EAAE;gBACT,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;YACD,OAAO,EAAE;gBACP,kBAAM;gBACN,8BAAY;gBACZ,GAAG,SAAS;gBACZ,0BAAU;gBACV,cAAc;gBACd,YAAY;aACb;SACF,CAAC;IACJ,CAAC;IAEM,AAAP,MAAM,CAAC,YAAY,CAIjB,MAAqD;QACrD,MAAM,cAAc,GAEhB;YACF,OAAO,EAAE,iCAAqB;YAC9B,UAAU,EAAE,MAAM,CAAC,UAAU;YAC7B,MAAM,EAAE,MAAM,CAAC,MAAM;SACtB,CAAC;QAEF,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,MAAM,UAAU,GAAG,IAAA,sCAAsB,EAAC,MAAM,CAAC,CAAC;IAElD,wEAAwE;IACxE,oBAAoB;IACpB,0BAAU,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,oBAAO,CAAC,GAAG,CAAC,IAAI,kBAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAkE;AAElE,+DAAoE;AACpE,2CAAqC;AACrC,uDAI2B;AAC3B,uDAAiD;AACjD,mDAA6C;AAC7C,2CAIqB;AACrB,mDAA2E;AAC3E,6CAA8C;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAA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ynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
@@ -15,6 +15,7 @@ export declare class NativeLogger implements LoggerService {
|
|
|
15
15
|
fatal(message: any, ...optionalParams: any[]): void;
|
|
16
16
|
private call;
|
|
17
17
|
private callError;
|
|
18
|
+
private logMessages;
|
|
18
19
|
private logSingleMessage;
|
|
19
20
|
private getContextAndMessagesToPrint;
|
|
20
21
|
private getContextAndStackAndMessagesToPrint;
|
package/dist/cjs/NativeLogger.js
CHANGED
|
@@ -28,6 +28,76 @@ const params_js_1 = require("./params.js");
|
|
|
28
28
|
* and works on every supported NestJS version when asked for explicitly.
|
|
29
29
|
*/
|
|
30
30
|
const HAS_STRUCTURED_PARAMS = 'stringifyParams' in common_1.ConsoleLogger.prototype;
|
|
31
|
+
/**
|
|
32
|
+
* NestJS v12.1.1 (nestjs/nest#17893) attaches the first `Error` passed with the
|
|
33
|
+
* message to that entry as a structured `error` field instead of logging it as
|
|
34
|
+
* an entry of its own, and parses the arguments of `fatal` the way it parses
|
|
35
|
+
* those of `error`. Detected the same way as above: `extractJsonError` is the
|
|
36
|
+
* method added for it. Unlike `structuredParams`, ConsoleLogger has no option
|
|
37
|
+
* for this, so neither does NativeLogger.
|
|
38
|
+
*/
|
|
39
|
+
const HAS_STRUCTURED_ERRORS = 'extractJsonError' in common_1.ConsoleLogger.prototype;
|
|
40
|
+
/**
|
|
41
|
+
* How many levels of nested errors (`cause`, `AggregateError#errors`) are
|
|
42
|
+
* serialized, as in `ConsoleLogger`.
|
|
43
|
+
*/
|
|
44
|
+
const MAX_ERROR_DEPTH = 5;
|
|
45
|
+
/**
|
|
46
|
+
* Mirrors `ConsoleLogger#resolveMessage`: a class resolves to its name, any
|
|
47
|
+
* other function is called (lazy message) and its result resolved again.
|
|
48
|
+
*/
|
|
49
|
+
function resolveMessage(message) {
|
|
50
|
+
if (typeof message !== 'function') {
|
|
51
|
+
return message;
|
|
52
|
+
}
|
|
53
|
+
if (Function.prototype.toString.call(message).startsWith('class ')) {
|
|
54
|
+
return message.name;
|
|
55
|
+
}
|
|
56
|
+
return resolveMessage(message());
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Mirrors `ConsoleLogger#serializeError`: `name`, `message`, `stack`, own
|
|
60
|
+
* primitive properties (e.g. `code`) and, recursively, `cause` and the
|
|
61
|
+
* `errors` of an `AggregateError`, up to a fixed depth.
|
|
62
|
+
*/
|
|
63
|
+
function serializeError(error, depth = 0, ancestors = new Set()) {
|
|
64
|
+
const serialized = {
|
|
65
|
+
name: error.name,
|
|
66
|
+
message: error.message,
|
|
67
|
+
stack: error.stack,
|
|
68
|
+
};
|
|
69
|
+
for (const [key, value] of Object.entries(error)) {
|
|
70
|
+
if (key in serialized || key === 'cause' || key === 'errors') {
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (value === null ||
|
|
74
|
+
(typeof value !== 'object' && typeof value !== 'function')) {
|
|
75
|
+
serialized[key] = value;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const serializeNested = (value) => {
|
|
79
|
+
if (!(value instanceof Error)) {
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
if (ancestors.has(value)) {
|
|
83
|
+
return '[Circular]';
|
|
84
|
+
}
|
|
85
|
+
if (depth + 1 > MAX_ERROR_DEPTH) {
|
|
86
|
+
return '[Truncated]';
|
|
87
|
+
}
|
|
88
|
+
return serializeError(value, depth + 1, ancestors);
|
|
89
|
+
};
|
|
90
|
+
ancestors.add(error);
|
|
91
|
+
if (error.cause !== undefined) {
|
|
92
|
+
serialized.cause = serializeNested(error.cause);
|
|
93
|
+
}
|
|
94
|
+
const errors = error.errors;
|
|
95
|
+
if (Array.isArray(errors)) {
|
|
96
|
+
serialized.errors = errors.map(serializeNested);
|
|
97
|
+
}
|
|
98
|
+
ancestors.delete(error);
|
|
99
|
+
return serialized;
|
|
100
|
+
}
|
|
31
101
|
/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */
|
|
32
102
|
function isPlainObject(value) {
|
|
33
103
|
if (typeof value !== 'object' || value === null) {
|
|
@@ -69,26 +139,50 @@ let NativeLogger = class NativeLogger {
|
|
|
69
139
|
this.call('warn', message, ...optionalParams);
|
|
70
140
|
}
|
|
71
141
|
error(message, ...optionalParams) {
|
|
72
|
-
this.callError(message, ...optionalParams);
|
|
142
|
+
this.callError('error', message, ...optionalParams);
|
|
73
143
|
}
|
|
74
144
|
fatal(message, ...optionalParams) {
|
|
75
|
-
|
|
145
|
+
if (HAS_STRUCTURED_ERRORS) {
|
|
146
|
+
this.callError('fatal', message, ...optionalParams);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
this.call('fatal', message, ...optionalParams);
|
|
150
|
+
}
|
|
76
151
|
}
|
|
77
152
|
call(level, message, ...optionalParams) {
|
|
78
153
|
const args = [message, ...optionalParams];
|
|
79
154
|
const { messages, context, params } = this.getContextAndMessagesToPrint(args);
|
|
80
|
-
|
|
81
|
-
this.logSingleMessage(level, msg, context, undefined, params);
|
|
82
|
-
}
|
|
155
|
+
this.logMessages(level, messages, context, undefined, params);
|
|
83
156
|
}
|
|
84
|
-
callError(message, ...optionalParams) {
|
|
157
|
+
callError(level, message, ...optionalParams) {
|
|
85
158
|
const args = [message, ...optionalParams];
|
|
86
159
|
const { messages, context, stack, params } = this.getContextAndStackAndMessagesToPrint(args);
|
|
87
|
-
|
|
88
|
-
|
|
160
|
+
this.logMessages(level, messages, context, stack, params);
|
|
161
|
+
}
|
|
162
|
+
logMessages(level, messages, context, stack, params) {
|
|
163
|
+
// Lazy messages must not be evaluated for a disabled level.
|
|
164
|
+
if (!this.logger.logger.isLevelEnabled(level)) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
messages = messages.map(resolveMessage);
|
|
168
|
+
// Mirrors `ConsoleLogger#extractJsonError`: the first error goes to the
|
|
169
|
+
// first entry; when it is the message itself, its message takes its place.
|
|
170
|
+
let error;
|
|
171
|
+
const errorIndex = HAS_STRUCTURED_ERRORS
|
|
172
|
+
? messages.findIndex((msg) => msg instanceof Error)
|
|
173
|
+
: -1;
|
|
174
|
+
if (errorIndex !== -1) {
|
|
175
|
+
error = messages[errorIndex];
|
|
176
|
+
messages =
|
|
177
|
+
errorIndex === 0
|
|
178
|
+
? [error.message, ...messages.slice(1)]
|
|
179
|
+
: messages.filter((_, index) => index !== errorIndex);
|
|
89
180
|
}
|
|
181
|
+
messages.forEach((msg, index) => {
|
|
182
|
+
this.logSingleMessage(level, msg, context, stack, params, index === 0 ? error : undefined);
|
|
183
|
+
});
|
|
90
184
|
}
|
|
91
|
-
logSingleMessage(level, message, context, stack, params) {
|
|
185
|
+
logSingleMessage(level, message, context, stack, params, error) {
|
|
92
186
|
// Flattened params go in first so that this logger's own fields win on a
|
|
93
187
|
// key collision. Collisions with pino's fields (the level, the timestamp,
|
|
94
188
|
// the message key, the base bindings) are not handled: pino does not
|
|
@@ -101,6 +195,9 @@ let NativeLogger = class NativeLogger {
|
|
|
101
195
|
if (stack) {
|
|
102
196
|
objArg.stack = stack;
|
|
103
197
|
}
|
|
198
|
+
if (error) {
|
|
199
|
+
objArg.error = serializeError(error);
|
|
200
|
+
}
|
|
104
201
|
if (params && !this.flattenParams) {
|
|
105
202
|
objArg.params = params;
|
|
106
203
|
}
|
|
@@ -1 +1 @@
|
|
|
1
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,EAAE,MAAM,EAAE,GACjC,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC;QAC1C,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YACzB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,WAAW,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAClD,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;YAC1E,OAAO;gBACL,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;gBAChD,OAAO;gBACP,MAAM;aACP,CAAC;QACJ,CAAC;QACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;IAEO,aAAa,CAAC,KAAc;QAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,yBAAyB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5E,CAAC;CACF,CAAA;;uBA3LY,YAAY;IADxB,IAAA,mBAAU,GAAE;IAQR,WAAA,IAAA,eAAM,EAAC,iCAAqB,CAAC,CAAA;qCADH,0BAAU;GAN5B,YAAY,CA2LxB","sourcesContent":["import {\n ConsoleLogger,\n Inject,\n Injectable,\n type LoggerService,\n} from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n/**\n * NestJS v12 collects plain objects passed after the message into a single\n * `params` field instead of logging each of them as its own entry\n * (`ConsoleLoggerOptions.structuredParams`, on by default). NativeLogger exists\n * to match whichever `ConsoleLogger` the application actually has, so detect\n * the capability rather than the version: `stringifyParams` is the method v12\n * added for exactly this, and NestJS exposes no version at runtime.\n *\n * This only decides the *default*; the collecting itself is implemented here\n * and works on every supported NestJS version when asked for explicitly.\n */\nconst HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;\n\n/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */\nfunction isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto === null) {\n return true;\n }\n const ctor =\n Object.hasOwn(proto, 'constructor') &&\n (proto as { constructor: unknown }).constructor;\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n );\n}\n\n@Injectable()\nexport class NativeLogger implements LoggerService {\n private readonly contextName: string;\n private readonly structuredParams: boolean;\n private readonly flattenParams: boolean;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext, nativeLogger }: Params,\n ) {\n this.contextName = renameContext || 'context';\n this.structuredParams =\n nativeLogger?.structuredParams ?? HAS_STRUCTURED_PARAMS;\n this.flattenParams = nativeLogger?.flattenParams ?? false;\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.callError(message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n this.call('fatal', message, ...optionalParams);\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage(level, msg, context, undefined, params);\n }\n }\n\n private callError(message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, stack, params } =\n this.getContextAndStackAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage('error', msg, context, stack, params);\n }\n }\n\n private logSingleMessage(\n level: Level,\n message: unknown,\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n ) {\n // Flattened params go in first so that this logger's own fields win on a\n // key collision. Collisions with pino's fields (the level, the timestamp,\n // the message key, the base bindings) are not handled: pino does not\n // deduplicate keys either, and their names depend on the pino options, so\n // any guard here would be guesswork.\n const objArg: Record<string, any> =\n params && this.flattenParams ? { ...params } : {};\n\n if (context) {\n objArg[this.contextName] = context;\n }\n\n if (stack) {\n objArg.stack = stack;\n }\n\n if (params && !this.flattenParams) {\n objArg.params = params;\n }\n\n if (typeof message === 'object' && message !== null) {\n if (message instanceof Error) {\n this.logger[level](objArg, message.stack || message.message);\n } else {\n this.logger[level](objArg, message as unknown as string);\n }\n } else {\n this.logger[level](objArg, String(message));\n }\n }\n\n private getContextAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n params?: Record<string, any>;\n } {\n if (args.length <= 1) {\n return { messages: args, context: undefined };\n }\n const lastElement = args[args.length - 1];\n const isContext = typeof lastElement === 'string';\n const context = isContext ? lastElement : undefined;\n const remainingArgs = isContext ? args.slice(0, args.length - 1) : args;\n\n if (!this.structuredParams) {\n return { messages: remainingArgs, context };\n }\n\n // The first argument is always the message; only plain objects after it\n // become params, everything else stays a message of its own.\n const messages: unknown[] = [remainingArgs[0]];\n const paramObjects: Record<string, any>[] = [];\n for (const arg of remainingArgs.slice(1)) {\n if (isPlainObject(arg)) {\n paramObjects.push(arg as Record<string, any>);\n } else {\n messages.push(arg);\n }\n }\n\n return {\n messages,\n context,\n params: paramObjects.length\n ? Object.assign({}, ...paramObjects)\n : undefined,\n };\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n stack?: string;\n params?: Record<string, any>;\n } {\n if (args.length === 2) {\n if (this.isStackFormat(args[1])) {\n return {\n messages: [args[0]],\n stack: args[1] as string,\n context: undefined,\n };\n }\n if (typeof args[1] === 'string') {\n return {\n messages: [args[0]],\n context: args[1],\n };\n }\n }\n\n const trailingArg = args[args.length - 1];\n if (args.length > 2 && this.isStackFormat(trailingArg)) {\n const { messages, context, params } = this.getContextAndMessagesToPrint(\n args.slice(0, -1),\n );\n return { messages, context, stack: trailingArg as string, params };\n }\n\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n if (messages.length <= 1) {\n return { messages, context, params };\n }\n\n const lastMessage = messages[messages.length - 1];\n if (typeof lastMessage === 'string' || typeof lastMessage === 'undefined') {\n return {\n stack: lastMessage,\n messages: messages.slice(0, messages.length - 1),\n context,\n params,\n };\n }\n return { messages, context, params };\n }\n\n private isStackFormat(value: unknown): boolean {\n if (typeof value !== 'string' && typeof value !== 'undefined') {\n return false;\n }\n return typeof value === 'string' && /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(value);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NativeLogger.js","sourceRoot":"","sources":["../../src/NativeLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAKwB;AAExB,mDAA6C;AAC7C,2CAA4D;AAE5D;;;;;;;;;;GAUG;AACH,MAAM,qBAAqB,GAAG,iBAAiB,IAAI,sBAAa,CAAC,SAAS,CAAC;AAE3E;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAG,kBAAkB,IAAI,sBAAa,CAAC,SAAS,CAAC;AAE5E;;;GAGG;AACH,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B;;;GAGG;AACH,SAAS,cAAc,CAAC,OAAgB;IACtC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,I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U,GAAE;IAQR,WAAA,IAAA,eAAM,EAAC,iCAAqB,CAAC,CAAA;qCADH,0BAAU;GAN5B,YAAY,CAuOxB","sourcesContent":["import {\n ConsoleLogger,\n Inject,\n Injectable,\n type LoggerService,\n} from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n/**\n * NestJS v12 collects plain objects passed after the message into a single\n * `params` field instead of logging each of them as its own entry\n * (`ConsoleLoggerOptions.structuredParams`, on by default). NativeLogger exists\n * to match whichever `ConsoleLogger` the application actually has, so detect\n * the capability rather than the version: `stringifyParams` is the method v12\n * added for exactly this, and NestJS exposes no version at runtime.\n *\n * This only decides the *default*; the collecting itself is implemented here\n * and works on every supported NestJS version when asked for explicitly.\n */\nconst HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;\n\n/**\n * NestJS v12.1.1 (nestjs/nest#17893) attaches the first `Error` passed with the\n * message to that entry as a structured `error` field instead of logging it as\n * an entry of its own, and parses the arguments of `fatal` the way it parses\n * those of `error`. Detected the same way as above: `extractJsonError` is the\n * method added for it. Unlike `structuredParams`, ConsoleLogger has no option\n * for this, so neither does NativeLogger.\n */\nconst HAS_STRUCTURED_ERRORS = 'extractJsonError' in ConsoleLogger.prototype;\n\n/**\n * How many levels of nested errors (`cause`, `AggregateError#errors`) are\n * serialized, as in `ConsoleLogger`.\n */\nconst MAX_ERROR_DEPTH = 5;\n\n/**\n * Mirrors `ConsoleLogger#resolveMessage`: a class resolves to its name, any\n * other function is called (lazy message) and its result resolved again.\n */\nfunction resolveMessage(message: unknown): unknown {\n if (typeof message !== 'function') {\n return message;\n }\n if (Function.prototype.toString.call(message).startsWith('class ')) {\n return message.name;\n }\n return resolveMessage(message());\n}\n\n/**\n * Mirrors `ConsoleLogger#serializeError`: `name`, `message`, `stack`, own\n * primitive properties (e.g. `code`) and, recursively, `cause` and the\n * `errors` of an `AggregateError`, up to a fixed depth.\n */\nfunction serializeError(\n error: Error,\n depth = 0,\n ancestors = new Set<Error>(),\n): Record<string, unknown> {\n const serialized: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n for (const [key, value] of Object.entries(error)) {\n if (key in serialized || key === 'cause' || key === 'errors') {\n continue;\n }\n if (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function')\n ) {\n serialized[key] = value;\n }\n }\n\n const serializeNested = (value: unknown) => {\n if (!(value instanceof Error)) {\n return value;\n }\n if (ancestors.has(value)) {\n return '[Circular]';\n }\n if (depth + 1 > MAX_ERROR_DEPTH) {\n return '[Truncated]';\n }\n return serializeError(value, depth + 1, ancestors);\n };\n\n ancestors.add(error);\n if (error.cause !== undefined) {\n serialized.cause = serializeNested(error.cause);\n }\n const errors = (error as Partial<AggregateError>).errors;\n if (Array.isArray(errors)) {\n serialized.errors = errors.map(serializeNested);\n }\n ancestors.delete(error);\n\n return serialized;\n}\n\n/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */\nfunction isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto === null) {\n return true;\n }\n const ctor =\n Object.hasOwn(proto, 'constructor') &&\n (proto as { constructor: unknown }).constructor;\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n );\n}\n\n@Injectable()\nexport class NativeLogger implements LoggerService {\n private readonly contextName: string;\n private readonly structuredParams: boolean;\n private readonly flattenParams: boolean;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext, nativeLogger }: Params,\n ) {\n this.contextName = renameContext || 'context';\n this.structuredParams =\n nativeLogger?.structuredParams ?? HAS_STRUCTURED_PARAMS;\n this.flattenParams = nativeLogger?.flattenParams ?? false;\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.callError('error', message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n if (HAS_STRUCTURED_ERRORS) {\n this.callError('fatal', message, ...optionalParams);\n } else {\n this.call('fatal', message, ...optionalParams);\n }\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n this.logMessages(level, messages, context, undefined, params);\n }\n\n private callError(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, stack, params } =\n this.getContextAndStackAndMessagesToPrint(args);\n this.logMessages(level, messages, context, stack, params);\n }\n\n private logMessages(\n level: Level,\n messages: unknown[],\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n ) {\n // Lazy messages must not be evaluated for a disabled level.\n if (!this.logger.logger.isLevelEnabled(level)) {\n return;\n }\n messages = messages.map(resolveMessage);\n\n // Mirrors `ConsoleLogger#extractJsonError`: the first error goes to the\n // first entry; when it is the message itself, its message takes its place.\n let error: Error | undefined;\n const errorIndex = HAS_STRUCTURED_ERRORS\n ? messages.findIndex((msg) => msg instanceof Error)\n : -1;\n if (errorIndex !== -1) {\n error = messages[errorIndex] as Error;\n messages =\n errorIndex === 0\n ? [error.message, ...messages.slice(1)]\n : messages.filter((_, index) => index !== errorIndex);\n }\n\n messages.forEach((msg, index) => {\n this.logSingleMessage(\n level,\n msg,\n context,\n stack,\n params,\n index === 0 ? error : undefined,\n );\n });\n }\n\n private logSingleMessage(\n level: Level,\n message: unknown,\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n error?: Error,\n ) {\n // Flattened params go in first so that this logger's own fields win on a\n // key collision. Collisions with pino's fields (the level, the timestamp,\n // the message key, the base bindings) are not handled: pino does not\n // deduplicate keys either, and their names depend on the pino options, so\n // any guard here would be guesswork.\n const objArg: Record<string, any> =\n params && this.flattenParams ? { ...params } : {};\n\n if (context) {\n objArg[this.contextName] = context;\n }\n\n if (stack) {\n objArg.stack = stack;\n }\n\n if (error) {\n objArg.error = serializeError(error);\n }\n\n if (params && !this.flattenParams) {\n objArg.params = params;\n }\n\n if (typeof message === 'object' && message !== null) {\n if (message instanceof Error) {\n this.logger[level](objArg, message.stack || message.message);\n } else {\n this.logger[level](objArg, message as unknown as string);\n }\n } else {\n this.logger[level](objArg, String(message));\n }\n }\n\n private getContextAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n params?: Record<string, any>;\n } {\n if (args.length <= 1) {\n return { messages: args, context: undefined };\n }\n const lastElement = args[args.length - 1];\n const isContext = typeof lastElement === 'string';\n const context = isContext ? lastElement : undefined;\n const remainingArgs = isContext ? args.slice(0, args.length - 1) : args;\n\n if (!this.structuredParams) {\n return { messages: remainingArgs, context };\n }\n\n // The first argument is always the message; only plain objects after it\n // become params, everything else stays a message of its own.\n const messages: unknown[] = [remainingArgs[0]];\n const paramObjects: Record<string, any>[] = [];\n for (const arg of remainingArgs.slice(1)) {\n if (isPlainObject(arg)) {\n paramObjects.push(arg as Record<string, any>);\n } else {\n messages.push(arg);\n }\n }\n\n return {\n messages,\n context,\n params: paramObjects.length\n ? Object.assign({}, ...paramObjects)\n : undefined,\n };\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n stack?: string;\n params?: Record<string, any>;\n } {\n if (args.length === 2) {\n if (this.isStackFormat(args[1])) {\n return {\n messages: [args[0]],\n stack: args[1] as string,\n context: undefined,\n };\n }\n if (typeof args[1] === 'string') {\n return {\n messages: [args[0]],\n context: args[1],\n };\n }\n }\n\n const trailingArg = args[args.length - 1];\n if (args.length > 2 && this.isStackFormat(trailingArg)) {\n const { messages, context, params } = this.getContextAndMessagesToPrint(\n args.slice(0, -1),\n );\n return { messages, context, stack: trailingArg as string, params };\n }\n\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n if (messages.length <= 1) {\n return { messages, context, params };\n }\n\n const lastMessage = messages[messages.length - 1];\n if (typeof lastMessage === 'string' || typeof lastMessage === 'undefined') {\n return {\n stack: lastMessage,\n messages: messages.slice(0, messages.length - 1),\n context,\n params,\n };\n }\n return { messages, context, params };\n }\n\n private isStackFormat(value: unknown): boolean {\n if (typeof value !== 'string' && typeof value !== 'undefined') {\n return false;\n }\n return typeof value === 'string' && /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(value);\n }\n}\n"]}
|
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
|
|
3
|
-
import { ApplicationConfig } from '@nestjs/core';
|
|
3
|
+
import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
|
|
4
4
|
import { type LoggerModuleAsyncParams, type Params } from './params.js';
|
|
5
5
|
export declare class LoggerModule implements NestModule {
|
|
6
6
|
private readonly params;
|
|
7
7
|
private readonly applicationConfig;
|
|
8
|
+
private readonly httpAdapterHost;
|
|
8
9
|
static forRoot<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params?: Params<IM, SR, CustomLevels>): DynamicModule;
|
|
9
10
|
static forRootAsync<IM = IncomingMessage, SR = ServerResponse, CustomLevels extends string = never>(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule;
|
|
10
|
-
constructor(params: Params, applicationConfig: ApplicationConfig);
|
|
11
|
+
constructor(params: Params, applicationConfig: ApplicationConfig, httpAdapterHost: HttpAdapterHost);
|
|
11
12
|
configure(consumer: MiddlewareConsumer): void;
|
|
13
|
+
/**
|
|
14
|
+
* Fastify hands its headers to the raw response in a single `writeHead`
|
|
15
|
+
* call, and Node keeps no record of headers passed that way: `getHeaders()`,
|
|
16
|
+
* which the `res` serializer reads, stays empty. Setting them on the raw
|
|
17
|
+
* response first makes `writeHead` merge into that record instead, so the
|
|
18
|
+
* request log carries the response headers as it does under Express.
|
|
19
|
+
*/
|
|
20
|
+
private exposeFastifyResponseHeaders;
|
|
12
21
|
/**
|
|
13
22
|
* A path excluded from the global prefix is served outside of it, while
|
|
14
23
|
* `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a
|
package/dist/esm/LoggerModule.js
CHANGED
|
@@ -12,7 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
12
12
|
};
|
|
13
13
|
var LoggerModule_1;
|
|
14
14
|
import { Global, Inject, Module, RequestMethod, } from '@nestjs/common';
|
|
15
|
-
import { ApplicationConfig } from '@nestjs/core';
|
|
15
|
+
import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
|
|
16
16
|
import { createProvidersForDecorated } from './InjectPinoLogger.js';
|
|
17
17
|
import { Logger } from './Logger.js';
|
|
18
18
|
import { getMicroserviceHook, PINO_PRE_REQUEST_HOOK, registerMicroserviceHook, } from './microservice.js';
|
|
@@ -36,6 +36,7 @@ const DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];
|
|
|
36
36
|
let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
37
37
|
params;
|
|
38
38
|
applicationConfig;
|
|
39
|
+
httpAdapterHost;
|
|
39
40
|
static forRoot(params) {
|
|
40
41
|
const paramsProvider = {
|
|
41
42
|
provide: PARAMS_PROVIDER_TOKEN,
|
|
@@ -94,9 +95,10 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
94
95
|
],
|
|
95
96
|
};
|
|
96
97
|
}
|
|
97
|
-
constructor(params, applicationConfig) {
|
|
98
|
+
constructor(params, applicationConfig, httpAdapterHost) {
|
|
98
99
|
this.params = params;
|
|
99
100
|
this.applicationConfig = applicationConfig;
|
|
101
|
+
this.httpAdapterHost = httpAdapterHost;
|
|
100
102
|
// Microservices have no middleware, so `configure` is never called for
|
|
101
103
|
// them. The hook is registered here instead, early enough that the message
|
|
102
104
|
// handlers being built later pick it up.
|
|
@@ -117,6 +119,28 @@ let LoggerModule = LoggerModule_1 = class LoggerModule {
|
|
|
117
119
|
else {
|
|
118
120
|
consumer.apply(...middlewares).forRoutes(...forRoutes);
|
|
119
121
|
}
|
|
122
|
+
this.exposeFastifyResponseHeaders();
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Fastify hands its headers to the raw response in a single `writeHead`
|
|
126
|
+
* call, and Node keeps no record of headers passed that way: `getHeaders()`,
|
|
127
|
+
* which the `res` serializer reads, stays empty. Setting them on the raw
|
|
128
|
+
* response first makes `writeHead` merge into that record instead, so the
|
|
129
|
+
* request log carries the response headers as it does under Express.
|
|
130
|
+
*/
|
|
131
|
+
exposeFastifyResponseHeaders() {
|
|
132
|
+
const adapter = this.httpAdapterHost.httpAdapter;
|
|
133
|
+
if (adapter?.getType() !== 'fastify')
|
|
134
|
+
return;
|
|
135
|
+
adapter
|
|
136
|
+
.getInstance()
|
|
137
|
+
.addHook('onSend', (_req, reply, _payload, done) => {
|
|
138
|
+
for (const [name, value] of Object.entries(reply.getHeaders())) {
|
|
139
|
+
if (value !== undefined)
|
|
140
|
+
reply.raw.setHeader(name, value);
|
|
141
|
+
}
|
|
142
|
+
done();
|
|
143
|
+
});
|
|
120
144
|
}
|
|
121
145
|
/**
|
|
122
146
|
* A path excluded from the global prefix is served outside of it, while
|
|
@@ -142,7 +166,8 @@ LoggerModule = LoggerModule_1 = __decorate([
|
|
|
142
166
|
Global(),
|
|
143
167
|
Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] }),
|
|
144
168
|
__param(0, Inject(PARAMS_PROVIDER_TOKEN)),
|
|
145
|
-
__metadata("design:paramtypes", [Object, ApplicationConfig
|
|
169
|
+
__metadata("design:paramtypes", [Object, ApplicationConfig,
|
|
170
|
+
HttpAdapterHost])
|
|
146
171
|
], LoggerModule);
|
|
147
172
|
export { LoggerModule };
|
|
148
173
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAEL,MAAM,EACN,MAAM,EAEN,MAAM,EAGN,aAAa,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAEL,qBAAqB,GAEtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE9C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,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,qBAAqB;YAC9B,QAAQ,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC;QAEF,MAAM,SAAS,GAAG,2BAA2B,EAAE,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB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AC;QAED,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store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AClC,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,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger.js';\nimport { Logger } from './Logger.js';\nimport {\n getMicroserviceHook,\n PINO_PRE_REQUEST_HOOK,\n registerMicroserviceHook,\n} from './microservice.js';\nimport { NativeLogger } from './NativeLogger.js';\nimport { PinoLogger } from './PinoLogger.js';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params.js';\nimport { ensureLoggerMiddleware, ensureRootLogger } from './rootLogger.js';\nimport { Store, storage } from './storage.js';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n const hookProvider = createHookProvider();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n hookProvider,\n ],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n private readonly httpAdapterHost: HttpAdapterHost,\n ) {\n // Microservices have no middleware, so `configure` is never called for\n // them. The hook is registered here instead, early enough that the message\n // handlers being built later pick it up.\n if (params.microservice) {\n ensureRootLogger(params.pinoHttp);\n registerMicroserviceHook(applicationConfig, params);\n }\n }\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n\n this.exposeFastifyResponseHeaders();\n }\n\n /**\n * Fastify hands its headers to the raw response in a single `writeHead`\n * call, and Node keeps no record of headers passed that way: `getHeaders()`,\n * which the `res` serializer reads, stays empty. Setting them on the raw\n * response first makes `writeHead` merge into that record instead, so the\n * request log carries the response headers as it does under Express.\n */\n private exposeFastifyResponseHeaders() {\n const adapter = this.httpAdapterHost.httpAdapter;\n if (adapter?.getType() !== 'fastify') return;\n\n adapter\n .getInstance()\n .addHook(\n 'onSend',\n (\n _req: unknown,\n reply: FastifyReplyLike,\n _payload: unknown,\n done: () => void,\n ) => {\n for (const [name, value] of Object.entries(reply.getHeaders())) {\n if (value !== undefined) reply.raw.setHeader(name, value);\n }\n done();\n },\n );\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\n/** The part of fastify's `Reply` used here, spelled out to not depend on it. */\ntype FastifyReplyLike = {\n raw: ServerResponse;\n getHeaders(): Record<string, number | string | string[] | undefined>;\n};\n\n/**\n * Exposes the very hook the module registers on its own, for the one case it\n * cannot reach: a hybrid application connected without `inheritAppConfig`.\n */\nfunction createHookProvider(): Provider {\n return {\n provide: PINO_PRE_REQUEST_HOOK,\n useFactory: (params: Params) => {\n ensureRootLogger(params.pinoHttp);\n return getMicroserviceHook(params);\n },\n inject: [PARAMS_PROVIDER_TOKEN],\n };\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
|
|
@@ -15,6 +15,7 @@ export declare class NativeLogger implements LoggerService {
|
|
|
15
15
|
fatal(message: any, ...optionalParams: any[]): void;
|
|
16
16
|
private call;
|
|
17
17
|
private callError;
|
|
18
|
+
private logMessages;
|
|
18
19
|
private logSingleMessage;
|
|
19
20
|
private getContextAndMessagesToPrint;
|
|
20
21
|
private getContextAndStackAndMessagesToPrint;
|
package/dist/esm/NativeLogger.js
CHANGED
|
@@ -25,6 +25,76 @@ import { PARAMS_PROVIDER_TOKEN } from './params.js';
|
|
|
25
25
|
* and works on every supported NestJS version when asked for explicitly.
|
|
26
26
|
*/
|
|
27
27
|
const HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;
|
|
28
|
+
/**
|
|
29
|
+
* NestJS v12.1.1 (nestjs/nest#17893) attaches the first `Error` passed with the
|
|
30
|
+
* message to that entry as a structured `error` field instead of logging it as
|
|
31
|
+
* an entry of its own, and parses the arguments of `fatal` the way it parses
|
|
32
|
+
* those of `error`. Detected the same way as above: `extractJsonError` is the
|
|
33
|
+
* method added for it. Unlike `structuredParams`, ConsoleLogger has no option
|
|
34
|
+
* for this, so neither does NativeLogger.
|
|
35
|
+
*/
|
|
36
|
+
const HAS_STRUCTURED_ERRORS = 'extractJsonError' in ConsoleLogger.prototype;
|
|
37
|
+
/**
|
|
38
|
+
* How many levels of nested errors (`cause`, `AggregateError#errors`) are
|
|
39
|
+
* serialized, as in `ConsoleLogger`.
|
|
40
|
+
*/
|
|
41
|
+
const MAX_ERROR_DEPTH = 5;
|
|
42
|
+
/**
|
|
43
|
+
* Mirrors `ConsoleLogger#resolveMessage`: a class resolves to its name, any
|
|
44
|
+
* other function is called (lazy message) and its result resolved again.
|
|
45
|
+
*/
|
|
46
|
+
function resolveMessage(message) {
|
|
47
|
+
if (typeof message !== 'function') {
|
|
48
|
+
return message;
|
|
49
|
+
}
|
|
50
|
+
if (Function.prototype.toString.call(message).startsWith('class ')) {
|
|
51
|
+
return message.name;
|
|
52
|
+
}
|
|
53
|
+
return resolveMessage(message());
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Mirrors `ConsoleLogger#serializeError`: `name`, `message`, `stack`, own
|
|
57
|
+
* primitive properties (e.g. `code`) and, recursively, `cause` and the
|
|
58
|
+
* `errors` of an `AggregateError`, up to a fixed depth.
|
|
59
|
+
*/
|
|
60
|
+
function serializeError(error, depth = 0, ancestors = new Set()) {
|
|
61
|
+
const serialized = {
|
|
62
|
+
name: error.name,
|
|
63
|
+
message: error.message,
|
|
64
|
+
stack: error.stack,
|
|
65
|
+
};
|
|
66
|
+
for (const [key, value] of Object.entries(error)) {
|
|
67
|
+
if (key in serialized || key === 'cause' || key === 'errors') {
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (value === null ||
|
|
71
|
+
(typeof value !== 'object' && typeof value !== 'function')) {
|
|
72
|
+
serialized[key] = value;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const serializeNested = (value) => {
|
|
76
|
+
if (!(value instanceof Error)) {
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
if (ancestors.has(value)) {
|
|
80
|
+
return '[Circular]';
|
|
81
|
+
}
|
|
82
|
+
if (depth + 1 > MAX_ERROR_DEPTH) {
|
|
83
|
+
return '[Truncated]';
|
|
84
|
+
}
|
|
85
|
+
return serializeError(value, depth + 1, ancestors);
|
|
86
|
+
};
|
|
87
|
+
ancestors.add(error);
|
|
88
|
+
if (error.cause !== undefined) {
|
|
89
|
+
serialized.cause = serializeNested(error.cause);
|
|
90
|
+
}
|
|
91
|
+
const errors = error.errors;
|
|
92
|
+
if (Array.isArray(errors)) {
|
|
93
|
+
serialized.errors = errors.map(serializeNested);
|
|
94
|
+
}
|
|
95
|
+
ancestors.delete(error);
|
|
96
|
+
return serialized;
|
|
97
|
+
}
|
|
28
98
|
/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */
|
|
29
99
|
function isPlainObject(value) {
|
|
30
100
|
if (typeof value !== 'object' || value === null) {
|
|
@@ -66,26 +136,50 @@ let NativeLogger = class NativeLogger {
|
|
|
66
136
|
this.call('warn', message, ...optionalParams);
|
|
67
137
|
}
|
|
68
138
|
error(message, ...optionalParams) {
|
|
69
|
-
this.callError(message, ...optionalParams);
|
|
139
|
+
this.callError('error', message, ...optionalParams);
|
|
70
140
|
}
|
|
71
141
|
fatal(message, ...optionalParams) {
|
|
72
|
-
|
|
142
|
+
if (HAS_STRUCTURED_ERRORS) {
|
|
143
|
+
this.callError('fatal', message, ...optionalParams);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
this.call('fatal', message, ...optionalParams);
|
|
147
|
+
}
|
|
73
148
|
}
|
|
74
149
|
call(level, message, ...optionalParams) {
|
|
75
150
|
const args = [message, ...optionalParams];
|
|
76
151
|
const { messages, context, params } = this.getContextAndMessagesToPrint(args);
|
|
77
|
-
|
|
78
|
-
this.logSingleMessage(level, msg, context, undefined, params);
|
|
79
|
-
}
|
|
152
|
+
this.logMessages(level, messages, context, undefined, params);
|
|
80
153
|
}
|
|
81
|
-
callError(message, ...optionalParams) {
|
|
154
|
+
callError(level, message, ...optionalParams) {
|
|
82
155
|
const args = [message, ...optionalParams];
|
|
83
156
|
const { messages, context, stack, params } = this.getContextAndStackAndMessagesToPrint(args);
|
|
84
|
-
|
|
85
|
-
|
|
157
|
+
this.logMessages(level, messages, context, stack, params);
|
|
158
|
+
}
|
|
159
|
+
logMessages(level, messages, context, stack, params) {
|
|
160
|
+
// Lazy messages must not be evaluated for a disabled level.
|
|
161
|
+
if (!this.logger.logger.isLevelEnabled(level)) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
messages = messages.map(resolveMessage);
|
|
165
|
+
// Mirrors `ConsoleLogger#extractJsonError`: the first error goes to the
|
|
166
|
+
// first entry; when it is the message itself, its message takes its place.
|
|
167
|
+
let error;
|
|
168
|
+
const errorIndex = HAS_STRUCTURED_ERRORS
|
|
169
|
+
? messages.findIndex((msg) => msg instanceof Error)
|
|
170
|
+
: -1;
|
|
171
|
+
if (errorIndex !== -1) {
|
|
172
|
+
error = messages[errorIndex];
|
|
173
|
+
messages =
|
|
174
|
+
errorIndex === 0
|
|
175
|
+
? [error.message, ...messages.slice(1)]
|
|
176
|
+
: messages.filter((_, index) => index !== errorIndex);
|
|
86
177
|
}
|
|
178
|
+
messages.forEach((msg, index) => {
|
|
179
|
+
this.logSingleMessage(level, msg, context, stack, params, index === 0 ? error : undefined);
|
|
180
|
+
});
|
|
87
181
|
}
|
|
88
|
-
logSingleMessage(level, message, context, stack, params) {
|
|
182
|
+
logSingleMessage(level, message, context, stack, params, error) {
|
|
89
183
|
// Flattened params go in first so that this logger's own fields win on a
|
|
90
184
|
// key collision. Collisions with pino's fields (the level, the timestamp,
|
|
91
185
|
// the message key, the base bindings) are not handled: pino does not
|
|
@@ -98,6 +192,9 @@ let NativeLogger = class NativeLogger {
|
|
|
98
192
|
if (stack) {
|
|
99
193
|
objArg.stack = stack;
|
|
100
194
|
}
|
|
195
|
+
if (error) {
|
|
196
|
+
objArg.error = serializeError(error);
|
|
197
|
+
}
|
|
101
198
|
if (params && !this.flattenParams) {
|
|
102
199
|
objArg.params = params;
|
|
103
200
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NativeLogger.js","sourceRoot":"","sources":["../../src/NativeLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,aAAa,EACb,MAAM,EACN,UAAU,GAEX,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAU,MAAM,aAAa,CAAC;AAE5D;;;;;;;;;;GAUG;AACH,MAAM,qBAAqB,GAAG,iBAAiB,IAAI,aAAa,CAAC,SAAS,CAAC;AAE3E,8EAA8E;AAC9E,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,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,WAAW,EAAE,CAAC;YAC1E,OAAO;gBACL,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;gBAChD,OAAO;gBACP,MAAM;aACP,CAAC;QACJ,CAAC;QACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;IAEO,aAAa,CAAC,KAAc;QAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,yBAAyB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5E,CAAC;CACF,CAAA;AA3LY,YAAY;IADxB,UAAU,EAAE;IAQR,WAAA,MAAM,CAAC,qBAAqB,CAAC,CAAA;qCADH,UAAU;GAN5B,YAAY,CA2LxB","sourcesContent":["import {\n ConsoleLogger,\n Inject,\n Injectable,\n type LoggerService,\n} from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n/**\n * NestJS v12 collects plain objects passed after the message into a single\n * `params` field instead of logging each of them as its own entry\n * (`ConsoleLoggerOptions.structuredParams`, on by default). NativeLogger exists\n * to match whichever `ConsoleLogger` the application actually has, so detect\n * the capability rather than the version: `stringifyParams` is the method v12\n * added for exactly this, and NestJS exposes no version at runtime.\n *\n * This only decides the *default*; the collecting itself is implemented here\n * and works on every supported NestJS version when asked for explicitly.\n */\nconst HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;\n\n/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */\nfunction isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto === null) {\n return true;\n }\n const ctor =\n Object.hasOwn(proto, 'constructor') &&\n (proto as { constructor: unknown }).constructor;\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n );\n}\n\n@Injectable()\nexport class NativeLogger implements LoggerService {\n private readonly contextName: string;\n private readonly structuredParams: boolean;\n private readonly flattenParams: boolean;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext, nativeLogger }: Params,\n ) {\n this.contextName = renameContext || 'context';\n this.structuredParams =\n nativeLogger?.structuredParams ?? HAS_STRUCTURED_PARAMS;\n this.flattenParams = nativeLogger?.flattenParams ?? false;\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.callError(message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n this.call('fatal', message, ...optionalParams);\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage(level, msg, context, undefined, params);\n }\n }\n\n private callError(message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, stack, params } =\n this.getContextAndStackAndMessagesToPrint(args);\n for (const msg of messages) {\n this.logSingleMessage('error', msg, context, stack, params);\n }\n }\n\n private logSingleMessage(\n level: Level,\n message: unknown,\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n ) {\n // Flattened params go in first so that this logger's own fields win on a\n // key collision. Collisions with pino's fields (the level, the timestamp,\n // the message key, the base bindings) are not handled: pino does not\n // deduplicate keys either, and their names depend on the pino options, so\n // any guard here would be guesswork.\n const objArg: Record<string, any> =\n params && this.flattenParams ? { ...params } : {};\n\n if (context) {\n objArg[this.contextName] = context;\n }\n\n if (stack) {\n objArg.stack = stack;\n }\n\n if (params && !this.flattenParams) {\n objArg.params = params;\n }\n\n if (typeof message === 'object' && message !== null) {\n if (message instanceof Error) {\n this.logger[level](objArg, message.stack || message.message);\n } else {\n this.logger[level](objArg, message as unknown as string);\n }\n } else {\n this.logger[level](objArg, String(message));\n }\n }\n\n private getContextAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n params?: Record<string, any>;\n } {\n if (args.length <= 1) {\n return { messages: args, context: undefined };\n }\n const lastElement = args[args.length - 1];\n const isContext = typeof lastElement === 'string';\n const context = isContext ? lastElement : undefined;\n const remainingArgs = isContext ? args.slice(0, args.length - 1) : args;\n\n if (!this.structuredParams) {\n return { messages: remainingArgs, context };\n }\n\n // The first argument is always the message; only plain objects after it\n // become params, everything else stays a message of its own.\n const messages: unknown[] = [remainingArgs[0]];\n const paramObjects: Record<string, any>[] = [];\n for (const arg of remainingArgs.slice(1)) {\n if (isPlainObject(arg)) {\n paramObjects.push(arg as Record<string, any>);\n } else {\n messages.push(arg);\n }\n }\n\n return {\n messages,\n context,\n params: paramObjects.length\n ? Object.assign({}, ...paramObjects)\n : undefined,\n };\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n stack?: string;\n params?: Record<string, any>;\n } {\n if (args.length === 2) {\n if (this.isStackFormat(args[1])) {\n return {\n messages: [args[0]],\n stack: args[1] as string,\n context: undefined,\n };\n }\n if (typeof args[1] === 'string') {\n return {\n messages: [args[0]],\n context: args[1],\n };\n }\n }\n\n const trailingArg = args[args.length - 1];\n if (args.length > 2 && this.isStackFormat(trailingArg)) {\n const { messages, context, params } = this.getContextAndMessagesToPrint(\n args.slice(0, -1),\n );\n return { messages, context, stack: trailingArg as string, params };\n }\n\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n if (messages.length <= 1) {\n return { messages, context, params };\n }\n\n const lastMessage = messages[messages.length - 1];\n if (typeof lastMessage === 'string' || typeof lastMessage === 'undefined') {\n return {\n stack: lastMessage,\n messages: messages.slice(0, messages.length - 1),\n context,\n params,\n };\n }\n return { messages, context, params };\n }\n\n private isStackFormat(value: unknown): boolean {\n if (typeof value !== 'string' && typeof value !== 'undefined') {\n return false;\n }\n return typeof value === 'string' && /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(value);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NativeLogger.js","sourceRoot":"","sources":["../../src/NativeLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,aAAa,EACb,MAAM,EACN,UAAU,GAEX,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAU,MAAM,aAAa,CAAC;AAE5D;;;;;;;;;;GAUG;AACH,MAAM,qBAAqB,GAAG,iBAAiB,IAAI,aAAa,CAAC,SAAS,CAAC;AAE3E;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAG,kBAAkB,IAAI,aAAa,CAAC,SAAS,CAAC;AAE5E;;;GAGG;AACH,MAAM,eAAe,GAAG,CAAC,CAAC;AAE1B;;;GAGG;AACH,SAAS,cAAc,CAAC,OAAgB;IACtC,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QACnE,OAAO,OAAO,CAAC,IAAI,CAAC;IACtB,CAAC;IACD,OAAO,cAAc,CAAC,OAAO,EAAE,CAAC,CAAC;AACnC,CAAC;AAED;;;;GAIG;A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E,OAAO,EAAE,KAAK,EAAE,WAAqB,EAAE,MAAM,EAAE,CAAC;QACrE,CAAC;QAED,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,GACjC,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC;QAC1C,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YACzB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,WAAW,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAClD,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE,CAAC;YAC1E,OAAO;gBACL,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;gBAChD,OAAO;gBACP,MAAM;aACP,CAAC;QACJ,CAAC;QACD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;IAEO,aAAa,CAAC,KAAc;QAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;YAC9D,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,yBAAyB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5E,CAAC;CACF,CAAA;AAvOY,YAAY;IADxB,UAAU,EAAE;IAQR,WAAA,MAAM,CAAC,qBAAqB,CAAC,CAAA;qCADH,UAAU;GAN5B,YAAY,CAuOxB","sourcesContent":["import {\n ConsoleLogger,\n Inject,\n Injectable,\n type LoggerService,\n} from '@nestjs/common';\nimport { Level } from 'pino';\nimport { PinoLogger } from './PinoLogger.js';\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params.js';\n\n/**\n * NestJS v12 collects plain objects passed after the message into a single\n * `params` field instead of logging each of them as its own entry\n * (`ConsoleLoggerOptions.structuredParams`, on by default). NativeLogger exists\n * to match whichever `ConsoleLogger` the application actually has, so detect\n * the capability rather than the version: `stringifyParams` is the method v12\n * added for exactly this, and NestJS exposes no version at runtime.\n *\n * This only decides the *default*; the collecting itself is implemented here\n * and works on every supported NestJS version when asked for explicitly.\n */\nconst HAS_STRUCTURED_PARAMS = 'stringifyParams' in ConsoleLogger.prototype;\n\n/**\n * NestJS v12.1.1 (nestjs/nest#17893) attaches the first `Error` passed with the\n * message to that entry as a structured `error` field instead of logging it as\n * an entry of its own, and parses the arguments of `fatal` the way it parses\n * those of `error`. Detected the same way as above: `extractJsonError` is the\n * method added for it. Unlike `structuredParams`, ConsoleLogger has no option\n * for this, so neither does NativeLogger.\n */\nconst HAS_STRUCTURED_ERRORS = 'extractJsonError' in ConsoleLogger.prototype;\n\n/**\n * How many levels of nested errors (`cause`, `AggregateError#errors`) are\n * serialized, as in `ConsoleLogger`.\n */\nconst MAX_ERROR_DEPTH = 5;\n\n/**\n * Mirrors `ConsoleLogger#resolveMessage`: a class resolves to its name, any\n * other function is called (lazy message) and its result resolved again.\n */\nfunction resolveMessage(message: unknown): unknown {\n if (typeof message !== 'function') {\n return message;\n }\n if (Function.prototype.toString.call(message).startsWith('class ')) {\n return message.name;\n }\n return resolveMessage(message());\n}\n\n/**\n * Mirrors `ConsoleLogger#serializeError`: `name`, `message`, `stack`, own\n * primitive properties (e.g. `code`) and, recursively, `cause` and the\n * `errors` of an `AggregateError`, up to a fixed depth.\n */\nfunction serializeError(\n error: Error,\n depth = 0,\n ancestors = new Set<Error>(),\n): Record<string, unknown> {\n const serialized: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n for (const [key, value] of Object.entries(error)) {\n if (key in serialized || key === 'cause' || key === 'errors') {\n continue;\n }\n if (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function')\n ) {\n serialized[key] = value;\n }\n }\n\n const serializeNested = (value: unknown) => {\n if (!(value instanceof Error)) {\n return value;\n }\n if (ancestors.has(value)) {\n return '[Circular]';\n }\n if (depth + 1 > MAX_ERROR_DEPTH) {\n return '[Truncated]';\n }\n return serializeError(value, depth + 1, ancestors);\n };\n\n ancestors.add(error);\n if (error.cause !== undefined) {\n serialized.cause = serializeNested(error.cause);\n }\n const errors = (error as Partial<AggregateError>).errors;\n if (Array.isArray(errors)) {\n serialized.errors = errors.map(serializeNested);\n }\n ancestors.delete(error);\n\n return serialized;\n}\n\n/** Mirrors `isPlainObject` from `@nestjs/common`, which is not public API. */\nfunction isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto === null) {\n return true;\n }\n const ctor =\n Object.hasOwn(proto, 'constructor') &&\n (proto as { constructor: unknown }).constructor;\n return (\n typeof ctor === 'function' &&\n ctor instanceof ctor &&\n Function.prototype.toString.call(ctor) ===\n Function.prototype.toString.call(Object)\n );\n}\n\n@Injectable()\nexport class NativeLogger implements LoggerService {\n private readonly contextName: string;\n private readonly structuredParams: boolean;\n private readonly flattenParams: boolean;\n\n constructor(\n protected readonly logger: PinoLogger,\n @Inject(PARAMS_PROVIDER_TOKEN) { renameContext, nativeLogger }: Params,\n ) {\n this.contextName = renameContext || 'context';\n this.structuredParams =\n nativeLogger?.structuredParams ?? HAS_STRUCTURED_PARAMS;\n this.flattenParams = nativeLogger?.flattenParams ?? false;\n }\n\n verbose(message: any, ...optionalParams: any[]) {\n this.call('trace', message, ...optionalParams);\n }\n\n debug(message: any, ...optionalParams: any[]) {\n this.call('debug', message, ...optionalParams);\n }\n\n log(message: any, ...optionalParams: any[]) {\n this.call('info', message, ...optionalParams);\n }\n\n warn(message: any, ...optionalParams: any[]) {\n this.call('warn', message, ...optionalParams);\n }\n\n error(message: any, ...optionalParams: any[]) {\n this.callError('error', message, ...optionalParams);\n }\n\n fatal(message: any, ...optionalParams: any[]) {\n if (HAS_STRUCTURED_ERRORS) {\n this.callError('fatal', message, ...optionalParams);\n } else {\n this.call('fatal', message, ...optionalParams);\n }\n }\n\n private call(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n this.logMessages(level, messages, context, undefined, params);\n }\n\n private callError(level: Level, message: any, ...optionalParams: any[]) {\n const args = [message, ...optionalParams];\n const { messages, context, stack, params } =\n this.getContextAndStackAndMessagesToPrint(args);\n this.logMessages(level, messages, context, stack, params);\n }\n\n private logMessages(\n level: Level,\n messages: unknown[],\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n ) {\n // Lazy messages must not be evaluated for a disabled level.\n if (!this.logger.logger.isLevelEnabled(level)) {\n return;\n }\n messages = messages.map(resolveMessage);\n\n // Mirrors `ConsoleLogger#extractJsonError`: the first error goes to the\n // first entry; when it is the message itself, its message takes its place.\n let error: Error | undefined;\n const errorIndex = HAS_STRUCTURED_ERRORS\n ? messages.findIndex((msg) => msg instanceof Error)\n : -1;\n if (errorIndex !== -1) {\n error = messages[errorIndex] as Error;\n messages =\n errorIndex === 0\n ? [error.message, ...messages.slice(1)]\n : messages.filter((_, index) => index !== errorIndex);\n }\n\n messages.forEach((msg, index) => {\n this.logSingleMessage(\n level,\n msg,\n context,\n stack,\n params,\n index === 0 ? error : undefined,\n );\n });\n }\n\n private logSingleMessage(\n level: Level,\n message: unknown,\n context: string | undefined,\n stack?: string,\n params?: Record<string, any>,\n error?: Error,\n ) {\n // Flattened params go in first so that this logger's own fields win on a\n // key collision. Collisions with pino's fields (the level, the timestamp,\n // the message key, the base bindings) are not handled: pino does not\n // deduplicate keys either, and their names depend on the pino options, so\n // any guard here would be guesswork.\n const objArg: Record<string, any> =\n params && this.flattenParams ? { ...params } : {};\n\n if (context) {\n objArg[this.contextName] = context;\n }\n\n if (stack) {\n objArg.stack = stack;\n }\n\n if (error) {\n objArg.error = serializeError(error);\n }\n\n if (params && !this.flattenParams) {\n objArg.params = params;\n }\n\n if (typeof message === 'object' && message !== null) {\n if (message instanceof Error) {\n this.logger[level](objArg, message.stack || message.message);\n } else {\n this.logger[level](objArg, message as unknown as string);\n }\n } else {\n this.logger[level](objArg, String(message));\n }\n }\n\n private getContextAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n params?: Record<string, any>;\n } {\n if (args.length <= 1) {\n return { messages: args, context: undefined };\n }\n const lastElement = args[args.length - 1];\n const isContext = typeof lastElement === 'string';\n const context = isContext ? lastElement : undefined;\n const remainingArgs = isContext ? args.slice(0, args.length - 1) : args;\n\n if (!this.structuredParams) {\n return { messages: remainingArgs, context };\n }\n\n // The first argument is always the message; only plain objects after it\n // become params, everything else stays a message of its own.\n const messages: unknown[] = [remainingArgs[0]];\n const paramObjects: Record<string, any>[] = [];\n for (const arg of remainingArgs.slice(1)) {\n if (isPlainObject(arg)) {\n paramObjects.push(arg as Record<string, any>);\n } else {\n messages.push(arg);\n }\n }\n\n return {\n messages,\n context,\n params: paramObjects.length\n ? Object.assign({}, ...paramObjects)\n : undefined,\n };\n }\n\n private getContextAndStackAndMessagesToPrint(args: unknown[]): {\n messages: unknown[];\n context: string | undefined;\n stack?: string;\n params?: Record<string, any>;\n } {\n if (args.length === 2) {\n if (this.isStackFormat(args[1])) {\n return {\n messages: [args[0]],\n stack: args[1] as string,\n context: undefined,\n };\n }\n if (typeof args[1] === 'string') {\n return {\n messages: [args[0]],\n context: args[1],\n };\n }\n }\n\n const trailingArg = args[args.length - 1];\n if (args.length > 2 && this.isStackFormat(trailingArg)) {\n const { messages, context, params } = this.getContextAndMessagesToPrint(\n args.slice(0, -1),\n );\n return { messages, context, stack: trailingArg as string, params };\n }\n\n const { messages, context, params } =\n this.getContextAndMessagesToPrint(args);\n if (messages.length <= 1) {\n return { messages, context, params };\n }\n\n const lastMessage = messages[messages.length - 1];\n if (typeof lastMessage === 'string' || typeof lastMessage === 'undefined') {\n return {\n stack: lastMessage,\n messages: messages.slice(0, messages.length - 1),\n context,\n params,\n };\n }\n return { messages, context, params };\n }\n\n private isStackFormat(value: unknown): boolean {\n if (typeof value !== 'string' && typeof value !== 'undefined') {\n return false;\n }\n return typeof value === 'string' && /^(.)+\\n\\s+at .+:\\d+:\\d+/.test(value);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nestjs-pino",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.3.0-alpha.0d3adc",
|
|
4
4
|
"description": "Pino logger for NestJS",
|
|
5
5
|
"main": "./dist/cjs/index.js",
|
|
6
6
|
"types": "./dist/cjs/index.d.ts",
|
|
@@ -51,12 +51,12 @@
|
|
|
51
51
|
"homepage": "https://github.com/iamolegga/nestjs-pino#readme",
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@biomejs/biome": "^2.5.11",
|
|
54
|
-
"@nestjs/common": "^12.
|
|
55
|
-
"@nestjs/core": "^12.
|
|
56
|
-
"@nestjs/microservices": "^12.
|
|
57
|
-
"@nestjs/platform-express": "^12.
|
|
58
|
-
"@nestjs/platform-fastify": "^12.
|
|
59
|
-
"@nestjs/testing": "^12.
|
|
54
|
+
"@nestjs/common": "^12.1.2",
|
|
55
|
+
"@nestjs/core": "^12.1.2",
|
|
56
|
+
"@nestjs/microservices": "^12.1.2",
|
|
57
|
+
"@nestjs/platform-express": "^12.1.2",
|
|
58
|
+
"@nestjs/platform-fastify": "^12.1.2",
|
|
59
|
+
"@nestjs/testing": "^12.1.2",
|
|
60
60
|
"@swc/core": "^1.16.1",
|
|
61
61
|
"@types/express": "^5.0.6",
|
|
62
62
|
"@types/memorystream": "^0.3.4",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"rxjs": "^7.8.2",
|
|
72
72
|
"supertest": "^7.2.2",
|
|
73
73
|
"typescript": "^7.0.2",
|
|
74
|
-
"unplugin-swc": "^
|
|
74
|
+
"unplugin-swc": "^2.0.0",
|
|
75
75
|
"vitest": "^5.0.0"
|
|
76
76
|
},
|
|
77
77
|
"peerDependencies": {
|