@bymax-one/nest-logger 1.4.14 → 1.4.16
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/CHANGELOG.md +39 -1
- package/README.md +246 -807
- package/dist/server/index.cjs +44 -29
- package/dist/server/index.mjs +44 -29
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -33,67 +33,31 @@
|
|
|
33
33
|
|
|
34
34
|
## ✨ Overview
|
|
35
35
|
|
|
36
|
-
`@bymax-one/nest-logger` replaces ad-hoc `console.log` and legacy Winston setups with a
|
|
36
|
+
`@bymax-one/nest-logger` replaces ad-hoc `console.log` and legacy Winston setups with a structured logging pipeline. Every entry is a JSON object carrying a `logKey` (`MODULE_ACTION_RESULT` convention), `requestId`, `tenantId` and, when OpenTelemetry is active, the correlated `traceId`/`spanId`.
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
The library has **zero direct dependencies**: every package arrives as a peer dependency, so you control exact versions and the supply chain stays small.
|
|
39
39
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
- **🔌 Your sinks, your rules** — The library defines `ILogDestination`. You implement it for Loki, Postgres, a rolling file, or anything else. No vendor lock-in, no hidden transport dependencies.
|
|
46
|
-
- **🔒 Redacted by default** — 32 sensitive field names are censored **down to 100 levels of nesting**, covering passwords, tokens, PCI DSS card data, MFA secrets, LGPD documents and credential-bearing HTTP headers. One recursive walk per entry, not a path list. Domain-specific names are yours to add via `redactPaths`.
|
|
47
|
-
- **⚡ On the hot path, so it stays cheap** — Singleton providers, one composed Pino mixin, and a single-pass redactor. No `Scope.REQUEST`, no path matching.
|
|
48
|
-
- **🔭 Correlated when you need it** — When an OpenTelemetry span is active, `traceId`/`spanId`/`traceFlags` land in every entry. When the peer is absent, the mixin steps aside at zero cost.
|
|
49
|
-
|
|
50
|
-
```
|
|
51
|
-
pnpm add @bymax-one/nest-logger
|
|
52
|
-
```
|
|
40
|
+
- **🎯 One module, the whole pipeline** — logger service, HTTP access log, exception filter, context propagation, redaction and destinations arrive in a single `forRoot()`.
|
|
41
|
+
- **🔌 Your sinks, your rules** — implement `ILogDestination` for Loki, Postgres, a rolling file or anything else. No hidden transport dependencies.
|
|
42
|
+
- **🔒 Redacted by default** — 32 sensitive field names (passwords, tokens, card data, MFA secrets, LGPD documents, credential headers) are censored down to 100 levels of nesting. Domain-specific names are yours to add via `redactPaths`.
|
|
43
|
+
- **⚡ Cheap on the hot path** — singleton providers, one composed Pino mixin and a single-pass redactor. The shipped configuration sustains about 274,000 entries/s (see [Performance](#-performance)).
|
|
44
|
+
- **🔭 Correlated when you need it** — with an active OpenTelemetry span, `traceId`/`spanId`/`traceFlags` land in every entry; without the peer the mixin steps aside at zero cost.
|
|
53
45
|
|
|
54
46
|
---
|
|
55
47
|
|
|
56
48
|
## 🔥 Features
|
|
57
49
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
- ✅ **
|
|
61
|
-
- ✅
|
|
62
|
-
- ✅ **
|
|
63
|
-
- ✅ **
|
|
64
|
-
- ✅
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
- ✅ **
|
|
69
|
-
- ✅ **PCI DSS & MFA Coverage** — card data and MFA secrets redacted out of the box, with common HTTP auth headers
|
|
70
|
-
- ✅ **LGPD-Aware Paths** — CPF, CNPJ, and RG redacted by default for Brazilian workloads
|
|
71
|
-
- ✅ **Append-Only Redact List** — `DEFAULT_REDACT_PATHS` never shrinks without a major version; extend it via `redactPaths`
|
|
72
|
-
- ✅ **Validated Trace IDs** — OTel identifiers pass `isValidTraceId` before injection, never raw user input
|
|
73
|
-
|
|
74
|
-
### 🔍 Observability & Context
|
|
75
|
-
|
|
76
|
-
- ✅ **OpenTelemetry Correlation** — optional `@opentelemetry/api` peer; injects `traceId`/`spanId`/`traceFlags` into every log via a Pino mixin when an active span is detected. Resolution is anchored at the library's own module path, so a Docker `WORKDIR`, a pnpm workspace or a monorepo launched from the repo root cannot silently switch correlation off
|
|
77
|
-
- ✅ **Stable Resource Identity** — `service.name`/`.namespace`/`.version`/`.instance.id` and `deployment.environment.name`, all **Stable** in Semantic Conventions v1.44.0, resolved from one deterministic precedence shared with the OTel SDK
|
|
78
|
-
- ✅ **Semconv Error Fields** — opt-in `exception.type`/`.message`/`.stacktrace` and low-cardinality `error.type`, additive beside the legacy `err.*`, with full `Error.cause` chains
|
|
79
|
-
- ✅ **Machine-Readable Event Names** — `event.name` derived from `logKey` following OTel naming rules
|
|
80
|
-
- ✅ **AsyncLocalStorage Context** — `requestId`, `tenantId`, `userId` flow automatically through the request lifecycle without prop drilling
|
|
81
|
-
- ✅ **HTTP Access Log, before guards** — logs every request including the ones an interceptor cannot see (401/403/429 guard rejections, 404 unmatched routes), with URL normalization (UUID, ULID, nanoid and numeric segments replaced by `:id`) and the query string stripped
|
|
82
|
-
- ✅ **Exception Filter** — captures NestJS `HttpException` and unexpected errors with structured output
|
|
83
|
-
|
|
84
|
-
### 🔌 Destinations
|
|
85
|
-
|
|
86
|
-
- ✅ **Pluggable Destinations** — implement `ILogDestination` to ship logs to Loki, Postgres, rolling files, or any sink
|
|
87
|
-
- ✅ **Managed Lifecycle** — `onInit()` / `onShutdown()` hooks; a destination that fails `onInit()` is reported and removed from the write fan-out and from shutdown, and boot is never aborted
|
|
88
|
-
- ✅ **Crash-Proof Writes** — every `write()` is wrapped in a try/catch; a failure is reported on `stderr` and swallowed, never propagated to the app
|
|
89
|
-
|
|
90
|
-
### 🧩 Developer Experience
|
|
91
|
-
|
|
92
|
-
- ✅ **Zero Runtime Dependencies** — everything arrives as a peer dependency, so you control versions and supply-chain surface
|
|
93
|
-
- ✅ **2 Subpath Exports** — `.` for the NestJS server API, `./shared` for zero-dependency types and constants
|
|
94
|
-
- ✅ **Dynamic Module** — configure via `forRoot()` or `forRootAsync()`, sensible defaults included
|
|
95
|
-
- ✅ **Strict TypeScript** — `strict: true`, no `any` in production code, JSDoc on every public export
|
|
96
|
-
- ✅ **100% Coverage + Mutation Tested** — statements, branches, functions, and lines gated at 100%, with Stryker as the deeper gate
|
|
50
|
+
- ✅ **Structured JSON** with `MODULE_ACTION_RESULT` log keys and an exported regex for CI
|
|
51
|
+
- ✅ **NestJS `LoggerService` bridge**: framework logs flow through Pino
|
|
52
|
+
- ✅ **PII redaction by default**: 32 field names censored to a 100-level ceiling, append-only list
|
|
53
|
+
- ✅ **Per-field size guard**: an oversized field becomes a truncation envelope
|
|
54
|
+
- ✅ **OpenTelemetry correlation**: `traceId`/`spanId`/`traceFlags` from the active span, validated
|
|
55
|
+
- ✅ **Stable resource identity** and opt-in semconv error fields with `Error.cause` chains
|
|
56
|
+
- ✅ **`AsyncLocalStorage` context**: `requestId`, `tenantId`, `userId` without prop drilling
|
|
57
|
+
- ✅ **HTTP access log before guards**: 401/403/429 and 404 are logged, URLs normalized, query stripped
|
|
58
|
+
- ✅ **Pluggable destinations** with managed lifecycle; a failing sink never reaches the app
|
|
59
|
+
- ✅ **Dev-friendly output**: opt-in `PrettyDevDestination` with a configurable view
|
|
60
|
+
- ✅ **Zero runtime dependencies**, two subpath exports, strict TypeScript, 100% coverage and mutation score
|
|
97
61
|
|
|
98
62
|
---
|
|
99
63
|
|
|
@@ -117,25 +81,17 @@ The `/shared` subpath is safe to import in isomorphic code, test helpers, CLI sc
|
|
|
117
81
|
---
|
|
118
82
|
|
|
119
83
|
> [!TIP]
|
|
120
|
-
> Prefer to learn from a working app? See
|
|
84
|
+
> Prefer to learn from a working app? See [nest-logger-example](https://github.com/bymaxone/nest-logger-example), a full NestJS project wired with this library.
|
|
121
85
|
|
|
122
86
|
## 🚀 Quick Start
|
|
123
87
|
|
|
124
88
|
### 1. Install
|
|
125
89
|
|
|
126
90
|
```bash
|
|
127
|
-
# Using pnpm (recommended)
|
|
128
91
|
pnpm add @bymax-one/nest-logger
|
|
129
|
-
|
|
130
|
-
# Using npm
|
|
131
|
-
npm install @bymax-one/nest-logger
|
|
132
|
-
|
|
133
|
-
# Using yarn
|
|
134
|
-
yarn add @bymax-one/nest-logger
|
|
135
92
|
```
|
|
136
93
|
|
|
137
|
-
|
|
138
|
-
> You must also install the required **peer dependencies**. The library ships `"dependencies": {}`, so nothing arrives implicitly:
|
|
94
|
+
The library ships `"dependencies": {}`, so install the **peer dependencies** yourself:
|
|
139
95
|
|
|
140
96
|
```bash
|
|
141
97
|
# Server subpath (required)
|
|
@@ -146,43 +102,12 @@ pnpm add -D pino-pretty
|
|
|
146
102
|
|
|
147
103
|
# Optional — OpenTelemetry trace correlation
|
|
148
104
|
pnpm add @opentelemetry/api @opentelemetry/sdk-node
|
|
149
|
-
|
|
150
105
|
```
|
|
151
106
|
|
|
152
|
-
>
|
|
153
|
-
>
|
|
154
|
-
> by two different build routes: `pnpm prune --prod` keeps the store entry, and a clean
|
|
155
|
-
> `pnpm install --prod --frozen-lockfile` in a fresh stage installs it too. In both, the peer was
|
|
156
|
-
> recorded in the lockfile. `PrettyDevDestination` imports it lazily, relative to the library's own
|
|
157
|
-
> directory under `.pnpm/`, where it is a sibling — so it resolves.
|
|
158
|
-
>
|
|
159
|
-
> That is two measurements, not a law of pnpm: whether a production install always carries an optional
|
|
160
|
-
> peer, however the lockfile was produced, has not been tested here. The advice below does not depend
|
|
161
|
-
> on it.
|
|
162
|
-
>
|
|
163
|
-
> The clean-install case is worth stating separately, because "we do a fresh prod install, not a
|
|
164
|
-
> prune" reads like an exemption and is not one. It is what one of those consumers concluded before
|
|
165
|
-
> measuring their own image.
|
|
166
|
-
>
|
|
167
|
-
> **On other package managers this is different**, and the difference cuts the other way: under npm's
|
|
168
|
-
> or yarn's flat `node_modules`, a pruned devDependency really is gone. If you install with those,
|
|
169
|
-
> do not read this warning as universal.
|
|
170
|
-
>
|
|
171
|
-
> Either way, the rule that survives both layouts: **"it is a devDependency, therefore this path
|
|
172
|
-
> cannot run in production" is not a safe premise, because the premise is about someone else's
|
|
173
|
-
> install command.** `PrettyDevDestination` refuses to initialize when `NODE_ENV` is exactly
|
|
174
|
-
> `production`: it reports `LOGGER_DESTINATION_INIT_FAILED` on stderr and, when it is the only
|
|
175
|
-
> destination, entries go to stdout as raw NDJSON. In any other environment that ships to a log
|
|
176
|
-
> pipeline (a staging stack with `NODE_ENV=staging`, an unset `NODE_ENV`) it still renders ANSI
|
|
177
|
-
> colour into a pipeline that will fail to parse every line, which is indistinguishable from a
|
|
178
|
-
> service that went quiet. Gate it on an explicit configuration value you can see, not on the
|
|
179
|
-
> packaging.
|
|
180
|
-
|
|
181
|
-
> [!NOTE]
|
|
182
|
-
> `@opentelemetry/api` is resolved lazily when the Pino instance is built. When it is absent the trace mixin silently steps aside — the logger never fails to start, and never warns, over an optional peer. A copy that is installed but broken is different: it is reported once on `stderr` as `LOGGER_OTEL_API_BROKEN`, because correlation would otherwise be off with no sign.
|
|
107
|
+
> [!WARNING]
|
|
108
|
+
> **Under pnpm, `-D` does not guarantee that a peer is absent from a production image**: it was measured present after both `pnpm prune --prod` and a clean `pnpm install --prod --frozen-lockfile`. Under npm or yarn a pruned devDependency really is gone. Do not rely on packaging to keep `PrettyDevDestination` out of production: it refuses to initialize when `NODE_ENV` is exactly `production`, but in any other environment that feeds a log pipeline (staging, an unset `NODE_ENV`) it writes ANSI colour that the pipeline cannot parse. Gate it on an explicit configuration value.
|
|
183
109
|
|
|
184
|
-
|
|
185
|
-
> The published declarations depend on no HTTP framework's types. The HTTP interceptor, the exception filter and the request-id middleware are typed by structural contracts (`LoggableRequest`, `LoggableResponse`, `NextHandler`) that an Express request and response satisfy as-is, so nothing extra is needed even when you compile with `skipLibCheck: false`. The emitted `.d.ts` imports only `@nestjs/common`, `pino` and `rxjs`.
|
|
110
|
+
`@opentelemetry/api` is resolved lazily. When it is absent the trace mixin steps aside silently; a copy that is installed but broken is reported once on `stderr` as `LOGGER_OTEL_API_BROKEN`. The published declarations depend on no HTTP framework's types: the interceptor, filter and request-id middleware use structural contracts (`LoggableRequest`, `LoggableResponse`, `NextHandler`) that an Express request and response satisfy as-is.
|
|
186
111
|
|
|
187
112
|
### 2. Register the module
|
|
188
113
|
|
|
@@ -233,13 +158,10 @@ import { BymaxLoggerModule } from '@bymax-one/nest-logger'
|
|
|
233
158
|
export class AppModule {}
|
|
234
159
|
```
|
|
235
160
|
|
|
161
|
+
`forRootAsync` also accepts `useClass` or `useExisting` with a class implementing `BymaxLoggerModuleOptionsFactory` (see the Configuration section). Options from any form pass the same validation as `forRoot`, and an error thrown while producing them fails module initialisation.
|
|
162
|
+
|
|
236
163
|
> [!IMPORTANT]
|
|
237
|
-
> **`forRootAsync` does not register the exception filter.** With `http.isEnabled` it registers the
|
|
238
|
-
> access log (`HTTP_REQUEST_START`, `_SUCCESS`, `_CLIENT_ERROR`, `_SERVER_ERROR`, `_ABORTED`), and the
|
|
239
|
-
> failing request's error still reaches its terminal entry. The two entries the filter writes,
|
|
240
|
-
> `HTTP_EXCEPTION_HANDLED` and `HTTP_EXCEPTION_UNHANDLED`, are not emitted, and
|
|
241
|
-
> `http.shouldCaptureExceptions` has no effect on this path. `forRoot` registers the filter itself.
|
|
242
|
-
> To get the same entries from `forRootAsync`, register it:
|
|
164
|
+
> **`forRootAsync` does not register the exception filter.** With `http.isEnabled` it registers the access log, but `HTTP_EXCEPTION_HANDLED` and `HTTP_EXCEPTION_UNHANDLED` are not emitted and `http.shouldCaptureExceptions` has no effect. Register it yourself:
|
|
243
165
|
>
|
|
244
166
|
> ```typescript
|
|
245
167
|
> import { Module } from '@nestjs/common'
|
|
@@ -249,41 +171,6 @@ export class AppModule {}
|
|
|
249
171
|
> @Module({ providers: [{ provide: APP_FILTER, useClass: HttpExceptionFilter }] })
|
|
250
172
|
> export class LoggingFilterModule {}
|
|
251
173
|
> ```
|
|
252
|
-
>
|
|
253
|
-
> It is left to you on purpose: the filter is a global catch-all that writes the response itself, and
|
|
254
|
-
> a library adding one from asynchronously resolved options would put it in the pipeline of every
|
|
255
|
-
> consumer, including those with HTTP logging off or with their own filters.
|
|
256
|
-
|
|
257
|
-
`useFactory` is one of three forms. When the options depend on a provider already in the DI graph, a class can produce them instead. It implements `BymaxLoggerModuleOptionsFactory`; pass it as `useClass` to have the module instantiate it, or as `useExisting` to reuse an instance another module already provides:
|
|
258
|
-
|
|
259
|
-
```typescript
|
|
260
|
-
// logger-options.factory.ts
|
|
261
|
-
import { Injectable } from '@nestjs/common'
|
|
262
|
-
import { ConfigService } from '@nestjs/config'
|
|
263
|
-
import type {
|
|
264
|
-
BymaxLoggerModuleOptions,
|
|
265
|
-
BymaxLoggerModuleOptionsFactory
|
|
266
|
-
} from '@bymax-one/nest-logger'
|
|
267
|
-
|
|
268
|
-
@Injectable()
|
|
269
|
-
export class LoggerOptionsFactory implements BymaxLoggerModuleOptionsFactory {
|
|
270
|
-
constructor(private readonly cfg: ConfigService) {}
|
|
271
|
-
|
|
272
|
-
createLoggerOptions(): BymaxLoggerModuleOptions {
|
|
273
|
-
return {
|
|
274
|
-
service: {
|
|
275
|
-
name: this.cfg.getOrThrow<string>('OTEL_SERVICE_NAME'),
|
|
276
|
-
version: this.cfg.getOrThrow<string>('RELEASE_SHA')
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// app.module.ts: imports: [BymaxLoggerModule.forRootAsync({ imports: [ConfigModule], useClass: LoggerOptionsFactory })]
|
|
283
|
-
// or, to reuse an instance another module exports: { imports: [OptionsModule], useExisting: LoggerOptionsFactory }
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
`createLoggerOptions()` may return the options or a promise of them. An error thrown from it, or from `useFactory`, fails module initialisation, and the options it returns go through the same validation as `forRoot`.
|
|
287
174
|
|
|
288
175
|
### 4. Inject the logger in a service
|
|
289
176
|
|
|
@@ -343,7 +230,7 @@ Output (JSON, production) for the `PAYMENT_REFUND_SUCCESS` call above, with the
|
|
|
343
230
|
}
|
|
344
231
|
```
|
|
345
232
|
|
|
346
|
-
`requestId` and `tenantId` are added when the call runs inside an HTTP request that passed through the request-ID middleware (`tenantId` only when the request carries the tenant header), and `traceId` and `spanId` when an OpenTelemetry span is active (see [OpenTelemetry correlation](
|
|
233
|
+
`requestId` and `tenantId` are added when the call runs inside an HTTP request that passed through the request-ID middleware (`tenantId` only when the request carries the tenant header), and `traceId` and `spanId` when an OpenTelemetry span is active (see [OpenTelemetry correlation](#-opentelemetry-correlation)). Outside a request, as in the flow above, they are absent.
|
|
347
234
|
|
|
348
235
|
Output (pretty-print, development):
|
|
349
236
|
|
|
@@ -353,9 +240,74 @@ Output (pretty-print, development):
|
|
|
353
240
|
stripeRefundId: "re_abc"
|
|
354
241
|
```
|
|
355
242
|
|
|
356
|
-
### 5.
|
|
243
|
+
### 5. Next steps
|
|
244
|
+
|
|
245
|
+
Wire the access log in `main.ts` with `applyAccessLog(app)` (see [HTTP Logging](#-http-logging)), enable [OpenTelemetry correlation](#-opentelemetry-correlation), and read the Configuration tables for every option.
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## ⚙️ Configuration
|
|
250
|
+
|
|
251
|
+
Full options reference for `BymaxLoggerModule.forRoot(options)`:
|
|
252
|
+
|
|
253
|
+
### Top-level options
|
|
254
|
+
|
|
255
|
+
| Option | Type | Default | Description |
|
|
256
|
+
| ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
257
|
+
| `service.name` | `string` | **Required** | Service name emitted in every log entry |
|
|
258
|
+
| `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
|
|
259
|
+
| `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
|
|
260
|
+
| `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#resource-identity) |
|
|
261
|
+
| `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
|
|
262
|
+
| `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
|
|
263
|
+
| `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
|
|
264
|
+
| `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
|
|
265
|
+
| `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
|
|
266
|
+
| `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
|
|
267
|
+
| `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` is the legacy `fast-redact` expansion (four-level ceiling, much slower) |
|
|
268
|
+
| `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
|
|
269
|
+
| `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
|
|
270
|
+
| `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
|
|
271
|
+
| `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see [Error fields](#error-fields)). A binary value is written as its size in both. Recommended: `'safe'` |
|
|
272
|
+
| `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
|
|
273
|
+
| `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
|
|
274
|
+
| `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
|
|
275
|
+
| `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
|
|
276
|
+
| `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
|
|
277
|
+
| `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
|
|
278
|
+
|
|
279
|
+
### `http` options
|
|
280
|
+
|
|
281
|
+
| Option | Type | Default | Description |
|
|
282
|
+
| ------------------------------ | ------------------------------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
283
|
+
| `http.isEnabled` | `boolean` | `false` | Register `HttpLoggingInterceptor` (and, on `forRoot`, `HttpExceptionFilter`) globally |
|
|
284
|
+
| `http.shouldCaptureExceptions` | `boolean` | `true` | Capture unhandled HTTP exceptions and emit `HTTP_EXCEPTION_UNHANDLED`. `forRoot` only: see the note under [Async configuration](#3-async-configuration-with-configservice) |
|
|
285
|
+
| `http.shouldGenerateRequestId` | `boolean` | `true` | Generate a `requestId` when the inbound request header is absent |
|
|
286
|
+
| `http.excludePaths` | `RegExp[]` | `[/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/]` | Paths that bypass HTTP logging. Use anchored, linear-time regexes (ReDoS-safe) |
|
|
287
|
+
| `http.tenantIdHeader` | `string \| false` | `'x-tenant-id'` | Request header carrying the tenant identifier, or `false` to read none. A value from the header is what the client asserted: see [Inbound `x-request-id` and tenant header](#inbound-x-request-id-and-tenant-header) |
|
|
288
|
+
| `http.tenantIdResolver` | `(req) => string \| undefined` | none | Resolves the tenant id on the server side. When given it is the only source and the header is not read |
|
|
289
|
+
|
|
290
|
+
### `otel` options
|
|
291
|
+
|
|
292
|
+
| Option | Type | Default | Description |
|
|
293
|
+
| ----------------------------------- | ----------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- |
|
|
294
|
+
| `otel.shouldAutoInjectTraceContext` | `boolean` | `true` | Detect `@opentelemetry/api` and inject `traceId`/`spanId` via Pino mixin |
|
|
295
|
+
| `otel.fieldFormat` | `'camelCase' \| 'snake_case'` | `'camelCase'` | Field names in log entries: `traceId`/`spanId` vs `trace_id`/`span_id` |
|
|
296
|
+
| `otel.traceIdField` | `string` | `'traceId'` | Field name for the trace ID; `fieldFormat: 'snake_case'` derives `trace_id` unless this is set |
|
|
297
|
+
| `otel.spanIdField` | `string` | `'spanId'` | Field name for the span ID; `fieldFormat: 'snake_case'` derives `span_id` unless this is set |
|
|
298
|
+
| `otel.traceFlagsField` | `string` | `'traceFlags'` | Field name for the trace flags; `fieldFormat: 'snake_case'` derives `trace_flags` unless this is set |
|
|
299
|
+
|
|
300
|
+
### Options from a class
|
|
301
|
+
|
|
302
|
+
`forRootAsync` accepts a class that produces the options, for when they depend on a provider already in the DI graph. It implements `BymaxLoggerModuleOptionsFactory`; pass it as `useClass` (the module instantiates it) or `useExisting` (an instance another module provides). `createLoggerOptions()` may return the options or a promise of them.
|
|
303
|
+
|
|
304
|
+
For example, `createLoggerOptions()` can return `{ service: { name: this.cfg.getOrThrow('OTEL_SERVICE_NAME'), version: this.cfg.getOrThrow('RELEASE_SHA') } }`, registered with `forRootAsync({ imports: [ConfigModule], useClass: LoggerOptionsFactory })`.
|
|
357
305
|
|
|
358
|
-
|
|
306
|
+
---
|
|
307
|
+
|
|
308
|
+
## 🌐 HTTP Logging
|
|
309
|
+
|
|
310
|
+
Set `http.isEnabled: true`, then wire the access log with `applyAccessLog(app)` in `main.ts` (recommended, see below) or `applyRequestIdMiddleware(consumer)`. The access log is recorded from **middleware** and emits six `HTTP_REQUEST_*` keys; the exception filter adds the last two:
|
|
359
311
|
|
|
360
312
|
| Log key | When |
|
|
361
313
|
| --------------------------- | --------------------------------------------------- |
|
|
@@ -368,59 +320,25 @@ Enable `http.isEnabled: true` in the module options and wire the access log —
|
|
|
368
320
|
| `HTTP_EXCEPTION_HANDLED` | `HttpException` caught by the filter |
|
|
369
321
|
| `HTTP_EXCEPTION_UNHANDLED` | Unexpected error caught by the filter |
|
|
370
322
|
|
|
371
|
-
`HTTP_REQUEST_START` is emitted **before guards**, so it carries no `userId
|
|
372
|
-
in a guard, and at that point there is no principal yet. The acting user is on the **terminal**
|
|
373
|
-
entry, where the guard has populated it. Both entries carry the same `requestId`, so joining on
|
|
374
|
-
that gives the whole request.
|
|
323
|
+
`HTTP_REQUEST_START` is emitted **before guards**, so it carries no `userId`: authentication runs in a guard and there is no principal yet. The acting user is on the terminal entry. Both entries carry the same `requestId`.
|
|
375
324
|
|
|
376
|
-
|
|
325
|
+
URLs are normalized (`/users/550e8400-e29b-41d4-a716-446655440000` becomes `/users/:id`) so label cardinality stays bounded. The **query string is stripped** from every logged URL and from the message of a logged exception, because a magic-link token in a query parameter is a secret no key-name redaction can scrub out of a string. Only a literal `?` starts a query: a secret placed in the path itself (`;jsessionid=...`, a token segment) stays in `url`.
|
|
377
326
|
|
|
378
|
-
|
|
327
|
+
For a body that does not parse (`entity.parse.failed`), one the parser's `verify` refuses (`entity.verify.failed`), or an unsupported content encoding or charset, `HTTP_EXCEPTION_HANDLED` carries a fixed message and the parser `type` in `bodyParserType`, because the parser's message can quote part of the body. The response the client receives is the application's concern. The malformed-JSON case needs the Express adapter and a body parser mounted before `app.init()`, as Nest's default one is; with another adapter, or a parser mounted after `app.init()`, that entry keeps the parser's message.
|
|
379
328
|
|
|
380
329
|
> [!IMPORTANT]
|
|
381
|
-
> **Why middleware and not an interceptor.** NestJS runs middleware → guards → interceptors →
|
|
382
|
-
> handler, so an interceptor never observes a request a guard rejected, and never observes one that
|
|
383
|
-
> matched no route. Measured against a real backend: **401, 403, 429 from a throttler and 404 for an
|
|
384
|
-
> unknown path produced no log line at all** — not even `HTTP_REQUEST_START` — so brute force,
|
|
385
|
-
> credential stuffing and route enumeration were invisible, and invisible without a `requestId` to
|
|
386
|
-
> correlate them by. The access log therefore runs before guards.
|
|
387
|
-
>
|
|
388
|
-
> A consumer who does not wire the middleware keeps the previous interceptor-based behaviour rather
|
|
389
|
-
> than losing HTTP logs — including its blind spot.
|
|
390
|
-
|
|
391
|
-
#### Requests rejected before routing
|
|
392
|
-
|
|
393
|
-
Middleware wired through `configure(consumer)` is not early enough for every request. NestJS
|
|
394
|
-
registers the body parser **one line before** it registers module middleware:
|
|
395
|
-
|
|
396
|
-
```js
|
|
397
|
-
// @nestjs/core/nest-application.js
|
|
398
|
-
useBodyParser && this.registerParserMiddleware()
|
|
399
|
-
await this.registerModules() // everything from configure(consumer)
|
|
400
|
-
```
|
|
330
|
+
> **Why middleware and not an interceptor.** NestJS runs middleware → guards → interceptors → handler, so an interceptor never sees a request a guard rejected or one that matched no route. Measured against a real backend, 401, 403, 429 and 404 produced no log line at all, which hid brute force and route enumeration. Without the middleware wiring, the interceptor-based behaviour remains, blind spot included.
|
|
401
331
|
|
|
402
|
-
|
|
403
|
-
and every remaining non-error handler is skipped — module middleware, guards, interceptors and the
|
|
404
|
-
route handler all never run. **A `POST` carrying truncated JSON therefore produces no access log
|
|
405
|
-
at all**, and the same hole covers a payload over the body limit and an unsupported content type:
|
|
406
|
-
exactly the requests a client got wrong or an attacker shaped.
|
|
332
|
+
### Requests rejected before routing
|
|
407
333
|
|
|
408
|
-
|
|
334
|
+
NestJS registers the body parser one line **before** it registers module middleware, so when the parser rejects a body (truncated JSON, a payload over the limit, an unsupported content type) every later handler is skipped. Through `configure(consumer)` that request produces:
|
|
409
335
|
|
|
410
336
|
| Wiring | A body the parser rejects produces |
|
|
411
337
|
| ------------------------------------------------------ | --------------------------------------------------------- |
|
|
412
338
|
| `forRoot` with `shouldCaptureExceptions` (the default) | **one** `HTTP_EXCEPTION_HANDLED` line, **no `requestId`** |
|
|
413
339
|
| `forRootAsync`, or `shouldCaptureExceptions: false` | **nothing at all** |
|
|
414
340
|
|
|
415
|
-
|
|
416
|
-
looks healthy — but the correlation scope is mounted behind the parser too, so it never opened:
|
|
417
|
-
the client can send `x-request-id: measure-me` and the entry carries no `requestId` to join it to.
|
|
418
|
-
A 400 you cannot trace to the caller is the same defect as a missing 400 wearing a healthier face.
|
|
419
|
-
|
|
420
|
-
`applyAccessLog(app)` closes both rows. `INestApplication.use()` delegates straight to the HTTP
|
|
421
|
-
adapter and `init()` (where the parser is registered) does not run until `listen()`, so mounting
|
|
422
|
-
from `main.ts` lands **ahead** of the parser — the same reason `helmet` and `cookie-parser` are
|
|
423
|
-
mounted this way:
|
|
341
|
+
`applyAccessLog(app)` closes both rows. `INestApplication.use()` delegates to the HTTP adapter and `init()` (where the parser is registered) has not run yet, so mounting from `main.ts` lands ahead of the parser, the same way `helmet` and `cookie-parser` are mounted:
|
|
424
342
|
|
|
425
343
|
```typescript
|
|
426
344
|
// main.ts
|
|
@@ -444,51 +362,17 @@ async function bootstrap() {
|
|
|
444
362
|
void bootstrap()
|
|
445
363
|
```
|
|
446
364
|
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
`
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
`http.shouldCaptureExceptions`, which defaults to `true`) registers the library's own exception
|
|
459
|
-
filter as an `APP_FILTER` provider; `forRootAsync` never does, so there is nothing for yours to
|
|
460
|
-
compete with unless you registered `HttpExceptionFilter` yourself. Where the library's filter is
|
|
461
|
-
registered, the order the modules are imported decides between `APP_FILTER` providers: one in your
|
|
462
|
-
root module, or in a module imported before `BymaxLoggerModule`, was answered by the library's
|
|
463
|
-
filter in the measurement, with or without an injected dependency, while one in a module imported
|
|
464
|
-
after it answered itself. It can be combined with `applyAccessLog(app)` or
|
|
465
|
-
`applyRequestIdMiddleware(consumer)`: a second mount reuses the scope.
|
|
466
|
-
|
|
467
|
-
`applyRequestIdMiddleware(consumer)` remains supported and unchanged; it is the right choice when
|
|
468
|
-
correlation should be scoped to a route subtree rather than the whole application. **Wiring both is
|
|
469
|
-
safe** — the correlation middleware adopts an id already in scope instead of minting a second one,
|
|
470
|
-
and the access log stands down when it finds the request's lifecycle already claimed, so nothing is
|
|
471
|
-
minted twice and nothing is logged twice.
|
|
472
|
-
|
|
473
|
-
**Delivery is reported separately from status.** `HTTP_REQUEST_ABORTED` is emitted when the
|
|
474
|
-
connection closed before the response was flushed, and it **keeps the real status the server
|
|
475
|
-
produced** rather than inventing one: nginx's `499` is not an HTTP status (IANA leaves 452–499
|
|
476
|
-
unassigned), so recording it would assert a code the protocol has no name for and break any
|
|
477
|
-
consumer grouping by class.
|
|
478
|
-
|
|
479
|
-
Its limit is worth stating: `writableFinished` distinguishes a response still in flight from one
|
|
480
|
-
handed to the operating system. A **fast handler whose client hangs up after the bytes were
|
|
481
|
-
flushed** is reported as the success it was — the server completed and flushed it, and whether the
|
|
482
|
-
peer read it is not knowable from the server side. What this catches is the case that matters
|
|
483
|
-
operationally: the slow upstream, the load-balancer timeout, the cancelled request.
|
|
484
|
-
|
|
485
|
-
#### Unexpected errors behind `@bymax-one/nest-core`
|
|
486
|
-
|
|
487
|
-
When nest-core's exception filter answers, an unexpected error becomes a fixed
|
|
488
|
-
`500 BYMAX_INTERNAL_ERROR`. The access-log line for that response carries the cause only when this
|
|
489
|
-
package's HTTP interceptor saw the error, which it does not for an error raised before it (in a
|
|
490
|
-
guard or a middleware) or with HTTP logging off. nest-core 1.6.2 adds an optional sink token, `BYMAX_UNEXPECTED_ERROR_SINK`, and
|
|
491
|
-
`PinoUnexpectedErrorSink` is a ready implementation of it. Bind it from a global module:
|
|
365
|
+
Mount it **before** `app.init()`: a serverless entry point or a test that calls `await app.init()` first must mount before that, not merely before `listen()`. The access log emits from the response's `'close'` event, so it needs no route match, handler or filter: one line in and one line out for a parser rejection, an unmatched-route 404, a guard rejection and an aborted connection alike.
|
|
366
|
+
|
|
367
|
+
To open only the correlation scope ahead of the parser, without the access log, call `BymaxLoggerModule.useRequestContext(app)` at the same point. A request the parser refuses then has its `requestId` and the `x-request-id` response header, so an exception filter that reads the id from `LogContextService` can put the same value in its envelope. Register such a filter with `app.useGlobalFilters(...)`, which answers ahead of every `APP_FILTER` provider. Where the library's own filter is registered (`forRoot` with `http.isEnabled`), the import order of modules decides between `APP_FILTER` providers: one in a module imported before `BymaxLoggerModule` was answered by the library's filter in the measurement, one imported after it answered itself.
|
|
368
|
+
|
|
369
|
+
`applyRequestIdMiddleware(consumer)` remains supported and suits correlation scoped to a route subtree. Wiring both is safe: the correlation middleware adopts an id already in scope and the access log stands down when the lifecycle is already claimed, so nothing is minted or logged twice.
|
|
370
|
+
|
|
371
|
+
**Delivery is reported separately from status.** `HTTP_REQUEST_ABORTED` is emitted when the connection closed before the response was flushed, and it keeps the real status the server produced rather than inventing one (`499` is not an HTTP status). A fast handler whose client hangs up after the bytes were flushed is reported as the success it was; whether the peer read it is not knowable server-side.
|
|
372
|
+
|
|
373
|
+
### Unexpected errors behind `@bymax-one/nest-core`
|
|
374
|
+
|
|
375
|
+
When nest-core's exception filter answers, an unexpected error becomes a fixed `500 BYMAX_INTERNAL_ERROR`, and the access-log line carries the cause only if this package's interceptor saw the error (not for an error raised in a guard or a middleware, or with HTTP logging off). With nest-core 1.6.2 or later, bind `PinoUnexpectedErrorSink` to its `BYMAX_UNEXPECTED_ERROR_SINK` token from a global module:
|
|
492
376
|
|
|
493
377
|
```typescript
|
|
494
378
|
import { Global, Module } from '@nestjs/common'
|
|
@@ -503,11 +387,7 @@ import { PinoUnexpectedErrorSink } from '@bymax-one/nest-logger'
|
|
|
503
387
|
export class UnexpectedErrorSinkModule {}
|
|
504
388
|
```
|
|
505
389
|
|
|
506
|
-
Import it next to `BymaxLoggerModule`. The binding resolves `PinoLoggerService` because
|
|
507
|
-
`BymaxLoggerModule` is global by default; with `isGlobal: false`, add the same `forRoot`/`forRootAsync` result the
|
|
508
|
-
application imports to the sink module's `imports`. Keep it in a constant: calling `forRoot` a
|
|
509
|
-
second time builds a second logger. Each unexpected error then produces one `error` entry with the key
|
|
510
|
-
`HTTP_UNEXPECTED_ERROR`:
|
|
390
|
+
Import it next to `BymaxLoggerModule`. The binding resolves `PinoLoggerService` because that module is global by default; with `isGlobal: false`, add the same `forRoot`/`forRootAsync` result to the sink module's `imports`, kept in a constant (a second `forRoot` call builds a second logger). Each unexpected error then produces one `error` entry with the key `HTTP_UNEXPECTED_ERROR`:
|
|
511
391
|
|
|
512
392
|
| Field | Content |
|
|
513
393
|
| --------------- | ------------------------------------------------------------------------------------------------------- |
|
|
@@ -516,17 +396,13 @@ second time builds a second logger. Each unexpected error then produces one `err
|
|
|
516
396
|
| `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
|
|
517
397
|
| `correlationId` | nest-core's correlation id, when one resolved |
|
|
518
398
|
|
|
519
|
-
The sink adds
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
of the headers) brings that data along, under the same key-name redaction. The trace id comes from the trace mixin, as on every other entry. `record()`
|
|
523
|
-
never throws, so a failing destination cannot change the response. This package does not import
|
|
524
|
-
nest-core: the class matches nest-core's contract by shape, and `IUnexpectedErrorSink` /
|
|
525
|
-
`UnexpectedErrorReport` are exported for reference.
|
|
399
|
+
The sink adds no body, headers or query string. The error is serialized as on every `err` entry, own fields included, so an error that itself carries request data brings it along, under the same key-name redaction. `record()` never throws, so a failing destination cannot change the response. This package does not import nest-core: the class matches its contract by shape, and `IUnexpectedErrorSink` and `UnexpectedErrorReport` are exported for reference.
|
|
400
|
+
|
|
401
|
+
---
|
|
526
402
|
|
|
527
|
-
|
|
403
|
+
## 🔭 OpenTelemetry Correlation
|
|
528
404
|
|
|
529
|
-
Initialize the OTel SDK **before** importing NestJS
|
|
405
|
+
Initialize the OTel SDK **before** importing NestJS:
|
|
530
406
|
|
|
531
407
|
```typescript
|
|
532
408
|
// main.ts (top of file — before any NestJS import)
|
|
@@ -568,30 +444,15 @@ async function bootstrap() {
|
|
|
568
444
|
void bootstrap()
|
|
569
445
|
```
|
|
570
446
|
|
|
571
|
-
Once active, every
|
|
572
|
-
|
|
573
|
-
**Without OpenTelemetry installed, everything above simply does not happen** — no error, no warning
|
|
574
|
-
on every log, no crash. The peer is optional and the logger is fully usable on its own. The one
|
|
575
|
-
case that _is_ reported is a misconfiguration: if trace injection is enabled and
|
|
576
|
-
`@opentelemetry/api` cannot be resolved, a single `LOGGER_BOOTSTRAP_WARNING` naming
|
|
577
|
-
`OTEL_API_UNAVAILABLE` is emitted at startup. Absence of `traceId` would otherwise be
|
|
578
|
-
indistinguishable from "no active span".
|
|
447
|
+
Once active, every entry carries `traceId`, `spanId` and `traceFlags`. The logger **observes** the trace context: it never creates spans, installs a context manager or parses `traceparent`. With the API present but no active span, no identifiers are emitted.
|
|
579
448
|
|
|
580
|
-
|
|
581
|
-
parses `traceparent` by hand. When the API is present but no span is active, no identifiers are
|
|
582
|
-
emitted — none are invented.
|
|
449
|
+
**Without OpenTelemetry installed, none of this happens** and there is no error or per-entry warning. The one reported misconfiguration is trace injection enabled while `@opentelemetry/api` cannot be resolved: a single `LOGGER_BOOTSTRAP_WARNING` with reason `OTEL_API_UNAVAILABLE` at startup, because a missing `traceId` would otherwise look like "no active span". The peer is resolved from the library's own module path, falling back to `process.cwd()`, so a Docker `WORKDIR`, a hoisted workspace or a monorepo started at its root does not switch correlation off.
|
|
583
450
|
|
|
584
|
-
|
|
585
|
-
> Resolution of the optional peer is anchored at the **library's own module path**, falling back to
|
|
586
|
-
> `process.cwd()`. Anchoring only at the working directory — as versions before this did — silently
|
|
587
|
-
> disabled correlation whenever the process was launched from somewhere other than the application
|
|
588
|
-
> root: a Docker `WORKDIR`, a pnpm/Yarn workspace with hoisted `node_modules`, a monorepo started at
|
|
589
|
-
> the repository root, a serverless bundle.
|
|
451
|
+
## 🧭 Resource, Events and Errors
|
|
590
452
|
|
|
591
|
-
###
|
|
453
|
+
### Resource identity
|
|
592
454
|
|
|
593
|
-
Every entry carries the service identity, using attributes that are **Stable** in Semantic
|
|
594
|
-
Conventions v1.44.0:
|
|
455
|
+
Every entry carries the service identity, using attributes that are **Stable** in Semantic Conventions v1.44.0:
|
|
595
456
|
|
|
596
457
|
```typescript
|
|
597
458
|
BymaxLoggerModule.forRoot({
|
|
@@ -622,136 +483,48 @@ BymaxLoggerModule.forRoot({
|
|
|
622
483
|
}
|
|
623
484
|
```
|
|
624
485
|
|
|
625
|
-
Set `resourceFormat: 'flat'` to emit the dotted
|
|
626
|
-
(`"service.instance.id": "pod-7f3a"`), which is what a collector mapping log fields onto resource
|
|
627
|
-
attributes reads directly.
|
|
628
|
-
|
|
629
|
-
#### Precedence
|
|
486
|
+
Set `resourceFormat: 'flat'` to emit the dotted names verbatim (`"service.instance.id": "pod-7f3a"`), which is what a collector mapping log fields onto resource attributes reads directly. The deprecated `deployment.environment` spelling is never emitted.
|
|
630
487
|
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
1. **explicit `service` options**
|
|
634
|
-
2. **`OTEL_SERVICE_NAME`** (name only)
|
|
635
|
-
3. **`OTEL_RESOURCE_ATTRIBUTES`** (`service.namespace=payments,service.version=2.14.3,…`)
|
|
636
|
-
4. **`NODE_ENV`** (environment only)
|
|
637
|
-
|
|
638
|
-
Explicit configuration wins because it is the most specific statement you can make. The order of
|
|
639
|
-
the two OpenTelemetry variables is required by the specification, not chosen: _"If `service.name` is
|
|
640
|
-
also provided in `OTEL_RESOURCE_ATTRIBUTES`, then `OTEL_SERVICE_NAME` takes precedence."_
|
|
641
|
-
|
|
642
|
-
Reading the same variables the SDK reads is what makes **logs and traces agree** without the logger
|
|
643
|
-
depending on the SDK. Configure the environment once and both signals describe the same service.
|
|
488
|
+
Values resolve once at startup, in this order: explicit `service` options, then `OTEL_SERVICE_NAME` (name only), then `OTEL_RESOURCE_ATTRIBUTES` (`service.namespace=payments,service.version=2.14.3,…`), then `NODE_ENV` (environment only). The order of the two OpenTelemetry variables is the specification's. Reading the variables the SDK reads makes logs and traces agree without depending on the SDK.
|
|
644
489
|
|
|
645
490
|
> [!IMPORTANT]
|
|
646
|
-
> **`service.instance.id` is never generated.**
|
|
647
|
-
> (`service.namespace`, `service.name`, `service.instance.id`) to be globally unique and recommends
|
|
648
|
-
> a random UUID — but a UUID minted by the logger would be the _logger's_, not the OpenTelemetry
|
|
649
|
-
> Resource's, so logs and traces would claim different instances of the same process. It would also
|
|
650
|
-
> change on every restart while looking authoritative. Supply it from the platform (Kubernetes pod
|
|
651
|
-
> UID, ECS task ARN, VM instance id) or through `OTEL_RESOURCE_ATTRIBUTES`. Omitted is honest;
|
|
652
|
-
> plausible-but-wrong is not.
|
|
653
|
-
>
|
|
654
|
-
> There is **no `OTEL_SERVICE_VERSION`** variable in the specification. Version comes from
|
|
655
|
-
> configuration or from `OTEL_RESOURCE_ATTRIBUTES`.
|
|
491
|
+
> **`service.instance.id` is never generated.** A UUID minted by the logger would not be the OpenTelemetry Resource's, so logs and traces would claim different instances of one process. Supply it from the platform (Kubernetes pod UID, ECS task ARN) or through `OTEL_RESOURCE_ATTRIBUTES`. There is no `OTEL_SERVICE_VERSION` variable in the specification.
|
|
656
492
|
|
|
657
|
-
|
|
493
|
+
### Event names
|
|
658
494
|
|
|
659
|
-
|
|
495
|
+
Structured entries carry a machine-readable name derived from `logKey`, lowercase and dot-namespaced (`PAYMENT_FAILED` → `payment.failed`, `USER_AUTHENTICATION_FAILED` → `user.authentication.failed`). `logKey` itself is never renamed. Calls through the NestJS variadic bridge (`logger.log`, `logger.warn`) carry no log key and get no event name. Keep names low cardinality: identifiers belong in their own fields.
|
|
660
496
|
|
|
661
|
-
|
|
662
|
-
rules — lowercase, dot-namespaced:
|
|
497
|
+
The value is meant for the **`EventName`** field of an OpenTelemetry LogRecord; the same-named `event.name` attribute is deprecated. A JSON line cannot express that distinction, so the carrier key is configurable through `eventNameField` and your collector decides where it lands. `eventNameField: false` emits nothing.
|
|
663
498
|
|
|
664
|
-
|
|
665
|
-
| ---------------------------- | ---------------------------- |
|
|
666
|
-
| `PAYMENT_FAILED` | `payment.failed` |
|
|
667
|
-
| `USER_AUTHENTICATION_FAILED` | `user.authentication.failed` |
|
|
668
|
-
|
|
669
|
-
`logKey` is **never renamed or removed** — this is additive. Calls through the NestJS variadic
|
|
670
|
-
bridge (`logger.log`, `logger.warn`, …) carry no log key and correctly get no event name: an
|
|
671
|
-
ordinary diagnostic line is not an Event.
|
|
672
|
-
|
|
673
|
-
Keep event names **low cardinality**. `payment.failed` is an event; `payment.failed.918231781` is an
|
|
674
|
-
identifier wearing an event's clothes and will multiply your series count. Identifiers belong in
|
|
675
|
-
their own fields.
|
|
676
|
-
|
|
677
|
-
> [!NOTE]
|
|
678
|
-
> The value is meant to be mapped onto the **`EventName`** field of the OpenTelemetry LogRecord,
|
|
679
|
-
> which is Stable in the Logs Data Model. The same-named `event.name` **attribute** is _Deprecated_
|
|
680
|
-
> precisely because the value belongs in that top-level field instead. A JSON log line has no way to
|
|
681
|
-
> express that distinction — every key is just a key — so the carrier key is configurable via
|
|
682
|
-
> `eventNameField`, and your collector decides where it lands. What it must not do is carry it into
|
|
683
|
-
> an OTLP _attributes_ map under the deprecated name.
|
|
684
|
-
|
|
685
|
-
Set `eventNameField: false` to emit nothing.
|
|
686
|
-
|
|
687
|
-
### 6d. Error fields
|
|
499
|
+
### Error fields
|
|
688
500
|
|
|
689
501
|
`errorFormat` controls the shape:
|
|
690
502
|
|
|
691
503
|
```json
|
|
692
|
-
// errorFormat: 'pino' (default
|
|
504
|
+
// errorFormat: 'pino' (default)
|
|
693
505
|
{ "err": { "type": "PaymentDeclined", "message": "card declined", "stack": "…",
|
|
694
506
|
"cause": { "name": "Error", "message": "gateway timeout" } } }
|
|
695
507
|
|
|
696
|
-
// errorFormat: 'both' (
|
|
508
|
+
// errorFormat: 'both' (adds the semconv fields beside err)
|
|
697
509
|
{ "err": { "type": "PaymentDeclined", … },
|
|
698
510
|
"exception.type": "PaymentDeclined",
|
|
699
511
|
"exception.message": "card declined",
|
|
700
512
|
"exception.stacktrace": "…",
|
|
701
513
|
"error.type": "PaymentDeclined" }
|
|
702
514
|
|
|
703
|
-
// errorFormat: 'semconv' (
|
|
515
|
+
// errorFormat: 'semconv' (err is removed)
|
|
704
516
|
{ "exception.type": "PaymentDeclined", "exception.message": "card declined",
|
|
705
517
|
"exception.stacktrace": "…", "error.type": "PaymentDeclined" }
|
|
706
518
|
```
|
|
707
519
|
|
|
708
|
-
All four attributes are **Stable**. `error.type` carries the
|
|
709
|
-
by construction — never a message, never an identifier — because the spec requires it to be
|
|
710
|
-
aggregatable.
|
|
711
|
-
|
|
712
|
-
**`Error.cause` chains are preserved**, depth- and width-bounded, circular-safe, and redacted like
|
|
713
|
-
any other field. `AggregateError` members reach the entry as `err.errors`. There is no
|
|
714
|
-
OpenTelemetry attribute for a cause chain, so these stay namespaced under `err` rather than
|
|
715
|
-
inventing an `exception.cause` the spec does not define.
|
|
716
|
-
|
|
717
|
-
**An error's own enumerable properties travel with it at every depth** — `code` on a Node system
|
|
718
|
-
error, `statusCode` from an HTTP layer, whatever domain fields you attached — including on a nested
|
|
719
|
-
`cause` and on each `AggregateError` member:
|
|
720
|
-
|
|
721
|
-
```json
|
|
722
|
-
{
|
|
723
|
-
"err": {
|
|
724
|
-
"type": "Error",
|
|
725
|
-
"message": "bootstrap failed",
|
|
726
|
-
"code": "EBOOT",
|
|
727
|
-
"cause": {
|
|
728
|
-
"name": "Error",
|
|
729
|
-
"message": "config invalid",
|
|
730
|
-
"code": "BYMAX_CONFIG_VALIDATION",
|
|
731
|
-
"issues": [{ "variable": "DATABASE_URL", "code": "invalid_url" }]
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
```
|
|
736
|
-
|
|
737
|
-
This matters because `code` is usually the field you alert on. Until 1.2.7 those properties survived
|
|
738
|
-
only on the error handed to the log call and were dropped the moment the same error was wrapped as
|
|
739
|
-
someone else's `cause` — which is what any handler that wraps what it caught does before
|
|
740
|
-
logging it. They never shadow a
|
|
741
|
-
field the serializer derives, and they pass through the same name-based redaction and size bound as
|
|
742
|
-
any other serializer output.
|
|
520
|
+
All four attributes are **Stable**. `error.type` carries the class name, so it stays low cardinality. `Error.cause` chains are preserved (depth- and width-bounded, circular-safe, redacted like any field) and `AggregateError` members reach the entry as `err.errors`. There is no OpenTelemetry attribute for a cause chain, so these stay under `err`.
|
|
743
521
|
|
|
744
|
-
An error's own enumerable properties (`code`, `statusCode`, domain fields) are
|
|
745
|
-
Pino's standard serializer did, with one exception: the arguments of a failed driver call are not
|
|
746
|
-
written. The fields `args` and `parameters` are omitted, a `command` object is reduced to its
|
|
747
|
-
`name`, and an error with a SQLSTATE `code` (five characters from `0-9A-Z`, the first not `E`) loses `detail`, `where` and `internalQuery`, which quote the row and
|
|
748
|
-
the statement (its other fields stay), because the redaction
|
|
749
|
-
matches key names and cannot see a value inside a string.
|
|
522
|
+
An error's own enumerable properties (`code`, `statusCode`, domain fields) travel with it at every depth, including on a nested `cause` and each `AggregateError` member, and pass through the same name-based redaction and size bound as any serializer output. They never shadow a field the serializer derives. Exceptions: the arguments of a failed driver call are not written (`args` and `parameters` are omitted, a `command` object is reduced to its `name`, and an error with a SQLSTATE `code` loses `detail`, `where` and `internalQuery`, which quote the row and the statement), because redaction matches key names and cannot see a value inside a string.
|
|
750
523
|
|
|
751
|
-
|
|
524
|
+
**`errorOwnFields`.** Node's own errors carry values: a failed child process has `stdout` and `stderr`, an `AssertionError` its `actual` and `expected`, a file system error its `path`. A list of names to drop cannot name them all, so the choice is yours:
|
|
752
525
|
|
|
753
|
-
- `
|
|
754
|
-
- `
|
|
526
|
+
- `'all'` (the default in 1.x) writes every own field as above.
|
|
527
|
+
- `'safe'` (recommended) writes only `code`, `errno`, `syscall`, `signal`, `status`, `statusCode`, `address`, `port`, `hostname` and the PostgreSQL `constraint`, `table`, `column`, `schema` and `routine`, plus the names in `errorOwnFieldNames` (matched exactly), at every depth. `path` is not on the list; add it if a path is not data to you. Under `'safe'` an `Error` is written from its own fields and its `toJSON` is not called (an HTTP client's `toJSON` may carry the request); any other `toJSON` is called once, as `JSON.stringify` would, and its result is censored. A serializer then receives a plain error-like object instead of an `Error` instance.
|
|
755
528
|
|
|
756
529
|
```typescript
|
|
757
530
|
BymaxLoggerModule.forRoot({
|
|
@@ -761,125 +534,39 @@ BymaxLoggerModule.forRoot({
|
|
|
761
534
|
})
|
|
762
535
|
```
|
|
763
536
|
|
|
764
|
-
**Binary values.** A Buffer,
|
|
765
|
-
|
|
766
|
-
Neither setting covers the `message`: Node writes the command line of a failed child process, arguments included, and what it printed to stderr into it, and the redaction matches key names, not text.
|
|
537
|
+
**Binary values.** A Buffer, typed array or `DataView` anywhere in the record is written as its size (`"[Binary 42 bytes]"`), in both modes and under both redaction strategies. If you turn every redaction off (`shouldDisableDefaultRedact: true`, no `redactPaths`, and `errorOwnFields` not `'safe'`), nothing walks the record and a Buffer is written the way Pino writes it. To log bytes on purpose, convert first, for example `buffer.toString('base64')`.
|
|
767
538
|
|
|
768
|
-
|
|
539
|
+
Neither setting covers the `message`: Node writes the command line of a failed child process, arguments included, into it, and redaction matches key names, not text.
|
|
769
540
|
|
|
770
|
-
An `Error` that cannot be read at all does not cost the record its `logKey`, `userId` or metadata:
|
|
541
|
+
When an error's properties cannot be read (a Proxy whose `ownKeys` throws, a throwing getter), none are copied and the error node carries `_errorFieldsIncomplete: true`. An `Error` that cannot be read at all does not cost the record its `logKey`, `userId` or metadata: it is replaced by its sanitized form (`name` and `message`, with the same marker), or `{ type: 'SanitizeFailed' }` when even those are unreadable. Filter on those two to find such entries.
|
|
771
542
|
|
|
772
|
-
An `Error` nested in the metadata
|
|
543
|
+
An `Error` nested in the metadata is written as its own enumerable fields, censored by name, with `type`, `message`, `stack`, `cause` and `errors` added, bounded like the root `err` and marked `_truncated` when cut. A string `cause` is logged like a `message`: do not put secrets in either. Whatever sits under a record-root key that has a serializer (`err`, or a key of `serializers`) reaches that serializer censored by name with its `Error`s still instances, and what a serializer returns is written as returned, so an `Error` in that output stays `{}`.
|
|
773
544
|
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
```typescript
|
|
777
|
-
// request-id.middleware.ts
|
|
778
|
-
import { Injectable, NestMiddleware } from '@nestjs/common'
|
|
779
|
-
import {
|
|
780
|
-
LogContextService,
|
|
781
|
-
type LoggableRequest,
|
|
782
|
-
type LoggableResponse
|
|
783
|
-
} from '@bymax-one/nest-logger'
|
|
784
|
-
import { randomUUID } from 'node:crypto'
|
|
785
|
-
|
|
786
|
-
@Injectable()
|
|
787
|
-
export class RequestIdMiddleware implements NestMiddleware {
|
|
788
|
-
constructor(private readonly logContext: LogContextService) {}
|
|
789
|
-
|
|
790
|
-
use(req: LoggableRequest, res: LoggableResponse, next: () => void) {
|
|
791
|
-
// A header can arrive repeated, so its type is `string | string[]`.
|
|
792
|
-
const raw = req.headers['x-request-id']
|
|
793
|
-
const requestId = (Array.isArray(raw) ? raw[0] : raw) ?? `r_${randomUUID()}`
|
|
794
|
-
this.logContext.run({ requestId }, next)
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
```
|
|
545
|
+
## 🧵 Context Propagation
|
|
798
546
|
|
|
799
|
-
Any
|
|
547
|
+
`LogContextService` holds an `AsyncLocalStorage` scope. Any entry emitted inside `logContext.run({ requestId }, callback)`, at any nesting depth, carries the scope's fields with no prop drilling. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` open the scope for each request; the full method list is in the API Reference.
|
|
800
548
|
|
|
801
|
-
|
|
549
|
+
### Inbound `x-request-id` and tenant header
|
|
802
550
|
|
|
803
|
-
The bundled `RequestIdMiddleware` does not trust the headers it reads. A request id or tenant id is accepted only when it is a string of **at most 256 characters**
|
|
551
|
+
The bundled `RequestIdMiddleware` does not trust the headers it reads. A request id or tenant id is accepted only when it is a string of **at most 256 characters** from `A-Z a-z 0-9 . _ : / + = -`. Anything else is replaced, never truncated or cleaned.
|
|
804
552
|
|
|
805
553
|
| Header | Rejected value becomes |
|
|
806
554
|
| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
807
555
|
| `x-request-id` | a fresh UUID, or none when `http.shouldGenerateRequestId` is `false` (an enclosing scope's `requestId`, if any, is then inherited) |
|
|
808
556
|
| the tenant header (`http.tenantIdHeader`) | no `tenantId` from the header; a tenant is never minted |
|
|
809
557
|
|
|
810
|
-
**A `tenantId` read from the header is what the client asserted.** Any client can send any tenant in `x-tenant-id
|
|
811
|
-
|
|
812
|
-
- `http: { tenantIdHeader: false }` reads no header, so the middleware takes no `tenantId` from the request.
|
|
813
|
-
- `http: { tenantIdResolver: (req) => ... }` takes the tenant from what the host trusts, for example a value an earlier middleware put on the request after verifying a token. When a resolver is given it is the only source: the header is not read even if the resolver answers nothing, so a client cannot fall back to it. The answer passes the same 256-character rule, and a resolver that throws gives no `tenantId`. The middleware runs before guards, so a tenant known only after authentication is set later with `LogContextService.set('tenantId', ...)`.
|
|
814
|
-
|
|
815
|
-
An accepted id is echoed back on the response `x-request-id` header and written to every entry the request produces, which is why the set is narrow. The example above reads the header raw to stay short; use `RequestIdMiddleware` through `applyAccessLog(app)` or `applyRequestIdMiddleware(consumer)` unless you apply the same rule yourself.
|
|
816
|
-
|
|
817
|
-
---
|
|
818
|
-
|
|
819
|
-
## ⚙️ Configuration
|
|
820
|
-
|
|
821
|
-
Full options reference for `BymaxLoggerModule.forRoot(options)`:
|
|
822
|
-
|
|
823
|
-
### Top-level options
|
|
824
|
-
|
|
825
|
-
| Option | Type | Default | Description |
|
|
826
|
-
| ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
827
|
-
| `service.name` | `string` | **Required** | Service name emitted in every log entry |
|
|
828
|
-
| `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
|
|
829
|
-
| `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
|
|
830
|
-
| `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#6b-resource-identity) |
|
|
831
|
-
| `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
|
|
832
|
-
| `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
|
|
833
|
-
| `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
|
|
834
|
-
| `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
|
|
835
|
-
| `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
|
|
836
|
-
| `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
|
|
837
|
-
| `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` restores the pre-1.2 `fast-redact` expansion (four-level ceiling, ~100× slower) |
|
|
838
|
-
| `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
|
|
839
|
-
| `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
|
|
840
|
-
| `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
|
|
841
|
-
| `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see _Own fields of an error_ in section 6). A binary value is written as its size in both. Recommended: `'safe'` |
|
|
842
|
-
| `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
|
|
843
|
-
| `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
|
|
844
|
-
| `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
|
|
845
|
-
| `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
|
|
846
|
-
| `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
|
|
847
|
-
| `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
|
|
848
|
-
|
|
849
|
-
### `http` options
|
|
850
|
-
|
|
851
|
-
| Option | Type | Default | Description |
|
|
852
|
-
| ------------------------------ | ------------------------------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
853
|
-
| `http.isEnabled` | `boolean` | `false` | Register `HttpLoggingInterceptor` (and, on `forRoot`, `HttpExceptionFilter`) globally |
|
|
854
|
-
| `http.shouldCaptureExceptions` | `boolean` | `true` | Capture unhandled HTTP exceptions and emit `HTTP_EXCEPTION_UNHANDLED`. `forRoot` only: see the note under [Async configuration](#3-async-configuration-with-configservice) |
|
|
855
|
-
| `http.shouldGenerateRequestId` | `boolean` | `true` | Generate a `requestId` when the inbound request header is absent |
|
|
856
|
-
| `http.excludePaths` | `RegExp[]` | `[/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/]` | Paths that bypass HTTP logging. Use anchored, linear-time regexes (ReDoS-safe) |
|
|
857
|
-
| `http.tenantIdHeader` | `string \| false` | `'x-tenant-id'` | Request header carrying the tenant identifier, or `false` to read none. A value from the header is what the client asserted: see [Inbound `x-request-id` and tenant header](#inbound-x-request-id-and-tenant-header) |
|
|
858
|
-
| `http.tenantIdResolver` | `(req) => string \| undefined` | none | Resolves the tenant id on the server side. When given it is the only source and the header is not read |
|
|
558
|
+
**A `tenantId` read from the header is what the client asserted.** Any client can send any tenant in `x-tenant-id`; the 256-character rule keeps the value safe to write, not true. Do not use a header-derived `tenantId` to decide whose data an entry is about unless something in front of the application sets or overwrites the header. A host that authenticates its tenants has two options:
|
|
859
559
|
|
|
860
|
-
|
|
560
|
+
- `http: { tenantIdHeader: false }` reads no header, so no `tenantId` is taken from the request.
|
|
561
|
+
- `http: { tenantIdResolver: (req) => ... }` takes the tenant from what the host trusts, for example a value an earlier middleware set after verifying a token. When given, it is the only source (the header is not read even if the resolver answers nothing), its answer passes the same rule, and a resolver that throws gives no `tenantId`. The middleware runs before guards, so a tenant known only after authentication is set later with `LogContextService.set('tenantId', ...)`.
|
|
861
562
|
|
|
862
|
-
|
|
863
|
-
| ----------------------------------- | ----------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- |
|
|
864
|
-
| `otel.shouldAutoInjectTraceContext` | `boolean` | `true` | Detect `@opentelemetry/api` and inject `traceId`/`spanId` via Pino mixin |
|
|
865
|
-
| `otel.fieldFormat` | `'camelCase' \| 'snake_case'` | `'camelCase'` | Field names in log entries: `traceId`/`spanId` vs `trace_id`/`span_id` |
|
|
866
|
-
| `otel.traceIdField` | `string` | `'traceId'` | Field name for the trace ID; `fieldFormat: 'snake_case'` derives `trace_id` unless this is set |
|
|
867
|
-
| `otel.spanIdField` | `string` | `'spanId'` | Field name for the span ID; `fieldFormat: 'snake_case'` derives `span_id` unless this is set |
|
|
868
|
-
| `otel.traceFlagsField` | `string` | `'traceFlags'` | Field name for the trace flags; `fieldFormat: 'snake_case'` derives `trace_flags` unless this is set |
|
|
563
|
+
An accepted id is echoed on the response `x-request-id` header and written to every entry of the request, which is why the accepted set is narrow.
|
|
869
564
|
|
|
870
565
|
---
|
|
871
566
|
|
|
872
567
|
## 🔑 Log Key Convention
|
|
873
568
|
|
|
874
|
-
All structured log calls
|
|
875
|
-
|
|
876
|
-
```
|
|
877
|
-
USER_LOGIN_SUCCESS AUTH_REGISTER_FAILED
|
|
878
|
-
PAYMENT_REFUND_PROCESSED WEBHOOK_STRIPE_RECEIVED
|
|
879
|
-
HTTP_REQUEST_CLIENT_ERROR METHOD_SLOW_EXECUTION
|
|
880
|
-
```
|
|
881
|
-
|
|
882
|
-
The regex is exported from the `/shared` entry for CI validation:
|
|
569
|
+
All structured log calls use the `MODULE_ACTION_RESULT` format (`USER_LOGIN_SUCCESS`, `PAYMENT_REFUND_PROCESSED`, `WEBHOOK_STRIPE_RECEIVED`). The regex is exported from `/shared` for CI validation:
|
|
883
570
|
|
|
884
571
|
```typescript
|
|
885
572
|
import { LOG_KEYS_CONVENTION_REGEX } from '@bymax-one/nest-logger/shared'
|
|
@@ -893,23 +580,17 @@ function assertValidLogKey(key: string) {
|
|
|
893
580
|
|
|
894
581
|
### Reserved keys
|
|
895
582
|
|
|
896
|
-
|
|
583
|
+
These are used by the library; do not reuse them in application code. All are exported as `RESERVED_LOG_KEYS` from `@bymax-one/nest-logger/shared`.
|
|
897
584
|
|
|
898
585
|
`LOGGER_BOOTSTRAP_OK` · `LOGGER_BOOTSTRAP_WARNING` · `LOGGER_SHUTDOWN_OK` · `HTTP_REQUEST_START` · `HTTP_REQUEST_SUCCESS` · `HTTP_REQUEST_REDIRECT` · `HTTP_REQUEST_CLIENT_ERROR` · `HTTP_REQUEST_SERVER_ERROR` · `HTTP_REQUEST_ABORTED` · `HTTP_REQUEST_COMPLETED` · `HTTP_EXCEPTION_HANDLED` · `HTTP_EXCEPTION_UNHANDLED` · `HTTP_UNEXPECTED_ERROR` · `HTTP_UNEXPECTED_ERROR_DROPPED` · `METHOD_EXECUTION` · `METHOD_SLOW_EXECUTION` · `LOGGER_DESTINATION_INIT_FAILED` · `LOGGER_DESTINATION_WRITE_FAILED` · `LOGGER_ENTRY_TRUNCATED` · `LOGGER_REDACTION_FAILED` · `LOGGER_OTEL_API_BROKEN`
|
|
899
586
|
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
`HTTP_REQUEST_COMPLETED` is reserved but deliberately never emitted — the four status-specific
|
|
903
|
-
terminal keys already carry the same `duration`, so a generic "completed" entry would double the
|
|
904
|
-
access-log volume to say nothing new. The reserved-but-unwritten set is exported as
|
|
905
|
-
`RESERVED_LOG_KEYS_NOT_EMITTED`, and a test asserts that every OTHER declared key has a writer in
|
|
906
|
-
the source, so a key can no longer be documented as a signal and then silently never emitted.
|
|
587
|
+
`HTTP_REQUEST_COMPLETED` is reserved but never emitted: the four status-specific terminal keys already carry the same `duration`. The reserved-but-unwritten set is exported as `RESERVED_LOG_KEYS_NOT_EMITTED`, and a test asserts that every other declared key has a writer in the source.
|
|
907
588
|
|
|
908
589
|
---
|
|
909
590
|
|
|
910
591
|
## 🧩 Custom Destinations
|
|
911
592
|
|
|
912
|
-
Implement `ILogDestination` to ship logs to any sink
|
|
593
|
+
Implement `ILogDestination` to ship logs to any sink. `write` receives the entry already serialized as a newline-terminated JSON string, so a sink that forwards lines should buffer them as they arrive and parse only where a field is needed. The [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has further examples (database, rolling file, stream).
|
|
913
594
|
|
|
914
595
|
```typescript
|
|
915
596
|
import type { ILogDestination } from '@bymax-one/nest-logger'
|
|
@@ -1000,22 +681,13 @@ BymaxLoggerModule.forRootAsync({
|
|
|
1000
681
|
|
|
1001
682
|
### Destinations replace stdout
|
|
1002
683
|
|
|
1003
|
-
A non-empty `destinations` **replaces** `DefaultStdoutDestination
|
|
684
|
+
A non-empty `destinations` **replaces** `DefaultStdoutDestination`, so a file-only or socket-only deployment can turn structured stdout off. To keep stdout beside a custom sink, list it explicitly: `destinations: [new DefaultStdoutDestination(), new LokiDestination({ ... })]`.
|
|
1004
685
|
|
|
1005
|
-
|
|
1006
|
-
destinations: [new DefaultStdoutDestination(), new LokiDestination({ ... })]
|
|
1007
|
-
```
|
|
1008
|
-
|
|
1009
|
-
The consequence worth knowing: a sink you supply may be the **only** one the application has, so its failure is the application's silence. Two guarantees cover that, and neither requires anything from you:
|
|
1010
|
-
|
|
1011
|
-
- **A destination that fails `onInit` is reported as `LOGGER_DESTINATION_INIT_FAILED` on `stderr`** — not through the logger, whose sinks are the ones that just failed — and receives no entries.
|
|
1012
|
-
- **If _every_ destination fails to initialize, entries fall back to raw NDJSON on `stdout`.** Degraded and ugly, but visible; nothing is lost, including the bootstrap entries.
|
|
1013
|
-
|
|
1014
|
-
So the common accident — adding `new PrettyDevDestination()` without installing the optional `pino-pretty` — costs you colours and a line on stderr telling you why, never your logs.
|
|
686
|
+
A sink you supply may be the only one the application has, so two guarantees cover its failure: a destination that fails `onInit` is reported as `LOGGER_DESTINATION_INIT_FAILED` on `stderr` (not through the logger, whose sinks just failed) and receives no entries, and if **every** destination fails to initialize, entries fall back to raw NDJSON on `stdout`. Adding `new PrettyDevDestination()` without the optional `pino-pretty` therefore costs colours and a line on stderr, never your logs.
|
|
1015
687
|
|
|
1016
688
|
### Choosing how the dev terminal renders
|
|
1017
689
|
|
|
1018
|
-
`PrettyDevDestination` takes a `view
|
|
690
|
+
`PrettyDevDestination` takes a `view`; every field defaults to the previous rendering, so `new PrettyDevDestination()` is unchanged. The default view is verbose (one entry can be seven lines).
|
|
1019
691
|
|
|
1020
692
|
```typescript
|
|
1021
693
|
// One line per entry, with the fields your project repeats on every line hidden.
|
|
@@ -1024,7 +696,6 @@ new PrettyDevDestination({
|
|
|
1024
696
|
})
|
|
1025
697
|
|
|
1026
698
|
// Message only, with the context pulled back into the line.
|
|
1027
|
-
// See the messageFormat warning below before interpolating any other field.
|
|
1028
699
|
new PrettyDevDestination({
|
|
1029
700
|
view: { hideObject: true, messageFormat: '[{context}] {msg}' }
|
|
1030
701
|
})
|
|
@@ -1039,94 +710,12 @@ new PrettyDevDestination({
|
|
|
1039
710
|
| `translateTime` | `'SYS:HH:MM:ss.l'` | Or `false` for the raw timestamp |
|
|
1040
711
|
| `colorize` | `true` | ANSI colour |
|
|
1041
712
|
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
> ```
|
|
1047
|
-
> ignore: '…,event.name' → INFO: msg {"logKey":"X","event.name":"x"} ← still there
|
|
1048
|
-
> ignore: '…,event\\.name' → INFO: msg {"logKey":"X"} ← hidden
|
|
1049
|
-
> ```
|
|
1050
|
-
>
|
|
1051
|
-
> In a TypeScript string literal that is `'event\\.name'` — one real backslash reaching `pino-pretty`. `service` and `deployment` need no escape; they really are nested objects. Reported by a consumer who copied the example above when it still had the unescaped form.
|
|
1052
|
-
|
|
1053
|
-
The shape is exported as `PrettyViewOptions` when you want to build the view separately — it is this library's own interface, not a re-export of `pino-pretty`'s `PrettyOptions`, so type-checking without the optional peer installed still resolves.
|
|
1054
|
-
|
|
1055
|
-
> **`messageFormat` interpolates every placeholder except `{msg}` raw — that can forge a terminal entry.** This library normalizes line separators and control characters in `msg` and in the stack, never in metadata, because escaping data would mean rewriting what you asked to be logged. `pino-pretty` substitutes whatever the field holds, so a newline in an interpolated field splits one entry into two and the second reads like a genuine record. Measured, with a newline in `context`:
|
|
1056
|
-
>
|
|
1057
|
-
> ```
|
|
1058
|
-
> lines produced by ONE entry: 2
|
|
1059
|
-
> 1: "[10:35:14.484] INFO: [Auth"
|
|
1060
|
-
> 2: "[10:00:00.000] INFO: FORGED admin promoted] real entry …"
|
|
1061
|
-
> ```
|
|
1062
|
-
>
|
|
1063
|
-
> Interpolate only fields your own code sets. Never one carrying user input — `{tenantId}`, `{userId}`, a header, a query value. If you need one of those visible, leave it in the record instead. That closes **this** path and no more: a metadata value is not safe terminal text either, since `JSON.stringify` escapes only C0 and emits DEL, the C1 range (U+0085 NEL included), U+2028 and U+2029 verbatim — see _One entry, one line_ below, where the same boundary is stated. Only `msg` and the stack carry that guarantee.
|
|
1064
|
-
|
|
1065
|
-
> **`destination` is not exposed, by design.** The library owns where entries go — a redirected stream would route around the fan-out and the last-resort rescue above. It is absent from the type and applied after your options are merged, so it cannot be overridden from untyped JavaScript either.
|
|
1066
|
-
|
|
1067
|
-
**The first entries of a boot are held, not lost.** The transform cannot exist until `onInit` — loading the optional peer is async — so everything NestJS emits while instantiating providers arrives before it. Those entries are buffered and then rendered through the transform in arrival order. If the peer is missing, the bound is reached, or the app shuts down before init, they are written as raw NDJSON instead: degraded, never dropped.
|
|
1068
|
-
|
|
1069
|
-
### Postgres destination (Prisma)
|
|
1070
|
-
|
|
1071
|
-
```typescript
|
|
1072
|
-
import { PINO_LEVEL_NUMBERS } from '@bymax-one/nest-logger'
|
|
1073
|
-
import type { ILogDestination } from '@bymax-one/nest-logger'
|
|
1074
|
-
import type { LogEntry } from '@bymax-one/nest-logger/shared'
|
|
1075
|
-
import type { PrismaClient } from '@prisma/client'
|
|
1076
|
-
|
|
1077
|
-
export class PrismaLogDestination implements ILogDestination {
|
|
1078
|
-
readonly name = 'prisma-postgres'
|
|
1079
|
-
readonly minLevel = 'warn' as const // only persist warnings and above
|
|
1080
|
-
|
|
1081
|
-
constructor(private readonly prisma: PrismaClient) {}
|
|
1082
|
-
|
|
1083
|
-
write(payload: string): void {
|
|
1084
|
-
// This destination stores individual columns, so it is one of the few that
|
|
1085
|
-
// has to parse. A sink that forwards the line verbatim should not.
|
|
1086
|
-
const entry = JSON.parse(payload) as LogEntry
|
|
1087
|
-
void this.prisma.applicationLog.create({
|
|
1088
|
-
data: {
|
|
1089
|
-
// `entry.level` is the Pino LABEL ('info'). Map it when the column is numeric.
|
|
1090
|
-
level: PINO_LEVEL_NUMBERS[entry.level],
|
|
1091
|
-
logKey: entry.logKey,
|
|
1092
|
-
message: entry.msg,
|
|
1093
|
-
payload: entry,
|
|
1094
|
-
createdAt: new Date(entry.time)
|
|
1095
|
-
}
|
|
1096
|
-
})
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
```
|
|
1100
|
-
|
|
1101
|
-
### Rolling file destination (`pino-roll`)
|
|
1102
|
-
|
|
1103
|
-
```typescript
|
|
1104
|
-
import { createStream } from 'pino-roll'
|
|
1105
|
-
import type { ILogDestination } from '@bymax-one/nest-logger'
|
|
1106
|
-
import type { LogEntry } from '@bymax-one/nest-logger/shared'
|
|
1107
|
-
|
|
1108
|
-
export class RollingFileDestination implements ILogDestination {
|
|
1109
|
-
readonly name = 'rolling-file'
|
|
1110
|
-
private stream?: Awaited<ReturnType<typeof createStream>>
|
|
1111
|
-
|
|
1112
|
-
async onInit(): Promise<void> {
|
|
1113
|
-
this.stream = await createStream('logs/app.log', {
|
|
1114
|
-
frequency: 'daily',
|
|
1115
|
-
mkdir: true,
|
|
1116
|
-
size: '50m'
|
|
1117
|
-
})
|
|
1118
|
-
}
|
|
713
|
+
- **`hideObject` hides fields from this destination only.** Other destinations still receive the complete entry. When pretty is your only destination nothing else holds the entry, because `destinations` replaces stdout; use `messageFormat` to pull a field back.
|
|
714
|
+
- **A dot in `ignore` means a nested path.** `event.name` is a literal top-level key, so it must be escaped (`'event\\.name'` in a TypeScript string) or nothing is hidden. `service` and `deployment` are real nested objects and need no escape.
|
|
715
|
+
- **`messageFormat` interpolates every placeholder except `{msg}` raw.** The library normalizes line separators and control characters in `msg` and the stack, never in metadata, so a newline in an interpolated field splits one entry into two and the second can read like a genuine record. Interpolate only fields your own code sets, never one carrying user input (`{tenantId}`, `{userId}`, a header).
|
|
716
|
+
- **`destination` is not exposed, by design.** The library owns where entries go; a redirected stream would route around the fan-out and the last-resort rescue.
|
|
1119
717
|
|
|
1120
|
-
|
|
1121
|
-
await new Promise<void>((resolve) => this.stream?.end(resolve))
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
write(payload: string): void {
|
|
1125
|
-
// Already newline-terminated JSON — re-serializing would double-encode it.
|
|
1126
|
-
this.stream?.write(payload)
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
```
|
|
718
|
+
The view type is exported as `PrettyViewOptions`. It is this library's own interface, so type-checking works without the optional peer installed. Entries emitted before `onInit` (while Nest instantiates providers) are buffered and then rendered in order; if the peer is missing, the bound is reached or the app shuts down first, they are written as raw NDJSON, never dropped.
|
|
1130
719
|
|
|
1131
720
|
---
|
|
1132
721
|
|
|
@@ -1136,15 +725,12 @@ export class RollingFileDestination implements ILogDestination {
|
|
|
1136
725
|
HTTP Request
|
|
1137
726
|
│
|
|
1138
727
|
▼
|
|
1139
|
-
RequestIdMiddleware ← runs
|
|
1140
|
-
│ guards AND interceptors) and opens the
|
|
1141
|
-
│ AsyncLocalStorage scope
|
|
728
|
+
RequestIdMiddleware ← runs first; opens the AsyncLocalStorage scope
|
|
1142
729
|
│ { requestId, tenantId }
|
|
1143
730
|
▼
|
|
1144
|
-
HttpAccessLogMiddleware ← emits HTTP_REQUEST_START
|
|
1145
|
-
│
|
|
1146
|
-
│
|
|
1147
|
-
│ rejection is logged too.
|
|
731
|
+
HttpAccessLogMiddleware ← emits HTTP_REQUEST_START in that scope and arms the
|
|
732
|
+
│ terminal entry on the response's 'close' event,
|
|
733
|
+
│ BEFORE guards, so a 401/403/429 is logged too
|
|
1148
734
|
▼
|
|
1149
735
|
Guards (consumer's auth) ← may reject here; no interceptor ever runs
|
|
1150
736
|
│
|
|
@@ -1159,7 +745,7 @@ Application Service
|
|
|
1159
745
|
▼
|
|
1160
746
|
Pino logger
|
|
1161
747
|
│
|
|
1162
|
-
createTraceContextMixin() ←
|
|
748
|
+
createTraceContextMixin() ← per entry
|
|
1163
749
|
├── ALS store → { requestId, tenantId, userId }
|
|
1164
750
|
└── OTel span → { traceId, spanId, traceFlags }
|
|
1165
751
|
│
|
|
@@ -1169,31 +755,21 @@ Application Service
|
|
|
1169
755
|
▼
|
|
1170
756
|
┌─────────────────────────────┐
|
|
1171
757
|
│ DefaultStdoutDestination │ ← default; replaced by `destinations`
|
|
1172
|
-
│
|
|
1173
|
-
│ PrismaLogDestination │ ← optional
|
|
1174
|
-
│ RollingFileDestination │ ← optional
|
|
758
|
+
│ your ILogDestination(s) │
|
|
1175
759
|
└─────────────────────────────┘
|
|
1176
760
|
```
|
|
1177
761
|
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
| Principle | Description |
|
|
1181
|
-
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1182
|
-
| **🪶 Singleton Scope** | `AsyncLocalStorage` delivers per-request context at zero latency overhead — NestJS's own docs put the cost of `Scope.REQUEST` at up to ~5% latency, unacceptable on a logger that runs for every request |
|
|
1183
|
-
| **🧬 One Composed Mixin** | ALS context and OTel trace context merge into a single Pino mixin with a deterministic order: ALS first, then OTel — an active span is the authoritative trace identity, so it wins on conflicts |
|
|
1184
|
-
| **⚡ Single-pass Redaction** | One recursive walk censors any value whose key name is in the sensitive set, to a 100-level ceiling past which nested objects are dropped rather than emitted — O(nodes), the same order the serializer already pays. Replaced 140 `fast-redact` wildcard paths that cost ~107 µs per entry |
|
|
1185
|
-
| **🔌 Interface-Driven Sinks** | `ILogDestination` is a contract — Loki, Postgres, rolling files, or anything else is a consumer implementation, never a dependency of this package |
|
|
1186
|
-
| **🌳 Zero Runtime Deps** | `"dependencies": {}` — every package arrives as a peer dependency, so consumers pin exact versions and the supply-chain surface stays theirs |
|
|
762
|
+
Providers are singletons: `AsyncLocalStorage` delivers per-request context without `Scope.REQUEST`. ALS context and the OTel span merge into one mixin in a fixed order (ALS first, then OTel, so an active span wins a conflict).
|
|
1187
763
|
|
|
1188
764
|
---
|
|
1189
765
|
|
|
1190
766
|
## 🔐 Security Model
|
|
1191
767
|
|
|
1192
|
-
A logger sees every payload the application handles, so the security posture is about what **never** reaches the sink
|
|
768
|
+
A logger sees every payload the application handles, so the security posture is about what **never** reaches the sink, and about a sink failure never reaching the application.
|
|
1193
769
|
|
|
1194
770
|
### Redaction by default
|
|
1195
771
|
|
|
1196
|
-
The library censors **32 sensitive field names** wherever they appear in a
|
|
772
|
+
The library censors **32 sensitive field names** wherever they appear in a record: down to 100 levels of nesting, inside arrays and inside class instances. Past that ceiling a nested object is dropped rather than emitted, so the limit cannot become a leak.
|
|
1197
773
|
|
|
1198
774
|
| Category | Fields |
|
|
1199
775
|
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -1207,33 +783,12 @@ The library censors **32 sensitive field names** wherever they appear in a log r
|
|
|
1207
783
|
| Conservative PII | `email` |
|
|
1208
784
|
| HTTP headers (absolute) | `req.headers.authorization`, `req.headers.cookie`, `req.headers["x-api-key"]`, `req.headers["x-auth-token"]`, `res.headers["set-cookie"]` — retained for the legacy `'paths'` strategy; the by-name row above already covers these shapes and every other |
|
|
1209
785
|
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
Redaction is one **recursive, snapshotting walk** of the record: a value is censored when its KEY NAME is in the set above, wherever that key sits. Nothing the caller passed is mutated, and every value is read exactly once and pinned into a fresh structure — so what reaches the sink is guaranteed to be what was inspected, even when the payload carries accessors or a `toJSON` that could answer differently on a second read.
|
|
1213
|
-
|
|
1214
|
-
A value with a `toJSON` is inspected through that method's output, because that is what reaches the log. A method can also **rename** what it exposes — `{ password, toJSON: () => ({ value: this.password }) }` would emit the secret under a name nobody declared sensitive — so when the source object itself carries a sensitive key, the method is not trusted and the whole value is censored. This deliberately over-redacts an object that holds a sensitive key and correctly omits it; the alternative (running `toJSON` against a sanitized copy) throws on every method that reads an internal slot rather than an own property, which is `Date`, `Decimal` and Luxon.
|
|
786
|
+
Redaction is one **recursive, snapshotting walk**: a value is censored when its key name is in the set, wherever it sits. Nothing the caller passed is mutated, and every value is read once and pinned into a fresh structure, so what reaches the sink is what was inspected even when the payload carries accessors or a `toJSON` that could answer differently on a second read. A value with a `toJSON` is inspected through that method's output; when the source object itself carries a sensitive key, the method is not trusted and the whole value is censored, because a method could rename what it exposes. `DEFAULT_REDACT_PATHS` is still exported at full fidelity, and `redactStrategy: 'paths'` feeds it to `fast-redact` for anyone depending on exact path semantics, with a four-level ceiling and a much higher cost.
|
|
1215
787
|
|
|
1216
788
|
> [!WARNING]
|
|
1217
|
-
> Redaction matches **key names**. A secret
|
|
1218
|
-
> emitted — `logger.log(key, msg, userId, { renamed: user.password })` writes it in clear, and so
|
|
1219
|
-
> does a `toJSON` that renames nested state. That is a property of name-based redaction, not a
|
|
1220
|
-
> defect: no name matcher can follow a value through a rename. Declare the name, or keep the value
|
|
1221
|
-
> out of the log.
|
|
1222
|
-
|
|
1223
|
-
Before `1.2.0` the same names were expanded into 140 `fast-redact` paths at wildcard depths 1–4 (`*.field`, `*.*.field`, …), because `fast-redact`'s `*` matches a single level and is not recursive. That approach had two problems, both measured:
|
|
1224
|
-
|
|
1225
|
-
| | depth-1–4 paths (pre-`1.2.0`) | name walk (`1.2.0`) |
|
|
1226
|
-
| -------------------------------- | -------------------------------------------: | ----------------------------------: |
|
|
1227
|
-
| Throughput, full production path | **9,311 logs/s** | **274,227 logs/s** |
|
|
1228
|
-
| Cost per entry | ~107 µs | ~3.6 µs |
|
|
1229
|
-
| Nesting covered | 4 levels — deeper **leaked** | 100 levels — deeper objects dropped |
|
|
1230
|
-
| `{ headers: { authorization } }` | **leaked** (only `req.headers.*` was pinned) | censored |
|
|
789
|
+
> Redaction matches **key names**. A secret under a name you have not declared sensitive is emitted: `logger.log(key, msg, userId, { renamed: user.password })` writes it in clear, and so does a `toJSON` that renames nested state. No name matcher can follow a value through a rename. Declare the name, or keep the value out of the log.
|
|
1231
790
|
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
**Not covered, by design:** a secret interpolated into the message STRING (`logger.info(key, \`token=${t}\`)`) — redaction works on structured fields, and no field-based mechanism can scrub a substring. Keep secrets out of `msg`.
|
|
1235
|
-
|
|
1236
|
-
**One entry, one line.** What the message string _cannot_ do is forge an entry. Every message argument passes through a line-separator normalization before it reaches Pino, so `\r`, `\n`, U+2028, U+2029 and C1 NEL (U+0085) become the literal two-character sequence `\n` — and every other control character that can drive a terminal (ESC, vertical tab, form feed, backspace, the rest of C0 except TAB, DEL and the C1 range) becomes its readable `\uXXXX` escape. This protects **two** sinks, not one. `pino-pretty` (shipped here as `PrettyDevDestination`) and any destination that re-renders the parsed message write those bytes straight to the terminal, where a raw newline **or** an `ESC E` produces something indistinguishable from a separate log entry. And the raw NDJSON line is exposed too when a human reads it in a terminal: JSON escaping covers only C0, so `JSON.stringify` and Pino's serializer emit DEL, the C1 range (U+0085 NEL included), U+2028 and U+2029 **verbatim** — measured on real bytes. Escaping at the sink neutralizes both paths. The scrubbed stack gets the same escaping (its newlines are kept, since a stack is multi-line by design), because `pino-pretty` prints it raw and its first line repeats the error message. Structured fields are untouched: `err.message` keeps the original text verbatim. That is the boundary — a control character placed in a **metadata value** still reaches a terminal, because escaping data would mean rewriting what you asked to be logged. Only `msg` and the stack carry this guarantee.
|
|
791
|
+
**One entry, one line.** Every message argument passes through a normalization before it reaches Pino: line separators (`\r`, `\n`, U+2028, U+2029, U+0085) become the two-character sequence `\n`, and every other control character that can drive a terminal (ESC, vertical tab, form feed, backspace, the rest of C0 except TAB, DEL and the C1 range) becomes a readable `\uXXXX` escape. This keeps a message from forging an entry in `pino-pretty` and in any destination that re-renders it, and `JSON.stringify` alone would leave DEL, C1, U+2028 and U+2029 verbatim in a raw line read in a terminal. The scrubbed stack gets the same escaping (its newlines are kept). Structured fields are untouched, so `err.message` keeps the original text, and a control character in a **metadata value** still reaches a terminal: only `msg` and the stack carry this guarantee.
|
|
1237
792
|
|
|
1238
793
|
### Extending the defaults
|
|
1239
794
|
|
|
@@ -1248,21 +803,10 @@ BymaxLoggerModule.forRoot({
|
|
|
1248
803
|
})
|
|
1249
804
|
```
|
|
1250
805
|
|
|
1251
|
-
The extra paths are **merged** with the defaults
|
|
806
|
+
The extra paths are **merged** with the defaults, never replacing them.
|
|
1252
807
|
|
|
1253
808
|
> [!IMPORTANT]
|
|
1254
|
-
> A
|
|
1255
|
-
> censors `ssn` wherever it appears, not only under `user`. That is broader than the path you
|
|
1256
|
-
> wrote, deliberately: consumer paths are applied by Pino's stringifier, which runs after the
|
|
1257
|
-
> per-field size bound, so without this a field covered only by a path could still surface inside
|
|
1258
|
-
> a truncation envelope's `_preview`. It errs toward redacting a name you have already declared
|
|
1259
|
-
> secret.
|
|
1260
|
-
>
|
|
1261
|
-
> An **array index is not a name**, so an unquoted numeric segment is skipped and the path falls
|
|
1262
|
-
> back to the nearest name: `redactPaths: ['tokens[0]']` censors the whole `tokens` array. The
|
|
1263
|
-
> walk matches key names and never array positions, so feeding it `0` would cover nothing while
|
|
1264
|
-
> censoring any object key literally named `0`. The quoted form `['obj["0"]']` stays a name,
|
|
1265
|
-
> since an object key named `0` IS matched by the walk.
|
|
809
|
+
> A path's **leaf name** is also fed to the name walk, so `redactPaths: ['user.ssn']` censors `ssn` wherever it appears, not only under `user`. That is deliberate: paths are applied by Pino's stringifier, after the per-field size bound, and without this a field covered only by a path could surface inside a truncation envelope's `_preview`. An **array index is not a name**: `redactPaths: ['tokens[0]']` censors the whole `tokens` array, while the quoted form `['obj["0"]']` stays a name.
|
|
1266
810
|
|
|
1267
811
|
### Disabling defaults (not recommended)
|
|
1268
812
|
|
|
@@ -1274,25 +818,25 @@ BymaxLoggerModule.forRoot({
|
|
|
1274
818
|
})
|
|
1275
819
|
```
|
|
1276
820
|
|
|
1277
|
-
A `LOGGER_BOOTSTRAP_WARNING`
|
|
821
|
+
A `LOGGER_BOOTSTRAP_WARNING` is emitted on startup so security reviews can audit when PII protection was reduced on purpose.
|
|
1278
822
|
|
|
1279
823
|
### An append-only default list
|
|
1280
824
|
|
|
1281
|
-
`DEFAULT_REDACT_PATHS` is append-only by contract: a path may be added in a minor release, but removing one requires a major version
|
|
825
|
+
`DEFAULT_REDACT_PATHS` is append-only by contract: a path may be added in a minor release, but removing one requires a major version. A field that silently stopped being redacted is a leak nobody would notice.
|
|
1282
826
|
|
|
1283
827
|
### Validated trace identifiers
|
|
1284
828
|
|
|
1285
|
-
|
|
829
|
+
The OTel mixin passes the active span's identifiers through `isValidTraceId` / `isValidSpanId` before injecting them, so a malformed or attacker-influenced value cannot reach the correlation fields your dashboards key on.
|
|
1286
830
|
|
|
1287
831
|
### Destination failures are contained
|
|
1288
832
|
|
|
1289
|
-
Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr`
|
|
833
|
+
Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr` (never back through the logger, which would loop) and the entry is dropped for that sink only. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
|
|
1290
834
|
|
|
1291
835
|
### What redaction covers, and what it cannot
|
|
1292
836
|
|
|
1293
|
-
The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one
|
|
837
|
+
The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one. A stack or message is written at most 16384 characters long and ends with `…[truncated]` when cut. A string under a metadata key is the caller's own data and is written as given: `maxEntrySizeBytes` bounds what a serializer returns, not a metadata string.
|
|
1294
838
|
|
|
1295
|
-
Redaction
|
|
839
|
+
Redaction matches **field names**, not values. A secret under a covered name is censored at any depth (under the legacy `'paths'` strategy the four-level ceiling applies instead), but the same secret **embedded inside a string** under an uncovered name travels intact:
|
|
1296
840
|
|
|
1297
841
|
```json
|
|
1298
842
|
{
|
|
@@ -1301,76 +845,59 @@ Redaction here matches **field names**, not values. Under the default `redactStr
|
|
|
1301
845
|
}
|
|
1302
846
|
```
|
|
1303
847
|
|
|
1304
|
-
|
|
848
|
+
No name rule reaches the second case, and scanning values for secret-shaped text would rewrite what you asked to log. **The boundary is yours to hold:** do not put rendered bodies, raw provider responses or whole request payloads into a field, and remember that an upstream error attached as `cause` carries whatever that error carries.
|
|
1305
849
|
|
|
1306
|
-
`redactStrategy` governs **your** payload
|
|
850
|
+
`redactStrategy` governs **your** payload: the record, child bindings and the output of any serializer you supply. The built-in `err` serializer is always name-walked, even under `'paths'`, because the four-level ceiling cannot reach the depth of a `cause` chain. Under `'paths'`, an `Error` anywhere in the record is converted with the default names censored in its own fields and its `cause` chain at any depth, with your paths applied on top; non-`Error` data is matched only by the configured paths.
|
|
1307
851
|
|
|
1308
852
|
#### A value interpolated into the message has no name to redact
|
|
1309
853
|
|
|
1310
|
-
The case above is a secret inside a field's **value**. The sharper version is a value interpolated into the message itself, where there is no field at all:
|
|
1311
|
-
|
|
1312
854
|
```ts
|
|
1313
|
-
// Both identifiers are
|
|
1314
|
-
// `familyId` field for any strategy to match, only a string that happens to
|
|
1315
|
-
// contain them.
|
|
855
|
+
// Both identifiers are message text: there is no field for any strategy to match.
|
|
1316
856
|
logger.warn(`reissueTokens: family revoked userId=${userId} familyId=${familyId}`)
|
|
1317
857
|
|
|
1318
|
-
// Same facts, as fields
|
|
1319
|
-
// library's own keys, not your domain's — and follows MODULE_ACTION_RESULT:
|
|
1320
|
-
// module AUTH, action REUSE, result DETECTED.
|
|
858
|
+
// Same facts, as fields (logKey is yours, in MODULE_ACTION_RESULT form).
|
|
1321
859
|
logger.warnStructured('AUTH_REUSE_DETECTED', 'token family revoked after reuse detection', userId, {
|
|
1322
860
|
familyId
|
|
1323
861
|
})
|
|
1324
862
|
```
|
|
1325
863
|
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
The rule that follows is short: **a value that matters is a field, not text.** A field can be redacted, queried, aggregated and correlated; the same value inside `msg` can only be read by a human who happens to be looking. That applies most to the values you would least like to interpolate — tokens, identifiers, addresses — and it is the one part of this contract the library cannot enforce for you, because the decision is made at the call site.
|
|
864
|
+
An interpolated value has no name, so no configuration can redact it. **A value that matters is a field, not text.** A field can be redacted, queried and correlated; inside `msg` it can only be read by a human. The library cannot enforce this, because the decision is made at the call site.
|
|
1329
865
|
|
|
1330
866
|
### A closed pipe does not kill the process
|
|
1331
867
|
|
|
1332
|
-
`node app | head` closes the read end of stdout while the application is still writing.
|
|
1333
|
-
|
|
1334
|
-
Every write this library makes to a process stream — the default stdout sink, the last-resort rescue, the pre-init drain, the `stderr` failure reports — installs a swallowing `'error'` listener on first use. The one exception is the stream `pino-pretty` writes through inside `PrettyDevDestination`, which attaches `'error'` listeners of its own. **The side effect is worth knowing:** that listener is on the shared `process.stdout`, so after the first log line an EPIPE raised by _your_ writes stops being an uncaught exception too. The alternative is the crash above. Your own `'error'` listener is never removed or replaced — this only ever adds one.
|
|
1335
|
-
|
|
1336
|
-
If you write to `process.stdout` from a custom `ILogDestination`, do the same in your own sink; the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has the exact pattern.
|
|
868
|
+
`node app | head` closes the read end of stdout while the application is still writing. Node reports the `EPIPE` asynchronously through the stream's `'error'` event, after `write()` returned, and attaches no default handler to `process.stdout`, so the emit becomes an uncaught exception and the process dies. Every write the library makes to a process stream (default stdout sink, last-resort rescue, pre-init drain, `stderr` reports) installs a swallowing `'error'` listener on first use. The one exception is the stream `pino-pretty` writes through, which attaches listeners of its own. The side effect: the listener sits on the shared `process.stdout`, so an EPIPE raised by your own writes stops being an uncaught exception too. Your own `'error'` listener is never removed or replaced. A custom `ILogDestination` that writes to `process.stdout` should do the same; the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has the pattern.
|
|
1337
869
|
|
|
1338
870
|
### Bounded field size
|
|
1339
871
|
|
|
1340
|
-
Every serializer
|
|
872
|
+
Every serializer, the default `err` one and any you supply, is wrapped so a field whose serialized JSON exceeds `maxEntrySizeBytes` (64 KB by default) is replaced by an envelope with `_truncated`, `_logKey: 'LOGGER_ENTRY_TRUNCATED'`, `_originalSize` and a 200-character `_preview`.
|
|
1341
873
|
|
|
1342
874
|
### Security Checklist
|
|
1343
875
|
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
- `
|
|
1347
|
-
-
|
|
1348
|
-
-
|
|
1349
|
-
-
|
|
1350
|
-
- Destination credentials (Loki, Postgres, OTLP) come from the environment, never from values written into module options in source control
|
|
1351
|
-
- Log retention at the sink matches your data-retention policy — redaction bounds what is stored, not how long
|
|
876
|
+
- `shouldDisableDefaultRedact` stays `false`; if it is on, the `LOGGER_BOOTSTRAP_WARNING` must be justified in a security review.
|
|
877
|
+
- Every custom field carrying a secret or personal document is added to `redactPaths` at the depths where it appears. The default list covers the standard set, not your domain's.
|
|
878
|
+
- `http.excludePaths` regexes are anchored and linear-time: an unbounded pattern runs on every request URL (ReDoS).
|
|
879
|
+
- Custom destinations never re-serialize the raw request object; they receive the already-redacted NDJSON line.
|
|
880
|
+
- Destination credentials (Loki, Postgres, OTLP) come from the environment, never from module options in source control.
|
|
881
|
+
- Log retention at the sink matches your data-retention policy: redaction bounds what is stored, not how long.
|
|
1352
882
|
|
|
1353
883
|
---
|
|
1354
884
|
|
|
1355
885
|
## 🛡️ Security Table
|
|
1356
886
|
|
|
1357
|
-
|
|
|
1358
|
-
| ------------------- |
|
|
1359
|
-
| PII
|
|
1360
|
-
| Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey`
|
|
1361
|
-
| MFA
|
|
1362
|
-
| PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry`
|
|
1363
|
-
| LGPD
|
|
1364
|
-
| HTTP
|
|
1365
|
-
| Redact
|
|
1366
|
-
| Trace
|
|
1367
|
-
| URL
|
|
1368
|
-
| Destination
|
|
1369
|
-
| Field
|
|
1370
|
-
| Supply
|
|
1371
|
-
|
|
1372
|
-
> [!IMPORTANT]
|
|
1373
|
-
> Redaction protects the fields it knows about. Any new field carrying a secret or a personal document must be added to `redactPaths` — the default list covers the standard set, not your domain's.
|
|
887
|
+
| Control | Implementation |
|
|
888
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
889
|
+
| PII redaction | 32 field names censored at any depth, to a 100-level ceiling, in one snapshotting walk |
|
|
890
|
+
| Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey` |
|
|
891
|
+
| MFA secrets | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
|
|
892
|
+
| PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
|
|
893
|
+
| LGPD documents | `cpf`, `cnpj`, `rg`, plus `email` as a conservative default |
|
|
894
|
+
| HTTP headers | `authorization`, `cookie`, `x-api-key`, `x-auth-token`, `set-cookie` |
|
|
895
|
+
| Redact list | `DEFAULT_REDACT_PATHS` is append-only; removal requires a major version |
|
|
896
|
+
| Trace injection | `isValidTraceId` / `isValidSpanId` validate every identifier before it is written |
|
|
897
|
+
| URL cardinality | UUIDs, ULIDs, nanoids and numeric IDs become `:id`; the query string is stripped |
|
|
898
|
+
| Destination failure | Every `write()` is wrapped; a failure goes to `stderr` and is swallowed |
|
|
899
|
+
| Field size | Per-field UTF-8 cap at `maxEntrySizeBytes` (64 KB default), over it a truncation envelope |
|
|
900
|
+
| Supply chain | `"dependencies": {}`, no runtime packages of the library's own choosing |
|
|
1374
901
|
|
|
1375
902
|
---
|
|
1376
903
|
|
|
@@ -1389,30 +916,20 @@ When integrating `@bymax-one/nest-logger` in production, verify each of the foll
|
|
|
1389
916
|
|
|
1390
917
|
## 🧪 Testing & Quality
|
|
1391
918
|
|
|
1392
|
-
A logger runs on every request of every service that installs it, so
|
|
919
|
+
A logger runs on every request of every service that installs it, so every behavior is pinned so that a regression fails a test:
|
|
1393
920
|
|
|
1394
|
-
-
|
|
1395
|
-
-
|
|
1396
|
-
|
|
1397
|
-
kill are suppressed on the line they apply to and each carries its reason; a rule against those
|
|
1398
|
-
comments was retired once their cost was measured at **+0.10 kB brotli**, roughly a tenth of
|
|
1399
|
-
what it had been assumed to be (see the [report](./docs/mutation_testing_results.md))
|
|
1400
|
-
- ✅ **Every suppression carries its reason** — each `// Stryker disable` names, after the `:` Stryker reads it from, why the mutant it silences cannot be observed; one of them is recorded as what it is, a mutant the suite kills but Stryker fails to attribute, rather than mislabelled an equivalent. `check:mutants` proves those reasons parse, so they reach the report rather than the `Ignored using a comment` fallback, and the score stays an accounting rather than a number
|
|
1401
|
-
- ✅ **No real I/O in unit tests** — the Pino instance and every destination are mocked; e2e tests exercise the wired module through `@nestjs/testing` and supertest
|
|
921
|
+
- **100% coverage** (statements, branches, functions, lines), enforced as a release gate across unit and e2e tests.
|
|
922
|
+
- **100% mutation score** with [Stryker](https://stryker-mutator.io/) on a cold run, with a `break` threshold of 100. The few mutants no test can kill are suppressed on the line they apply to, each with its reason (`pnpm check:mutants` proves the reasons parse). See the [report](./docs/mutation_testing_results.md).
|
|
923
|
+
- **No real I/O in unit tests**: Pino and every destination are mocked, and e2e tests exercise the wired module through `@nestjs/testing` and supertest.
|
|
1402
924
|
|
|
1403
925
|
```bash
|
|
1404
926
|
pnpm test # unit tests (Jest)
|
|
1405
|
-
pnpm test:
|
|
1406
|
-
pnpm test:
|
|
1407
|
-
pnpm
|
|
1408
|
-
pnpm
|
|
1409
|
-
pnpm typecheck # tsc strict check (all tsconfig variants)
|
|
1410
|
-
pnpm lint # ESLint
|
|
927
|
+
pnpm test:e2e # end-to-end tests
|
|
928
|
+
pnpm test:cov:all # full coverage gate
|
|
929
|
+
pnpm mutation # Stryker mutation testing
|
|
930
|
+
pnpm typecheck && pnpm lint
|
|
1411
931
|
```
|
|
1412
932
|
|
|
1413
|
-
> [!NOTE]
|
|
1414
|
-
> Line coverage proves a line _executed_ under test; mutation testing proves a test _would fail_ if that line were wrong. The full methodology and per-area breakdown are in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md).
|
|
1415
|
-
|
|
1416
933
|
---
|
|
1417
934
|
|
|
1418
935
|
## 📖 API Reference
|
|
@@ -1421,9 +938,7 @@ pnpm lint # ESLint
|
|
|
1421
938
|
|
|
1422
939
|
Implements NestJS `LoggerService`. All methods are available via `@InjectLogger()`.
|
|
1423
940
|
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
**Structured API** — the `MODULE_ACTION_RESULT` convention. The third parameter is the acting **`userId`**, not a context label (the context comes from `@InjectLogger(ctx)`), and it may be omitted: when it is, an ambient `userId` from the `LogContextService` scope is used.
|
|
941
|
+
**Structured API** — the `MODULE_ACTION_RESULT` convention. The third parameter is the acting **`userId`**, not a context label (the context comes from `@InjectLogger(ctx)`), and it may be omitted: an ambient `userId` from the `LogContextService` scope is then used.
|
|
1427
942
|
|
|
1428
943
|
| Method | Signature | Notes |
|
|
1429
944
|
| ----------------- | --------------------------------- | ---------------------------------------------------------------- |
|
|
@@ -1431,14 +946,9 @@ There are **two** APIs on this class, and they do not share a signature shape.
|
|
|
1431
946
|
| `warnStructured` | `(logKey, msg, userId?, meta?)` | Structured warn log — takes a **message string** |
|
|
1432
947
|
| `errorStructured` | `(logKey, error, userId?, meta?)` | Structured error log — takes an **`Error`**, serialized to `err` |
|
|
1433
948
|
|
|
1434
|
-
|
|
1435
|
-
> `meta` carries arbitrary fields, with two reserved groups dropped on the way in. `logKey`,
|
|
1436
|
-
> `userId` and `context` belong to the payload — the entry states who acted and where, read from
|
|
1437
|
-
> the authenticated ALS scope, so a metadata bag cannot forge them. `__proto__`, `constructor`
|
|
1438
|
-
> and `prototype` are dropped as well: they name a prototype chain rather than a field, and an
|
|
1439
|
-
> own `__proto__` (what `JSON.parse` of a request body produces) would otherwise be lost anyway.
|
|
949
|
+
`meta` carries arbitrary fields, except that `logKey`, `userId` and `context` belong to the payload (read from the authenticated ALS scope, so a metadata bag cannot forge them) and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field.
|
|
1440
950
|
|
|
1441
|
-
**NestJS `LoggerService` bridge** — the variadic contract NestJS
|
|
951
|
+
**NestJS `LoggerService` bridge** — the variadic contract NestJS calls, so `app.useLogger()` works. These take a message, not a log key.
|
|
1442
952
|
|
|
1443
953
|
| Method | Signature | Notes |
|
|
1444
954
|
| --------- | -------------------------------------- | ---------------------------------------------- |
|
|
@@ -1470,17 +980,7 @@ There are **two** APIs on this class, and they do not share a signature shape.
|
|
|
1470
980
|
| `get` | `(key)` | Reads one field from the current scope, or `undefined` when unset or outside a `run()` call |
|
|
1471
981
|
| `getStore` | `()` | Returns current scope or `undefined` outside a `run()` call |
|
|
1472
982
|
|
|
1473
|
-
|
|
1474
|
-
> **A nested `run()` discards the enclosing context.** The inner scope starts from its own `store`
|
|
1475
|
-
> alone, so a field an outer scope had set — a `tenantId` resolved at the edge, say — is absent for
|
|
1476
|
-
> the whole inner scope. Nothing throws; `get()` simply returns `undefined` and the field is missing
|
|
1477
|
-
> from every entry the callback emits, which is the kind of thing found by losing a field in
|
|
1478
|
-
> production. Use `runMerged()` when the inner scope should extend the outer one.
|
|
1479
|
-
>
|
|
1480
|
-
> Replacement stays the default because the opposite leaks in a worse direction: a background job
|
|
1481
|
-
> started inside a request scope would silently inherit the caller's `userId` and attribute its
|
|
1482
|
-
> entries to a user who never triggered it. A missing field is visibly missing; an inherited one is
|
|
1483
|
-
> wrong while looking right.
|
|
983
|
+
**A nested `run()` discards the enclosing context.** The inner scope starts from its own `store` alone, so a field an outer scope had set (a `tenantId` resolved at the edge) is absent for the whole inner scope; nothing throws and `get()` returns `undefined`. Use `runMerged()` when the inner scope should extend the outer one. Replacement is the default because the opposite leaks worse: a background job started inside a request scope would inherit the caller's `userId` and attribute its entries to a user who never triggered it.
|
|
1484
984
|
|
|
1485
985
|
### Decorators
|
|
1486
986
|
|
|
@@ -1494,21 +994,20 @@ There are **two** APIs on this class, and they do not share a signature shape.
|
|
|
1494
994
|
|
|
1495
995
|
Every token is a `Symbol`, never a string, so it cannot collide with one of yours. Inject with an explicit `@Inject(TOKEN)`: the package is built without decorator metadata, and so is any consumer built the same way.
|
|
1496
996
|
|
|
1497
|
-
| Export | Provides
|
|
1498
|
-
| ---------------------------- |
|
|
1499
|
-
| `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions`
|
|
1500
|
-
| `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance
|
|
1501
|
-
| `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]`
|
|
1502
|
-
| `LOGGER_REDACTOR_TOKEN` | the by-name redaction function, `(value: unknown) => unknown`. With `redactStrategy: 'paths'` it
|
|
1503
|
-
| `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class)
|
|
1504
|
-
| `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth
|
|
1505
|
-
| `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names
|
|
1506
|
-
| `isValidTraceId(id)` | `true` for 32 lowercase hex characters that are not all zeros
|
|
997
|
+
| Export | Provides | Use it to |
|
|
998
|
+
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
999
|
+
| `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions` | read the effective configuration, defaults applied |
|
|
1000
|
+
| `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance | hand it to a library that wants a Pino logger |
|
|
1001
|
+
| `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]` | inspect what is registered; do not mutate it |
|
|
1002
|
+
| `LOGGER_REDACTOR_TOKEN` | the by-name redaction function, `(value: unknown) => unknown`. With `redactStrategy: 'paths'` it censors no name outside an `Error`, because Pino's path redaction then runs at write time instead | apply the module's by-name redaction to a value of your own under the default `'names'` strategy; do not treat it as a sanitization boundary under `'paths'`. |
|
|
1003
|
+
| `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class) | inject the context by token |
|
|
1004
|
+
| `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth | extend the defaults by reference instead of copying the list |
|
|
1005
|
+
| `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names | only with `redactStrategy: 'paths'` |
|
|
1006
|
+
| `isValidTraceId(id)` | `true` for 32 lowercase hex characters that are not all zeros | apply the rule the trace mixin applies before it injects an id |
|
|
1507
1007
|
|
|
1508
1008
|
### Level maps (from `@bymax-one/nest-logger`)
|
|
1509
1009
|
|
|
1510
|
-
`LogEntry.level` is the Pino string
|
|
1511
|
-
column converts with the exported maps instead of hard-coding them:
|
|
1010
|
+
`LogEntry.level` is the Pino string label, not the numeric code. A destination writing a numeric column converts with the exported maps:
|
|
1512
1011
|
|
|
1513
1012
|
```typescript
|
|
1514
1013
|
import { PINO_LEVEL_NAMES, PINO_LEVEL_NUMBERS } from '@bymax-one/nest-logger'
|
|
@@ -1531,10 +1030,7 @@ type ServiceMetadata = {
|
|
|
1531
1030
|
readonly environment?: string
|
|
1532
1031
|
}
|
|
1533
1032
|
|
|
1534
|
-
// What is EMITTED
|
|
1535
|
-
// `service.instance.id`, and the environment is not under `service` at all.
|
|
1536
|
-
// Reusing the configuration type here would advertise `entry.service.instanceId`,
|
|
1537
|
-
// which no entry carries.
|
|
1033
|
+
// What is EMITTED: `instanceId` nests as `service.instance.id`, and the environment is not under `service`.
|
|
1538
1034
|
type EmittedServiceResource = {
|
|
1539
1035
|
readonly name: string
|
|
1540
1036
|
readonly version: string
|
|
@@ -1568,40 +1064,7 @@ type LogEntry = {
|
|
|
1568
1064
|
}
|
|
1569
1065
|
```
|
|
1570
1066
|
|
|
1571
|
-
Under `resourceFormat: 'flat'` there is no `service` object
|
|
1572
|
-
top-level keys (`"service.instance.id"`), which the index signature already admits.
|
|
1573
|
-
|
|
1574
|
-
The emitted types are exported, so a helper that receives one can be typed without inlining its
|
|
1575
|
-
shape:
|
|
1576
|
-
|
|
1577
|
-
```typescript
|
|
1578
|
-
import type {
|
|
1579
|
-
EmittedDeploymentResource,
|
|
1580
|
-
EmittedServiceResource,
|
|
1581
|
-
LogEntry
|
|
1582
|
-
} from '@bymax-one/nest-logger/shared'
|
|
1583
|
-
|
|
1584
|
-
/** Build the identity triplet a backend joins on, from a parsed entry. */
|
|
1585
|
-
function identityOf(entry: LogEntry): string {
|
|
1586
|
-
const service: EmittedServiceResource | undefined = entry.service
|
|
1587
|
-
const deployment: EmittedDeploymentResource | undefined = entry.deployment
|
|
1588
|
-
if (service === undefined) {
|
|
1589
|
-
return 'unknown'
|
|
1590
|
-
}
|
|
1591
|
-
// `service.namespace` is part of the identity, not decoration: OTel allows two
|
|
1592
|
-
// services to share a name when their namespaces differ, so a key built without
|
|
1593
|
-
// it collapses them into one.
|
|
1594
|
-
const namespace = service.namespace ?? 'no-namespace'
|
|
1595
|
-
const instance = service.instance?.id ?? 'no-instance'
|
|
1596
|
-
const environment = deployment?.environment.name ?? 'no-environment'
|
|
1597
|
-
return `${namespace}/${service.name}@${service.version}/${instance}/${environment}`
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
/** `event.name` is declared, so it reads as a string without a cast. */
|
|
1601
|
-
function eventOf(entry: LogEntry): string | undefined {
|
|
1602
|
-
return entry['event.name']
|
|
1603
|
-
}
|
|
1604
|
-
```
|
|
1067
|
+
Under `resourceFormat: 'flat'` there is no `service` object: the values arrive as dotted top-level keys (`"service.instance.id"`), which the index signature admits.
|
|
1605
1068
|
|
|
1606
1069
|
### `ILogDestination`
|
|
1607
1070
|
|
|
@@ -1671,69 +1134,45 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
|
|
|
1671
1134
|
|
|
1672
1135
|
## ⚡ Performance
|
|
1673
1136
|
|
|
1674
|
-
|
|
1137
|
+
Measured by this repository's own benchmark (`pnpm bench`, see [bench/README.md](./bench/README.md)) on the shipped configuration, which is what `forRoot({ service })` builds with nothing else set: name-walk redaction and the composed ALS/OTel mixin, inside an active request context, writing to a no-op sink.
|
|
1675
1138
|
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
| **Pino 10 (JSON)** | **~750,000** | **1.3 µs** | **~45 MB** | **8%** |
|
|
1679
|
-
| Pino 10 (pretty) | ~120,000 | 8 µs | ~50 MB | 14% |
|
|
1680
|
-
| Winston 3 (JSON) | ~110,000 | 9 µs | ~85 MB | 22% |
|
|
1681
|
-
| Winston 3 (transports) | ~75,000 | 13 µs | ~95 MB | 28% |
|
|
1139
|
+
- **About 274,000 entries/s** through the full production path, which retains 0.345× of the throughput of the bare wrapper (no redaction, no mixin) measured the same way.
|
|
1140
|
+
- The legacy `redactStrategy: 'paths'` measures about 7,900 entries/s in the same bench.
|
|
1682
1141
|
|
|
1683
|
-
|
|
1142
|
+
Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
|
|
1684
1143
|
|
|
1685
1144
|
---
|
|
1686
1145
|
|
|
1687
1146
|
## 🚫 What This Library Does NOT Do
|
|
1688
1147
|
|
|
1689
|
-
By design, the following are out of scope:
|
|
1690
|
-
|
|
1691
1148
|
- ❌ **OTel SDK initialization** — consumer's responsibility in `main.ts`
|
|
1692
1149
|
- ❌ **Custom metrics** (OTel Metrics API) — use `@opentelemetry/api` directly
|
|
1693
|
-
- ❌ **Alerting**
|
|
1150
|
+
- ❌ **Alerting** — configure your OTLP backend
|
|
1694
1151
|
- ❌ **Log aggregation UI** — Grafana, Datadog, Honeycomb
|
|
1695
1152
|
- ❌ **Sentry SDK** — install `@sentry/node` in the consumer if desired
|
|
1696
|
-
- ❌ **Immutable audit logs**
|
|
1697
|
-
- ❌ **File rotation built
|
|
1698
|
-
- ❌ **Fastify** — the HTTP integration targets the Express adapter (`@nestjs/platform-express`)
|
|
1699
|
-
- ❌ **`pino-http`** —
|
|
1153
|
+
- ❌ **Immutable audit logs**
|
|
1154
|
+
- ❌ **File rotation built in** — write a destination on `pino-roll` (see the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md))
|
|
1155
|
+
- ❌ **Fastify** — the HTTP integration targets the Express adapter (`@nestjs/platform-express`)
|
|
1156
|
+
- ❌ **`pino-http`** — `HttpLoggingInterceptor` is a NestJS-native replacement; running both produces duplicate logs
|
|
1700
1157
|
|
|
1701
1158
|
---
|
|
1702
1159
|
|
|
1703
1160
|
## 🤝 Contributing
|
|
1704
1161
|
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
- TypeScript strict (`noImplicitAny`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`)
|
|
1708
|
-
- 100% test coverage gate
|
|
1709
|
-
- Conventional Commits enforced by commitlint + husky
|
|
1710
|
-
- No direct dependencies — peer deps only
|
|
1711
|
-
- All boolean identifiers prefixed with `is / has / should / can`
|
|
1712
|
-
- All log keys in `MODULE_ACTION_RESULT` format
|
|
1162
|
+
Development follows the Bymax coding standards: TypeScript strict (`noImplicitAny`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`), a 100% coverage gate, Conventional Commits (commitlint + husky), peer dependencies only, boolean identifiers prefixed `is`/`has`/`should`/`can`, and log keys in `MODULE_ACTION_RESULT` form.
|
|
1713
1163
|
|
|
1714
1164
|
```bash
|
|
1715
|
-
# Clone the repository
|
|
1716
1165
|
git clone https://github.com/bymaxone/nest-logger.git
|
|
1717
1166
|
cd nest-logger
|
|
1718
|
-
|
|
1719
|
-
# Install dependencies
|
|
1720
1167
|
pnpm install
|
|
1721
|
-
|
|
1722
|
-
# Run tests
|
|
1723
|
-
pnpm test
|
|
1724
|
-
|
|
1725
|
-
# Build
|
|
1726
|
-
pnpm build
|
|
1727
|
-
|
|
1728
|
-
# Type check
|
|
1729
|
-
pnpm typecheck
|
|
1168
|
+
pnpm test && pnpm typecheck && pnpm build
|
|
1730
1169
|
```
|
|
1731
1170
|
|
|
1732
1171
|
---
|
|
1733
1172
|
|
|
1734
1173
|
## 🔒 Security Policy
|
|
1735
1174
|
|
|
1736
|
-
If you discover a security vulnerability, please **do not** open a public issue.
|
|
1175
|
+
If you discover a security vulnerability, please **do not** open a public issue. Email **support@bymax.one** with details.
|
|
1737
1176
|
|
|
1738
1177
|
---
|
|
1739
1178
|
|