nestjs-pino 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -342,6 +342,7 @@ interface Params<
342
342
  * (e.g.`Request completed`).
343
343
  */
344
344
  assignResponse?: boolean;
345
+
345
346
  }
346
347
  ```
347
348
 
@@ -593,9 +594,55 @@ class MyService {
593
594
 
594
595
  By default, this does not extend `Request completed` logs. Set the `assignResponse` parameter to `true` to also enrich response logs automatically emitted by `pino-http`.
595
596
 
597
+ ## Logging context anywhere else
598
+
599
+ Queue processors, cron jobs, CLI commands, standalone scripts, tests and
600
+ consumers wired up outside of NestJS have no request pipeline to hook into. Use
601
+ `runInContext` to open a logging context by hand, and `assign` and inherited
602
+ fields work there too:
603
+
604
+ ```ts
605
+ @Processor('emails')
606
+ export class EmailProcessor extends WorkerHost {
607
+ constructor(private readonly logger: PinoLogger) { super(); }
608
+
609
+ async process(job: Job) {
610
+ return this.logger.runInContext(
611
+ async () => {
612
+ this.logger.assign({ jobId: job.id, attempt: job.attemptsMade });
613
+ this.logger.info('sending');
614
+ await this.send(job.data);
615
+ },
616
+ { bindings: { queue: 'emails' } },
617
+ );
618
+ }
619
+ }
620
+ ```
621
+
622
+ It returns whatever the function returns, and an async function keeps the
623
+ context across every `await` inside it.
624
+
625
+ Pass `inherit: true` to start from the surrounding context instead of from the
626
+ root logger — useful for `@OnEvent` handlers and for work started during a
627
+ request but finished after it. The store is a new one either way, so `assign`
628
+ inside never reaches the log that closes the surrounding request:
629
+
630
+ ```ts
631
+ @OnEvent('order.paid')
632
+ async onPaid(e: OrderPaid) {
633
+ await this.logger.runInContext(
634
+ async () => {
635
+ this.logger.assign({ orderId: e.id });
636
+ await this.fulfil(e);
637
+ },
638
+ { inherit: true },
639
+ );
640
+ }
641
+ ```
642
+
596
643
  ## Change pino params at runtime
597
644
 
598
- Pino root instance with passed via module registration params creates a separate child logger for every request. This root logger params can be changed at runtime via `PinoLogger.root` property which is the pointer to logger instance. Example:
645
+ Pino root instance with passed via module registration params creates a separate child logger for every request. This root logger params can be changed at runtime via `PinoLogger.root` property which is the pointer to logger instance. Every log in the application descends from it — request logs, microservice message logs and logs made outside of any context alike — so a change reaches all of them. It is available in a microservice or standalone application too, where there is no HTTP middleware. Example:
599
646
 
600
647
  ```ts
601
648
  @Controller('/')
@@ -16,12 +16,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.LoggerModule = void 0;
17
17
  const common_1 = require("@nestjs/common");
18
18
  const core_1 = require("@nestjs/core");
19
- const pino_http_1 = require("pino-http");
20
19
  const InjectPinoLogger_1 = require("./InjectPinoLogger");
21
20
  const Logger_1 = require("./Logger");
22
21
  const NativeLogger_1 = require("./NativeLogger");
23
22
  const PinoLogger_1 = require("./PinoLogger");
24
23
  const params_1 = require("./params");
24
+ const rootLogger_1 = require("./rootLogger");
25
25
  const storage_1 = require("./storage");
26
26
  /**
27
27
  * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts
@@ -126,12 +126,13 @@ function createLoggerMiddlewares(params, useExisting = false, assignResponse = f
126
126
  if (useExisting) {
127
127
  return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];
128
128
  }
129
- const middleware = (0, pino_http_1.pinoHttp)(...(Array.isArray(params) ? params : [params]));
129
+ // The same instance the rest of the application already logs through, rather
130
+ // than a second one built here: one `transport`, and a `PinoLogger.root` that
131
+ // governs every log in the application, request-scoped or not.
132
+ const middleware = (0, rootLogger_1.ensureLoggerMiddleware)(params);
130
133
  // @ts-expect-error: root is readonly field, but this is the place where
131
134
  // it's set actually
132
135
  PinoLogger_1.PinoLogger.root = middleware.logger;
133
- // FIXME: params type here is pinoHttp.Options | pino.DestinationStream
134
- // pinoHttp has two overloads, each of them takes those types
135
136
  return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];
136
137
  }
137
138
  function bindLoggerMiddlewareFactory(useExisting, assignResponse) {
@@ -1 +1 @@
1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AAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,iBAAO,CAAC,GAAG,CAAC,IAAI,eAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\nimport { pinoHttp } from 'pino-http';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger';\nimport { Logger } from './Logger';\nimport { NativeLogger } from './NativeLogger';\nimport { PinoLogger } from './PinoLogger';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params';\nimport { Store, storage } from './storage';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ],\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {}\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n const middleware = pinoHttp(\n ...(Array.isArray(params) ? params : [params as any]),\n );\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 // FIXME: params type here is pinoHttp.Options | pino.DestinationStream\n // pinoHttp has two overloads, each of them takes those types\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
1
+ {"version":3,"file":"LoggerModule.js","sourceRoot":"","sources":["../src/LoggerModule.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA,2CASwB;AACxB,uCAAiD;AAEjD,yDAAiE;AACjE,qCAAkC;AAClC,iDAA8C;AAC9C,6CAA0C;AAC1C,qCAIkB;AAClB,6CAAsD;AACtD,uCAA2C;AAE3C;;;;;;;;;;GAUG;AACH,MAAM,cAAc,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,sBAAa,CAAC,GAAG,EAAE,CAAC,CAAC;AAInE,IAAM,YAAY,oBAAlB,MAAM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cAAc,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,6EAA6E;IAC7E,8EAA8E;IAC9E,+DAA+D;IAC/D,MAAM,UAAU,GAAG,IAAA,mCAAsB,EAAC,MAAM,CAAC,CAAC;IAElD,wEAAwE;IACxE,oBAAoB;IACpB,uBAAU,CAAC,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC;IAEpC,OAAO,CAAC,UAAU,EAAE,2BAA2B,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,2BAA2B,CAClC,WAAoB,EACpB,cAAuB;IAEvB,OAAO,SAAS,oBAAoB,CAClC,GAAoB,EACpB,GAAmB,EACnB,IAAgB;QAEhB,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;QAClB,IAAI,MAAM,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAElD,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAChC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAC7C,CAAC;QACD,IAAI,cAAc,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC;QAChD,CAAC;QAED,iBAAO,CAAC,GAAG,CAAC,IAAI,eAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { IncomingMessage, ServerResponse } from 'node:http';\n\nimport {\n type DynamicModule,\n Global,\n Inject,\n type MiddlewareConsumer,\n Module,\n type NestModule,\n type Provider,\n RequestMethod,\n} from '@nestjs/common';\nimport { ApplicationConfig } from '@nestjs/core';\n\nimport { createProvidersForDecorated } from './InjectPinoLogger';\nimport { Logger } from './Logger';\nimport { NativeLogger } from './NativeLogger';\nimport { PinoLogger } from './PinoLogger';\nimport {\n type LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n type Params,\n} from './params';\nimport { ensureLoggerMiddleware } from './rootLogger';\nimport { Store, storage } from './storage';\n\n/**\n * path-to-regexp v8, used by express@5 and @fastify/middie@9, no longer accepts\n * the unnamed `*` wildcard: NestJS auto-converts it, but warns while doing so\n * as soon as a global prefix is set.\n *\n * The missing leading slash is deliberate, and is supported upstream: since\n * @nestjs/common@11.0.8 `addLeadingSlash` leaves a path starting with `{/`\n * alone. A global prefix is then applied as `/v1{/*splat}` rather than\n * `/v1/{*splat}`, which matters because the latter does not match the prefix\n * root itself — `/v1` would go unlogged, while `/v1/anything` would not.\n */\nconst DEFAULT_ROUTES = [{ path: '{/*splat}', method: RequestMethod.ALL }];\n\n@Global()\n@Module({ providers: [Logger, NativeLogger], exports: [Logger, NativeLogger] })\nexport class LoggerModule implements NestModule {\n static forRoot<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params?: Params<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<Params<IM, SR, CustomLevels>> = {\n provide: PARAMS_PROVIDER_TOKEN,\n useValue: params || {},\n };\n\n const decorated = createProvidersForDecorated();\n\n return {\n module: LoggerModule,\n providers: [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ],\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\n };\n }\n\n static forRootAsync<\n IM = IncomingMessage,\n SR = ServerResponse,\n CustomLevels extends string = never,\n >(params: LoggerModuleAsyncParams<IM, SR, CustomLevels>): DynamicModule {\n const paramsProvider: Provider<\n Params<IM, SR, CustomLevels> | Promise<Params<IM, SR, CustomLevels>>\n > = {\n provide: PARAMS_PROVIDER_TOKEN,\n useFactory: params.useFactory,\n inject: params.inject,\n };\n\n const decorated = createProvidersForDecorated();\n\n const providers: any[] = [\n Logger,\n NativeLogger,\n ...decorated,\n PinoLogger,\n paramsProvider,\n ...(params.providers || []),\n ];\n\n return {\n module: LoggerModule,\n imports: params.imports,\n providers,\n exports: [Logger, NativeLogger, ...decorated, PinoLogger, paramsProvider],\n };\n }\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN) private readonly params: Params,\n private readonly applicationConfig: ApplicationConfig,\n ) {}\n\n configure(consumer: MiddlewareConsumer) {\n const {\n exclude,\n forRoutes = this.defaultRoutes(),\n pinoHttp,\n useExisting,\n assignResponse,\n } = this.params;\n\n const middlewares = createLoggerMiddlewares(\n pinoHttp || {},\n useExisting,\n assignResponse,\n );\n\n if (exclude) {\n consumer\n .apply(...middlewares)\n .exclude(...exclude)\n .forRoutes(...forRoutes);\n } else {\n consumer.apply(...middlewares).forRoutes(...forRoutes);\n }\n }\n\n /**\n * A path excluded from the global prefix is served outside of it, while\n * `DEFAULT_ROUTES` is prefixed like any other middleware route, so such a\n * path would go unlogged. NestJS adds excluded paths back on its own, but\n * only for routes that `RouteInfoPathExtractor.isAWildcard` recognises —\n * which `{/*splat}`, with its leading slash deliberately missing, is not.\n *\n * Only the default applies: an explicit `forRoutes` is the user's own call.\n */\n private defaultRoutes() {\n const { exclude } = this.applicationConfig.getGlobalPrefixOptions();\n\n return [\n ...DEFAULT_ROUTES,\n ...(exclude ?? []).map(({ path, requestMethod }) => ({\n path,\n method: requestMethod,\n })),\n ];\n }\n}\n\nfunction createLoggerMiddlewares(\n params: NonNullable<Params['pinoHttp']>,\n useExisting = false,\n assignResponse = false,\n) {\n if (useExisting) {\n return [bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n }\n\n // The same instance the rest of the application already logs through, rather\n // than a second one built here: one `transport`, and a `PinoLogger.root` that\n // governs every log in the application, request-scoped or not.\n const middleware = ensureLoggerMiddleware(params);\n\n // @ts-expect-error: root is readonly field, but this is the place where\n // it's set actually\n PinoLogger.root = middleware.logger;\n\n return [middleware, bindLoggerMiddlewareFactory(useExisting, assignResponse)];\n}\n\nfunction bindLoggerMiddlewareFactory(\n useExisting: boolean,\n assignResponse: boolean,\n) {\n return function bindLoggerMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n ) {\n let log = req.log;\n let resLog = assignResponse ? res.log : undefined;\n\n if (!useExisting && req.allLogs) {\n log = req.allLogs[req.allLogs.length - 1]!;\n }\n if (assignResponse && !useExisting && res.allLogs) {\n resLog = res.allLogs[res.allLogs.length - 1]!;\n }\n\n storage.run(new Store(log, resLog), next);\n };\n}\n"]}
@@ -16,6 +16,23 @@ type PinoMethods<CustomLevels extends string = never> = Pick<pino.Logger<CustomL
16
16
  */
17
17
  type LoggerFn = ((msg: string, ...args: any[]) => void) | ((obj: object, msg?: string, ...args: any[]) => void);
18
18
  export declare function __resetOutOfContextForTests(): void;
19
+ /**
20
+ * Options of {@link PinoLogger.runInContext}.
21
+ */
22
+ export interface RunInContextOptions {
23
+ /**
24
+ * Fields to bind to every log made inside the context, the way `pino-http`
25
+ * binds the request to a request logger.
26
+ */
27
+ bindings?: pino.Bindings;
28
+ /**
29
+ * Start from the logger of the surrounding context, when there is one,
30
+ * instead of from the root logger. The store itself is always a new one, so
31
+ * `assign` inside never leaks back out.
32
+ * @default false
33
+ */
34
+ inherit?: boolean;
35
+ }
19
36
  /**
20
37
  * @typeParam CustomLevels - union of the `customLevels` keys passed to pino, so
21
38
  * that `logger` exposes them. The class itself is instantiated by the DI
@@ -32,7 +49,7 @@ export declare class PinoLogger<CustomLevels extends string = never> implements
32
49
  protected context: string;
33
50
  protected readonly contextName: string;
34
51
  protected readonly errorKey: string;
35
- constructor({ pinoHttp, renameContext }: Params<any, any, CustomLevels>);
52
+ constructor({ pinoHttp, renameContext, useExisting }: Params<any, any, CustomLevels>);
36
53
  get logger(): pino.Logger<CustomLevels>;
37
54
  trace(msg: string, ...args: any[]): void;
38
55
  trace(obj: unknown, msg?: string, ...args: any[]): void;
@@ -48,6 +65,17 @@ export declare class PinoLogger<CustomLevels extends string = never> implements
48
65
  fatal(obj: unknown, msg?: string, ...args: any[]): void;
49
66
  setContext(value: string): void;
50
67
  assign(fields: pino.Bindings): void;
68
+ /**
69
+ * Runs `fn` inside a fresh logging context, so that `assign` works and every
70
+ * log made within it carries `bindings` — the same thing the HTTP middleware
71
+ * does per request, for the places NestJS has no request pipeline for: queue
72
+ * processors, cron jobs, CLI commands, standalone scripts, tests, and
73
+ * consumers wired up outside of Nest.
74
+ *
75
+ * Returns whatever `fn` returns; an async `fn` keeps the context across every
76
+ * `await` inside it.
77
+ */
78
+ runInContext<T>(fn: () => T, options?: RunInContextOptions): T;
51
79
  protected call(method: pino.Level | CustomLevels, ...args: Parameters<LoggerFn>): void;
52
80
  }
53
81
  export {};
@@ -11,20 +11,16 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
- var __importDefault = (this && this.__importDefault) || function (mod) {
15
- return (mod && mod.__esModule) ? mod : { "default": mod };
16
- };
17
14
  var PinoLogger_1;
18
15
  Object.defineProperty(exports, "__esModule", { value: true });
19
16
  exports.PinoLogger = void 0;
20
17
  exports.__resetOutOfContextForTests = __resetOutOfContextForTests;
21
18
  const common_1 = require("@nestjs/common");
22
- const pino_1 = __importDefault(require("pino"));
23
19
  const params_1 = require("./params");
20
+ const rootLogger_1 = require("./rootLogger");
24
21
  const storage_1 = require("./storage");
25
- let outOfContext;
26
22
  function __resetOutOfContextForTests() {
27
- outOfContext = undefined;
23
+ (0, rootLogger_1.resetRootLogger)();
28
24
  // @ts-expect-error reset root for tests only
29
25
  PinoLogger.root = undefined;
30
26
  }
@@ -45,7 +41,7 @@ let PinoLogger = class PinoLogger {
45
41
  context = '';
46
42
  contextName;
47
43
  errorKey = 'err';
48
- constructor({ pinoHttp, renameContext }) {
44
+ constructor({ pinoHttp, renameContext, useExisting }) {
49
45
  // Handle both array tuple [Options, DestinationStream] and object forms
50
46
  const pinoHttpOptions = Array.isArray(pinoHttp) ? pinoHttp[0] : pinoHttp;
51
47
  if (typeof pinoHttpOptions === 'object' &&
@@ -53,21 +49,14 @@ let PinoLogger = class PinoLogger {
53
49
  typeof pinoHttpOptions.customAttributeKeys !== 'undefined') {
54
50
  this.errorKey = pinoHttpOptions.customAttributeKeys.err ?? 'err';
55
51
  }
56
- if (!outOfContext) {
57
- if (Array.isArray(pinoHttp)) {
58
- outOfContext = (0, pino_1.default)(...pinoHttp);
59
- }
60
- else if ((0, params_1.isPassedLogger)(pinoHttp)) {
61
- outOfContext = pinoHttp.logger;
62
- }
63
- else if (typeof pinoHttp === 'object' &&
64
- 'stream' in pinoHttp &&
65
- typeof pinoHttp.stream !== 'undefined') {
66
- outOfContext = (0, pino_1.default)(pinoHttp, pinoHttp.stream);
67
- }
68
- else {
69
- outOfContext = (0, pino_1.default)(pinoHttp);
70
- }
52
+ const root = (0, rootLogger_1.ensureRootLogger)(pinoHttp);
53
+ // With `useExisting` the logger belongs to the Fastify adapter, so there is
54
+ // no root of ours to expose and the documented `undefined` stands. The root
55
+ // logger itself is still built, because logs made outside of a request have
56
+ // nowhere else to go.
57
+ if (!useExisting) {
58
+ // @ts-expect-error root is a readonly field, this is where it is set
59
+ PinoLogger_1.root = root;
71
60
  }
72
61
  this.contextName = renameContext || 'context';
73
62
  }
@@ -79,7 +68,7 @@ let PinoLogger = class PinoLogger {
79
68
  // cannot carry the custom levels through, and `pino.Logger`'s `onChild`
80
69
  // makes the two instantiations mutually non-comparable.
81
70
  return (storage_1.storage.getStore()?.logger ||
82
- outOfContext);
71
+ (0, rootLogger_1.getRootLogger)());
83
72
  }
84
73
  trace(...args) {
85
74
  this.call('trace', ...args);
@@ -110,6 +99,26 @@ let PinoLogger = class PinoLogger {
110
99
  store.logger = store.logger.child(fields);
111
100
  store.responseLogger?.setBindings(fields);
112
101
  }
102
+ /**
103
+ * Runs `fn` inside a fresh logging context, so that `assign` works and every
104
+ * log made within it carries `bindings` — the same thing the HTTP middleware
105
+ * does per request, for the places NestJS has no request pipeline for: queue
106
+ * processors, cron jobs, CLI commands, standalone scripts, tests, and
107
+ * consumers wired up outside of Nest.
108
+ *
109
+ * Returns whatever `fn` returns; an async `fn` keeps the context across every
110
+ * `await` inside it.
111
+ */
112
+ runInContext(fn, options = {}) {
113
+ const { bindings, inherit = false } = options;
114
+ const current = storage_1.storage.getStore();
115
+ const base = (inherit && current ? current.logger : (0, rootLogger_1.getRootLogger)());
116
+ const logger = bindings ? base.child(bindings) : base;
117
+ // The response logger is deliberately not carried over when inheriting:
118
+ // fields assigned inside the nested context must not reach the log that
119
+ // closes the surrounding request.
120
+ return storage_1.storage.run(new storage_1.Store(logger), fn);
121
+ }
113
122
  call(method, ...args) {
114
123
  if (this.context) {
115
124
  if (isFirstArgObject(args)) {
@@ -1 +1 @@
1
- {"version":3,"file":"PinoLogger.js","sourceRoot":"","sources":["../src/PinoLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,2CAA2D;AAC3D,gDAAwB;AAExB,qCAAyE;AACzE,uCAAoC;AAwBpC,IAAI,YAAqC,CAAC;AAE1C;IACE,YAAY,GAAG,SAAS,CAAC;IACzB,6CAA6C;IAC7C,UAAU,CAAC,IAAI,GAAG,SAAS,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;;IAGrB;;;;OAIG;IACH,MAAM,CAAU,IAAI,CAAc;IAExB,OAAO,GAAG,EAAE,CAAC;IACJ,WAAW,CAAS;IACpB,QAAQ,GAAW,KAAK,CAAC;IAE5C,YAEE,EAAE,QAAQ,EAAE,aAAa,EAAkC;QAE3D,wEAAwE;QACxE,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QACz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C,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EACpC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAC9B;wBACD,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;qBACjB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,IAAI,GAAG;wBACL,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,QAAQ,CAAC;wBAC7D,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;qBACjB,CAAC;gBACJ,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,IAAI,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YACzD,CAAC;QACH,CAAC;QACD,iDAAiD;QACjD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC/B,CAAC;CACF,CAAA;;qBAzIY,UAAU;IADtB,IAAA,mBAAU,EAAC,EAAE,KAAK,EAAE,cAAK,CAAC,SAAS,EAAE,CAAC;IAgBlC,WAAA,IAAA,eAAM,EAAC,8BAAqB,CAAC,CAAA;;GAfrB,UAAU,CAyItB;AAED,SAAS,gBAAgB,CACvB,IAA0B;IAE1B,OAAO,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC;AACrC,CAAC","sourcesContent":["import { Inject, Injectable, Scope } from '@nestjs/common';\nimport pino from 'pino';\n\nimport { isPassedLogger, PARAMS_PROVIDER_TOKEN, Params } from './params';\nimport { storage } from './storage';\n\ntype PinoMethods<CustomLevels extends string = never> = Pick<\n pino.Logger<CustomLevels>,\n 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'\n>;\n\n/**\n * This is copy of pino.LogFn but with possibilty to make method override.\n * Current usage works:\n *\n * trace(msg: string, ...args: any[]): void;\n * trace(obj: object, msg?: string, ...args: any[]): void;\n * trace(...args: Parameters<LoggerFn>) {\n * this.call('trace', ...args);\n * }\n *\n * But if change local LoggerFn to pino.LogFn – this will say that overrides\n * are incompatible\n */\ntype LoggerFn =\n | ((msg: string, ...args: any[]) => void)\n | ((obj: object, msg?: string, ...args: any[]) => void);\n\nlet outOfContext: pino.Logger | undefined;\n\nexport function __resetOutOfContextForTests() {\n outOfContext = undefined;\n // @ts-expect-error reset root for tests only\n PinoLogger.root = undefined;\n}\n\n/**\n * @typeParam CustomLevels - union of the `customLevels` keys passed to pino, so\n * that `logger` exposes them. The class itself is instantiated by the DI\n * container, which cannot infer a type argument, so custom levels are reachable\n * as `pinoLogger.logger.myLevel(...)` rather than `pinoLogger.myLevel(...)`.\n */\n@Injectable({ scope: Scope.TRANSIENT })\nexport class PinoLogger<CustomLevels extends string = never>\n implements PinoMethods<CustomLevels>\n{\n /**\n * root is the most root logger that can be used to change params at runtime.\n * Accessible only when `useExisting` is not set to `true` in `Params`.\n * Readonly, but you can change it's properties.\n */\n static readonly root: pino.Logger;\n\n protected context = '';\n protected readonly contextName: string;\n protected readonly errorKey: string = 'err';\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN)\n { pinoHttp, renameContext }: Params<any, any, CustomLevels>,\n ) {\n // Handle both array tuple [Options, DestinationStream] and object forms\n const pinoHttpOptions = Array.isArray(pinoHttp) ? pinoHttp[0] : pinoHttp;\n if (\n typeof pinoHttpOptions === 'object' &&\n 'customAttributeKeys' in pinoHttpOptions &&\n typeof pinoHttpOptions.customAttributeKeys !== 'undefined'\n ) {\n this.errorKey = pinoHttpOptions.customAttributeKeys.err ?? 'err';\n }\n\n if (!outOfContext) {\n if (Array.isArray(pinoHttp)) {\n outOfContext = pino(...pinoHttp);\n } else if (isPassedLogger(pinoHttp)) {\n outOfContext = pinoHttp.logger;\n } else if (\n typeof pinoHttp === 'object' &&\n 'stream' in pinoHttp &&\n typeof pinoHttp.stream !== 'undefined'\n ) {\n outOfContext = pino(pinoHttp, pinoHttp.stream);\n } else {\n outOfContext = pino(pinoHttp);\n }\n }\n\n this.contextName = renameContext || 'context';\n }\n\n get logger(): pino.Logger<CustomLevels> {\n // outOfContext is always set in runtime before starts using.\n //\n // The cast goes through `unknown` because `pino-http` augments\n // `http.IncomingMessage` with a plain, non-generic `pino.Logger`, so `Store`\n // cannot carry the custom levels through, and `pino.Logger`'s `onChild`\n // makes the two instantiations mutually non-comparable.\n return (storage.getStore()?.logger ||\n outOfContext!) as unknown as pino.Logger<CustomLevels>;\n }\n\n trace(msg: string, ...args: any[]): void;\n trace(obj: unknown, msg?: string, ...args: any[]): void;\n trace(...args: Parameters<LoggerFn>) {\n this.call('trace', ...args);\n }\n\n debug(msg: string, ...args: any[]): void;\n debug(obj: unknown, msg?: string, ...args: any[]): void;\n debug(...args: Parameters<LoggerFn>) {\n this.call('debug', ...args);\n }\n\n info(msg: string, ...args: any[]): void;\n info(obj: unknown, msg?: string, ...args: any[]): void;\n info(...args: Parameters<LoggerFn>) {\n this.call('info', ...args);\n }\n\n warn(msg: string, ...args: any[]): void;\n warn(obj: unknown, msg?: string, ...args: any[]): void;\n warn(...args: Parameters<LoggerFn>) {\n this.call('warn', ...args);\n }\n\n error(msg: string, ...args: any[]): void;\n error(obj: unknown, msg?: string, ...args: any[]): void;\n error(...args: Parameters<LoggerFn>) {\n this.call('error', ...args);\n }\n\n fatal(msg: string, ...args: any[]): void;\n fatal(obj: unknown, msg?: string, ...args: any[]): void;\n fatal(...args: Parameters<LoggerFn>) {\n this.call('fatal', ...args);\n }\n\n setContext(value: string) {\n this.context = value;\n }\n\n assign(fields: pino.Bindings) {\n const store = storage.getStore();\n if (!store) {\n throw new Error(\n `${PinoLogger.name}: unable to assign extra fields out of request scope`,\n );\n }\n store.logger = store.logger.child(fields);\n store.responseLogger?.setBindings(fields);\n }\n\n protected call(\n method: pino.Level | CustomLevels,\n ...args: Parameters<LoggerFn>\n ) {\n if (this.context) {\n if (isFirstArgObject(args)) {\n const firstArg = args[0];\n if (firstArg instanceof Error) {\n args = [\n Object.assign(\n { [this.contextName]: this.context },\n { [this.errorKey]: firstArg },\n ),\n ...args.slice(1),\n ];\n } else {\n args = [\n Object.assign({ [this.contextName]: this.context }, firstArg),\n ...args.slice(1),\n ];\n }\n } else {\n args = [{ [this.contextName]: this.context }, ...args];\n }\n }\n // @ts-expect-error args are union of tuple types\n this.logger[method](...args);\n }\n}\n\nfunction isFirstArgObject(\n args: Parameters<LoggerFn>,\n): args is [obj: object, msg?: string, ...args: any[]] {\n return typeof args[0] === 'object';\n}\n"]}
1
+ {"version":3,"file":"PinoLogger.js","sourceRoot":"","sources":["../src/PinoLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,2CAA2D;AAG3D,qCAAyD;AACzD,6CAAgF;AAChF,uCAA2C;AAwB3C;IACE,IAAA,4BAAe,GAAE,CAAC;IAClB,6CAA6C;IAC7C,UAAU,CAAC,IAAI,GAAG,SAAS,CAAC;AAC9B,CAAC;AAqBD;;;;;GAKG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;;IAGrB;;;;OAIG;IACH,MAAM,CAAU,IAAI,CAAc;IAExB,OAAO,GAAG,EAAE,CAAC;IACJ,WAAW,CAAS;IACpB,QAAQ,GAAW,KAAK,CAAC;IAE5C,YAEE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAkC;QAExE,wEAAwE;QACxE,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QACzE,IACE,OAAO,eAAe,KAAK,QAAQ;YACnC,qBAAqB,IAAI,eAAe;YACxC,OAAO,eAAe,CAAC,mBAAmB,KAAK,WAAW,EAC1D,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG,eAAe,CAAC,mBAAmB,CAAC,GA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B,IAAI,GAAG;wBACL,MAAM,CAAC,MAAM,CACX,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EACpC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAC9B;wBACD,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;qBACjB,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,IAAI,GAAG;wBACL,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,QAAQ,CAAC;wBAC7D,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;qBACjB,CAAC;gBACJ,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,IAAI,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YACzD,CAAC;QACH,CAAC;QACD,iDAAiD;QACjD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC/B,CAAC;CACF,CAAA;;qBA1JY,UAAU;IADtB,IAAA,mBAAU,EAAC,EAAE,KAAK,EAAE,cAAK,CAAC,SAAS,EAAE,CAAC;IAgBlC,WAAA,IAAA,eAAM,EAAC,8BAAqB,CAAC,CAAA;;GAfrB,UAAU,CA0JtB;AAED,SAAS,gBAAgB,CACvB,IAA0B;IAE1B,OAAO,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC;AACrC,CAAC","sourcesContent":["import { Inject, Injectable, Scope } from '@nestjs/common';\nimport pino from 'pino';\n\nimport { PARAMS_PROVIDER_TOKEN, Params } from './params';\nimport { ensureRootLogger, getRootLogger, resetRootLogger } from './rootLogger';\nimport { Store, storage } from './storage';\n\ntype PinoMethods<CustomLevels extends string = never> = Pick<\n pino.Logger<CustomLevels>,\n 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'\n>;\n\n/**\n * This is copy of pino.LogFn but with possibilty to make method override.\n * Current usage works:\n *\n * trace(msg: string, ...args: any[]): void;\n * trace(obj: object, msg?: string, ...args: any[]): void;\n * trace(...args: Parameters<LoggerFn>) {\n * this.call('trace', ...args);\n * }\n *\n * But if change local LoggerFn to pino.LogFn – this will say that overrides\n * are incompatible\n */\ntype LoggerFn =\n | ((msg: string, ...args: any[]) => void)\n | ((obj: object, msg?: string, ...args: any[]) => void);\n\nexport function __resetOutOfContextForTests() {\n resetRootLogger();\n // @ts-expect-error reset root for tests only\n PinoLogger.root = undefined;\n}\n\n/**\n * Options of {@link PinoLogger.runInContext}.\n */\nexport interface RunInContextOptions {\n /**\n * Fields to bind to every log made inside the context, the way `pino-http`\n * binds the request to a request logger.\n */\n bindings?: pino.Bindings;\n\n /**\n * Start from the logger of the surrounding context, when there is one,\n * instead of from the root logger. The store itself is always a new one, so\n * `assign` inside never leaks back out.\n * @default false\n */\n inherit?: boolean;\n}\n\n/**\n * @typeParam CustomLevels - union of the `customLevels` keys passed to pino, so\n * that `logger` exposes them. The class itself is instantiated by the DI\n * container, which cannot infer a type argument, so custom levels are reachable\n * as `pinoLogger.logger.myLevel(...)` rather than `pinoLogger.myLevel(...)`.\n */\n@Injectable({ scope: Scope.TRANSIENT })\nexport class PinoLogger<CustomLevels extends string = never>\n implements PinoMethods<CustomLevels>\n{\n /**\n * root is the most root logger that can be used to change params at runtime.\n * Accessible only when `useExisting` is not set to `true` in `Params`.\n * Readonly, but you can change it's properties.\n */\n static readonly root: pino.Logger;\n\n protected context = '';\n protected readonly contextName: string;\n protected readonly errorKey: string = 'err';\n\n constructor(\n @Inject(PARAMS_PROVIDER_TOKEN)\n { pinoHttp, renameContext, useExisting }: Params<any, any, CustomLevels>,\n ) {\n // Handle both array tuple [Options, DestinationStream] and object forms\n const pinoHttpOptions = Array.isArray(pinoHttp) ? pinoHttp[0] : pinoHttp;\n if (\n typeof pinoHttpOptions === 'object' &&\n 'customAttributeKeys' in pinoHttpOptions &&\n typeof pinoHttpOptions.customAttributeKeys !== 'undefined'\n ) {\n this.errorKey = pinoHttpOptions.customAttributeKeys.err ?? 'err';\n }\n\n const root = ensureRootLogger(pinoHttp);\n\n // With `useExisting` the logger belongs to the Fastify adapter, so there is\n // no root of ours to expose and the documented `undefined` stands. The root\n // logger itself is still built, because logs made outside of a request have\n // nowhere else to go.\n if (!useExisting) {\n // @ts-expect-error root is a readonly field, this is where it is set\n PinoLogger.root = root;\n }\n\n this.contextName = renameContext || 'context';\n }\n\n get logger(): pino.Logger<CustomLevels> {\n // outOfContext is always set in runtime before starts using.\n //\n // The cast goes through `unknown` because `pino-http` augments\n // `http.IncomingMessage` with a plain, non-generic `pino.Logger`, so `Store`\n // cannot carry the custom levels through, and `pino.Logger`'s `onChild`\n // makes the two instantiations mutually non-comparable.\n return (storage.getStore()?.logger ||\n getRootLogger()!) as unknown as pino.Logger<CustomLevels>;\n }\n\n trace(msg: string, ...args: any[]): void;\n trace(obj: unknown, msg?: string, ...args: any[]): void;\n trace(...args: Parameters<LoggerFn>) {\n this.call('trace', ...args);\n }\n\n debug(msg: string, ...args: any[]): void;\n debug(obj: unknown, msg?: string, ...args: any[]): void;\n debug(...args: Parameters<LoggerFn>) {\n this.call('debug', ...args);\n }\n\n info(msg: string, ...args: any[]): void;\n info(obj: unknown, msg?: string, ...args: any[]): void;\n info(...args: Parameters<LoggerFn>) {\n this.call('info', ...args);\n }\n\n warn(msg: string, ...args: any[]): void;\n warn(obj: unknown, msg?: string, ...args: any[]): void;\n warn(...args: Parameters<LoggerFn>) {\n this.call('warn', ...args);\n }\n\n error(msg: string, ...args: any[]): void;\n error(obj: unknown, msg?: string, ...args: any[]): void;\n error(...args: Parameters<LoggerFn>) {\n this.call('error', ...args);\n }\n\n fatal(msg: string, ...args: any[]): void;\n fatal(obj: unknown, msg?: string, ...args: any[]): void;\n fatal(...args: Parameters<LoggerFn>) {\n this.call('fatal', ...args);\n }\n\n setContext(value: string) {\n this.context = value;\n }\n\n assign(fields: pino.Bindings) {\n const store = storage.getStore();\n if (!store) {\n throw new Error(\n `${PinoLogger.name}: unable to assign extra fields out of request scope`,\n );\n }\n store.logger = store.logger.child(fields);\n store.responseLogger?.setBindings(fields);\n }\n\n /**\n * Runs `fn` inside a fresh logging context, so that `assign` works and every\n * log made within it carries `bindings` — the same thing the HTTP middleware\n * does per request, for the places NestJS has no request pipeline for: queue\n * processors, cron jobs, CLI commands, standalone scripts, tests, and\n * consumers wired up outside of Nest.\n *\n * Returns whatever `fn` returns; an async `fn` keeps the context across every\n * `await` inside it.\n */\n runInContext<T>(fn: () => T, options: RunInContextOptions = {}): T {\n const { bindings, inherit = false } = options;\n const current = storage.getStore();\n const base = (inherit && current ? current.logger : getRootLogger()!)!;\n const logger = bindings ? base.child(bindings) : base;\n\n // The response logger is deliberately not carried over when inheriting:\n // fields assigned inside the nested context must not reach the log that\n // closes the surrounding request.\n return storage.run(new Store(logger), fn);\n }\n\n protected call(\n method: pino.Level | CustomLevels,\n ...args: Parameters<LoggerFn>\n ) {\n if (this.context) {\n if (isFirstArgObject(args)) {\n const firstArg = args[0];\n if (firstArg instanceof Error) {\n args = [\n Object.assign(\n { [this.contextName]: this.context },\n { [this.errorKey]: firstArg },\n ),\n ...args.slice(1),\n ];\n } else {\n args = [\n Object.assign({ [this.contextName]: this.context }, firstArg),\n ...args.slice(1),\n ];\n }\n } else {\n args = [{ [this.contextName]: this.context }, ...args];\n }\n }\n // @ts-expect-error args are union of tuple types\n this.logger[method](...args);\n }\n}\n\nfunction isFirstArgObject(\n args: Parameters<LoggerFn>,\n): args is [obj: object, msg?: string, ...args: any[]] {\n return typeof args[0] === 'object';\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -3,6 +3,6 @@ export { Logger } from './Logger';
3
3
  export { LoggerErrorInterceptor } from './LoggerErrorInterceptor';
4
4
  export { LoggerModule } from './LoggerModule';
5
5
  export { NativeLogger } from './NativeLogger';
6
- export { PinoLogger } from './PinoLogger';
6
+ export { PinoLogger, type RunInContextOptions } from './PinoLogger';
7
7
  export { LoggerModuleAsyncParams, PARAMS_PROVIDER_TOKEN, Params, } from './params';
8
8
  export { nativeLoggerOptions } from './presets';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAsE;AAA7D,kHAAA,cAAc,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACzC,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AACf,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AACnB,mCAIkB;AAFhB,+GAAA,qBAAqB,OAAA;AAGvB,qCAAgD;AAAvC,8GAAA,mBAAmB,OAAA","sourcesContent":["export { getLoggerToken, InjectPinoLogger } from './InjectPinoLogger';\nexport { Logger } from './Logger';\nexport { LoggerErrorInterceptor } from './LoggerErrorInterceptor';\nexport { LoggerModule } from './LoggerModule';\nexport { NativeLogger } from './NativeLogger';\nexport { PinoLogger } from './PinoLogger';\nexport {\n LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n Params,\n} from './params';\nexport { nativeLoggerOptions } from './presets';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAsE;AAA7D,kHAAA,cAAc,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AACzC,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AACf,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AACrB,2CAAoE;AAA3D,wGAAA,UAAU,OAAA;AACnB,mCAIkB;AAFhB,+GAAA,qBAAqB,OAAA;AAGvB,qCAAgD;AAAvC,8GAAA,mBAAmB,OAAA","sourcesContent":["export { getLoggerToken, InjectPinoLogger } from './InjectPinoLogger';\nexport { Logger } from './Logger';\nexport { LoggerErrorInterceptor } from './LoggerErrorInterceptor';\nexport { LoggerModule } from './LoggerModule';\nexport { NativeLogger } from './NativeLogger';\nexport { PinoLogger, type RunInContextOptions } from './PinoLogger';\nexport {\n LoggerModuleAsyncParams,\n PARAMS_PROVIDER_TOKEN,\n Params,\n} from './params';\nexport { nativeLoggerOptions } from './presets';\n"]}
@@ -0,0 +1,16 @@
1
+ import { Logger } from 'pino';
2
+ import { HttpLogger } from 'pino-http';
3
+ /**
4
+ * These helpers only forward their argument to `pino-http`, so they are
5
+ * deliberately blind to the request, response and custom-level type arguments
6
+ * the caller picked. It cannot be spelled as `Params<any, any, any>['pinoHttp']`
7
+ * either: pino's `onChild` makes two `Logger<CustomLevels>` instantiations
8
+ * mutually non-assignable, so no instantiation is general enough to accept the
9
+ * others.
10
+ */
11
+ type PinoHttpParams = object;
12
+ export declare function ensureLoggerMiddleware(params?: PinoHttpParams): HttpLogger;
13
+ export declare function ensureRootLogger(params?: PinoHttpParams): Logger;
14
+ export declare function getRootLogger(): Logger | undefined;
15
+ export declare function resetRootLogger(): void;
16
+ export {};
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureLoggerMiddleware = ensureLoggerMiddleware;
4
+ exports.ensureRootLogger = ensureRootLogger;
5
+ exports.getRootLogger = getRootLogger;
6
+ exports.resetRootLogger = resetRootLogger;
7
+ const pino_http_1 = require("pino-http");
8
+ /**
9
+ * The one `pino-http` instance of the application, and with it the one pino
10
+ * logger everything else derives from.
11
+ *
12
+ * It used to be built twice: once in the `PinoLogger` constructor, for logs made
13
+ * outside a request, and once by `pino-http` inside the middleware, for logs
14
+ * made inside one. The two were unrelated objects writing to the same
15
+ * destination, so a `transport` was spawned twice, `PinoLogger.root` only ever
16
+ * governed the request half, and an application with no HTTP middleware — a
17
+ * microservice, a standalone script — had no root at all.
18
+ *
19
+ * `pinoHttp()` is just a factory, so nothing requires it to be called from
20
+ * `configure()`. It is called on first use instead, whoever gets there first,
21
+ * and `configure()` mounts that same instance as the middleware.
22
+ */
23
+ let middleware;
24
+ function isDestinationStream(value) {
25
+ return (!!value &&
26
+ typeof value === 'object' &&
27
+ typeof value.write === 'function');
28
+ }
29
+ function ensureLoggerMiddleware(params) {
30
+ if (!middleware) {
31
+ if (Array.isArray(params)) {
32
+ middleware = (0, pino_http_1.pinoHttp)(...params);
33
+ }
34
+ else if (isDestinationStream(params)) {
35
+ middleware = (0, pino_http_1.pinoHttp)(params);
36
+ }
37
+ else {
38
+ middleware = (0, pino_http_1.pinoHttp)(params);
39
+ }
40
+ }
41
+ return middleware;
42
+ }
43
+ function ensureRootLogger(params) {
44
+ return ensureLoggerMiddleware(params).logger;
45
+ }
46
+ function getRootLogger() {
47
+ return middleware?.logger;
48
+ }
49
+ function resetRootLogger() {
50
+ middleware = undefined;
51
+ }
52
+ //# sourceMappingURL=rootLogger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rootLogger.js","sourceRoot":"","sources":["../src/rootLogger.ts"],"names":[],"mappings":";;;;;;AACA,yCAAiD;AAYjD;;;;;;;;;;;;;;GAcG;AACH,IAAI,UAAkC,CAAC;AAEvC,SAAS,mBAAmB,CAAC,KAAc;IACzC,OAAO,CACL,CAAC,CAAC,KAAK;QACP,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAQ,KAA2B,CAAC,KAAK,KAAK,UAAU,CACzD,CAAC;AACJ,CAAC;AAED,gCAAuC,MAAuB;IAC5D,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC1B,UAAU,GAAG,IAAA,oBAAQ,EAAC,GAAI,MAAmC,CAAC,CAAC;QACjE,CAAC;aAAM,IAAI,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC;YACvC,UAAU,GAAG,IAAA,oBAAQ,EAAC,MAAM,CAAC,CAAC;QAChC,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,IAAA,oBAAQ,EAAC,MAAa,CAAC,CAAC;QACvC,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,0BAAiC,MAAuB;IACtD,OAAO,sBAAsB,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC;AAC/C,CAAC;AAED;IACE,OAAO,UAAU,EAAE,MAAM,CAAC;AAC5B,CAAC;AAED;IACE,UAAU,GAAG,SAAS,CAAC;AACzB,CAAC","sourcesContent":["import { DestinationStream, Logger } from 'pino';\nimport { HttpLogger, pinoHttp } from 'pino-http';\n\n/**\n * These helpers only forward their argument to `pino-http`, so they are\n * deliberately blind to the request, response and custom-level type arguments\n * the caller picked. It cannot be spelled as `Params<any, any, any>['pinoHttp']`\n * either: pino's `onChild` makes two `Logger<CustomLevels>` instantiations\n * mutually non-assignable, so no instantiation is general enough to accept the\n * others.\n */\ntype PinoHttpParams = object;\n\n/**\n * The one `pino-http` instance of the application, and with it the one pino\n * logger everything else derives from.\n *\n * It used to be built twice: once in the `PinoLogger` constructor, for logs made\n * outside a request, and once by `pino-http` inside the middleware, for logs\n * made inside one. The two were unrelated objects writing to the same\n * destination, so a `transport` was spawned twice, `PinoLogger.root` only ever\n * governed the request half, and an application with no HTTP middleware — a\n * microservice, a standalone script — had no root at all.\n *\n * `pinoHttp()` is just a factory, so nothing requires it to be called from\n * `configure()`. It is called on first use instead, whoever gets there first,\n * and `configure()` mounts that same instance as the middleware.\n */\nlet middleware: HttpLogger | undefined;\n\nfunction isDestinationStream(value: unknown): value is DestinationStream {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as DestinationStream).write === 'function'\n );\n}\n\nexport function ensureLoggerMiddleware(params?: PinoHttpParams): HttpLogger {\n if (!middleware) {\n if (Array.isArray(params)) {\n middleware = pinoHttp(...(params as [any, DestinationStream]));\n } else if (isDestinationStream(params)) {\n middleware = pinoHttp(params);\n } else {\n middleware = pinoHttp(params as any);\n }\n }\n return middleware;\n}\n\nexport function ensureRootLogger(params?: PinoHttpParams): Logger {\n return ensureLoggerMiddleware(params).logger;\n}\n\nexport function getRootLogger(): Logger | undefined {\n return middleware?.logger;\n}\n\nexport function resetRootLogger(): void {\n middleware = undefined;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nestjs-pino",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "Pino logger for NestJS",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",