@bymax-one/nest-logger 1.4.23 → 1.4.25
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 +220 -1
- package/README.md +158 -58
- package/dist/observability/index.cjs +112 -0
- package/dist/observability/index.d.cts +55 -0
- package/dist/observability/index.d.ts +55 -0
- package/dist/observability/index.mjs +110 -0
- package/dist/server/index.cjs +416 -149
- package/dist/server/index.d.cts +82 -4
- package/dist/server/index.d.ts +82 -4
- package/dist/server/index.mjs +416 -150
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +1 -0
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.mjs +1 -0
- package/package.json +24 -1
package/README.md
CHANGED
|
@@ -63,17 +63,20 @@ The library has **zero direct dependencies**: every package arrives as a peer de
|
|
|
63
63
|
|
|
64
64
|
## 📦 Subpath Exports
|
|
65
65
|
|
|
66
|
-
One package,
|
|
66
|
+
One package, three entry points — import only what your app needs:
|
|
67
67
|
|
|
68
|
-
| Subpath
|
|
69
|
-
|
|
|
70
|
-
| **Server**
|
|
71
|
-
| **Shared**
|
|
68
|
+
| Subpath | Import | Purpose | Dependencies |
|
|
69
|
+
| ----------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-----------------------------------------------------------: |
|
|
70
|
+
| **Server** | `@bymax-one/nest-logger` | NestJS module, logger service, interceptor, filter, decorators, destinations | NestJS 11, pino, rxjs, reflect-metadata |
|
|
71
|
+
| **Shared** | `@bymax-one/nest-logger/shared` | Types, constants, the log-key regex — `LogLevel`, `LogEntry`, `ServiceMetadata`, `ResolvedServiceMetadata`, `EmittedServiceResource`, `EmittedDeploymentResource` | None |
|
|
72
|
+
| **Observability** | `@bymax-one/nest-logger/observability` | The Prometheus counters and the readiness check of the logger, for `@bymax-one/nest-core` (see [Metrics and health](#-metrics-and-health)) | `@bymax-one/nest-core` and `prom-client`, both optional peers |
|
|
72
73
|
|
|
73
74
|
```
|
|
74
75
|
shared (zero deps)
|
|
75
76
|
↑
|
|
76
77
|
server
|
|
78
|
+
↑
|
|
79
|
+
observability (optional peers)
|
|
77
80
|
```
|
|
78
81
|
|
|
79
82
|
The `/shared` subpath is safe to import in isomorphic code, test helpers, CLI scripts, or shared packages that must not pull in NestJS.
|
|
@@ -102,12 +105,15 @@ pnpm add -D pino-pretty
|
|
|
102
105
|
|
|
103
106
|
# Optional — OpenTelemetry trace correlation
|
|
104
107
|
pnpm add @opentelemetry/api @opentelemetry/sdk-node
|
|
108
|
+
|
|
109
|
+
# Optional — the /observability subpath (Prometheus counters and the readiness check)
|
|
110
|
+
pnpm add @bymax-one/nest-core prom-client
|
|
105
111
|
```
|
|
106
112
|
|
|
107
113
|
> [!WARNING]
|
|
108
114
|
> **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.
|
|
109
115
|
|
|
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.
|
|
116
|
+
`@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. `LoggableRequest` carries `headers`, `method`, `url`, and optionally `originalUrl`, `ip` and `user`; the `userId` of an HTTP entry is `user.sub`, else `user.id`. `LoggableResponse` carries `statusCode`, `writableFinished`, `setHeader`, `status(code).json(body)` and `on('close', listener)`, which a custom adapter must provide for the terminal entry to be written.
|
|
111
117
|
|
|
112
118
|
### 2. Register the module
|
|
113
119
|
|
|
@@ -277,7 +283,7 @@ A key that holds `undefined` or `null` is read as not set, in the options and in
|
|
|
277
283
|
| `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
|
|
278
284
|
| `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
|
|
279
285
|
| `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults. A `req` serializer of your own receives the redaction walk's copy of the request, which has no `headers`: read the headers you need from `rawHeaders`, or log them under another key |
|
|
280
|
-
| `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function
|
|
286
|
+
| `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function. Its return value is converted with `String()` and written as the JSON string `time`, so a quote or a new line in it cannot break the line. A function that throws makes the log call throw |
|
|
281
287
|
| `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
|
|
282
288
|
|
|
283
289
|
### `http` options
|
|
@@ -292,6 +298,19 @@ A key that holds `undefined` or `null` is read as not set, in the options and in
|
|
|
292
298
|
| `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) |
|
|
293
299
|
| `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 |
|
|
294
300
|
|
|
301
|
+
### Option details
|
|
302
|
+
|
|
303
|
+
- Every option is type-checked at startup: a wrong type (the string `'false'` for a boolean, say) throws `[BymaxLoggerModule] options.<path> …` and names what was received by type, never by value.
|
|
304
|
+
- `service.name` and `service.version` must be strings that are not blank after `trim()`.
|
|
305
|
+
- `redactPaths` entries must be non-empty strings in `fast-redact` path syntax. A malformed path (`a..b`, `a[`) is not checked by the module: Pino refuses it while the logger is built, with `Invalid redaction path (<path>)`, which is not prefixed `[BymaxLoggerModule]`.
|
|
306
|
+
- Each `destinations` entry must be an object with a non-empty string `name` and a `write` function; `onInit`, `onShutdown` and `onRegistryReady`, when present, must be functions. Anything else is refused at startup with `[BymaxLoggerModule] options.destinations[i] …`.
|
|
307
|
+
- `serializers` must be a plain object whose every value is a function; a key `err` replaces the default `err` serializer.
|
|
308
|
+
- `http.excludePaths` replaces the default list instead of adding to it, and the defaults are exact anchored paths: `[/^\/health$/]` stops excluding `/metrics`.
|
|
309
|
+
- `http.tenantIdResolver` is synchronous; a returned promise counts as no tenant.
|
|
310
|
+
- A destination's `minLevel` can only narrow: it receives entries at the stricter of its `minLevel` and the module `level`. A value that is not a `LogLevel`, or a getter that throws, is ignored and the module level applies.
|
|
311
|
+
- A destination's `queuedBytes()` that throws or returns a number that is not finite counts as `0`.
|
|
312
|
+
- There is no retry and no back-off: a destination that initialized and keeps failing keeps receiving entries, and keeps being reported (throttled). One that needs to back off does so itself.
|
|
313
|
+
|
|
295
314
|
### `otel` options
|
|
296
315
|
|
|
297
316
|
| Option | Type | Default | Description |
|
|
@@ -337,22 +356,24 @@ For example, `createLoggerOptions()` can return `{ service: { name: this.cfg.get
|
|
|
337
356
|
|
|
338
357
|
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:
|
|
339
358
|
|
|
340
|
-
| Log key | When
|
|
341
|
-
| --------------------------- |
|
|
342
|
-
| `HTTP_REQUEST_START` | Request received
|
|
343
|
-
| `HTTP_REQUEST_SUCCESS` | 2xx response
|
|
344
|
-
| `HTTP_REQUEST_REDIRECT` | 3xx response
|
|
345
|
-
| `HTTP_REQUEST_CLIENT_ERROR` | 4xx response
|
|
346
|
-
| `HTTP_REQUEST_SERVER_ERROR` | 5xx response
|
|
347
|
-
| `HTTP_REQUEST_ABORTED` | Connection closed before the response was delivered
|
|
348
|
-
| `HTTP_EXCEPTION_HANDLED` | `HttpException` caught by the filter
|
|
349
|
-
| `HTTP_EXCEPTION_UNHANDLED` |
|
|
359
|
+
| Log key | When |
|
|
360
|
+
| --------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
361
|
+
| `HTTP_REQUEST_START` | Request received |
|
|
362
|
+
| `HTTP_REQUEST_SUCCESS` | 2xx response |
|
|
363
|
+
| `HTTP_REQUEST_REDIRECT` | 3xx response |
|
|
364
|
+
| `HTTP_REQUEST_CLIENT_ERROR` | 4xx response |
|
|
365
|
+
| `HTTP_REQUEST_SERVER_ERROR` | 5xx response |
|
|
366
|
+
| `HTTP_REQUEST_ABORTED` | Connection closed before the response was delivered |
|
|
367
|
+
| `HTTP_EXCEPTION_HANDLED` | `HttpException` below 500, or a thrown value that exposes a 4xx status, caught by the filter (`warn`) |
|
|
368
|
+
| `HTTP_EXCEPTION_UNHANDLED` | `HttpException` of 500 or more, or any other thrown value, caught by the filter (`error`) |
|
|
369
|
+
|
|
370
|
+
The levels are `info` for `HTTP_REQUEST_START`, `HTTP_REQUEST_SUCCESS` and `HTTP_REQUEST_REDIRECT`, `warn` for `HTTP_REQUEST_CLIENT_ERROR` and `HTTP_REQUEST_ABORTED`, and `error` for `HTTP_REQUEST_SERVER_ERROR`. A terminal entry carries `method`, `url`, `statusCode` and `duration`; a 4xx that threw adds `errorMessage`, and a 5xx the handler did not throw is logged with a synthesized `Error`. The exception entries carry `method`, `url` and `status`, and `bodyParserType` for a body that did not parse.
|
|
350
371
|
|
|
351
372
|
`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`.
|
|
352
373
|
|
|
353
374
|
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 path segment that looks like a credential (a long hex value, a JWT, an opaque token, an email address, or a dotted token such as `ya29.…` or `v4.local.…` of which any dot-separated part is a long opaque token) is written as `:redacted` in `url`, `fullUrl` and the not-found message, and `http.secretPathSegments` adds your own patterns. `fullUrl` is the raw path without its query and with those segments replaced, not the request as received. A long camelCase or Pascal-case name cannot be told from a token and is replaced too. A secret the rules cannot see, such as `;jsessionid=...` in a segment, stays in `url`, and the message of a 5xx error is the application's own text, which is not scrubbed.
|
|
354
375
|
|
|
355
|
-
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.
|
|
376
|
+
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. While `HttpExceptionFilter` is registered it also writes the response: an `HttpException` keeps its own body, a thrown value that exposes a 4xx status becomes `{ statusCode, message }`, and any other error becomes `500 { statusCode: 500, message: 'Internal server error' }`; the application owns the response only when it registers no such filter. 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.
|
|
356
377
|
|
|
357
378
|
> [!IMPORTANT]
|
|
358
379
|
> **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.
|
|
@@ -516,7 +537,7 @@ BymaxLoggerModule.forRoot({
|
|
|
516
537
|
|
|
517
538
|
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.
|
|
518
539
|
|
|
519
|
-
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.
|
|
540
|
+
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. `service.name` and `service.version` are required and a blank one is refused at startup, so `OTEL_SERVICE_NAME` and the name and version in `OTEL_RESOURCE_ATTRIBUTES` never apply to them in practice; `OTEL_RESOURCE_ATTRIBUTES` fills the optional fields (`namespace`, `instanceId`, `environment`) and keep the logs in step with the SDK when a value is given there too.
|
|
520
541
|
|
|
521
542
|
> [!IMPORTANT]
|
|
522
543
|
> **`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.
|
|
@@ -557,6 +578,8 @@ An error's own enumerable properties (`code`, `statusCode`, domain fields) trave
|
|
|
557
578
|
- `'all'` (the default in 1.x) writes every own field as above.
|
|
558
579
|
- `'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.
|
|
559
580
|
|
|
581
|
+
The `name` of an error is written as `type` (and as `exception.type` and `error.type`) and opens its stack. A name that is identifier-shaped and at most 64 characters (`TypeError`, `pg.DatabaseError`, `E_TIMEOUT`) is kept; any other passes the censor of the `message` of an entry, so a name that is text is hidden when `message` is. A value written as a short identifier in a name is not found by its shape: put it in a field whose name `redactPaths` covers. A name longer than 16,384 characters is cut to that length, and the first line of `err.stack` keeps those 16,384 characters as written, so such a name is not hidden there.
|
|
582
|
+
|
|
560
583
|
```typescript
|
|
561
584
|
BymaxLoggerModule.forRoot({
|
|
562
585
|
service: { name: 'api', version: '1.0.0' },
|
|
@@ -611,11 +634,15 @@ function assertValidLogKey(key: string) {
|
|
|
611
634
|
}
|
|
612
635
|
```
|
|
613
636
|
|
|
637
|
+
The regex accepts `A-Z`, `0-9` and `_`, starts with a letter, and needs an underscore followed by a letter with at least two characters before it and one after (`AB_CD` and `USER_AUTH_FAILED` pass, `A_B` and `ab_cd` do not). It does not count words, so `PAY__FAIL` passes too. The library does not check the `logKey` you pass at run time, so enforce the convention in CI with this regex.
|
|
638
|
+
|
|
614
639
|
### Reserved keys
|
|
615
640
|
|
|
616
641
|
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`.
|
|
617
642
|
|
|
618
|
-
`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`
|
|
643
|
+
`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_DESTINATION_SHUTDOWN_FAILED` · `LOGGER_ENTRY_TRUNCATED` · `LOGGER_REDACTION_FAILED` · `LOGGER_OTEL_API_BROKEN`
|
|
644
|
+
|
|
645
|
+
`LOGGER_BOOTSTRAP_OK` (`info`) is written once, after every destination finished `onInit` and `onRegistryReady`. `LOGGER_SHUTDOWN_OK` (`info`, field `destinations`) is written when shutdown starts, before any `onShutdown`; its absence from a stream means the process was killed rather than shut down.
|
|
619
646
|
|
|
620
647
|
`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.
|
|
621
648
|
|
|
@@ -720,7 +747,7 @@ A sink you supply may be the only one the application has, so two guarantees cov
|
|
|
720
747
|
|
|
721
748
|
### Choosing how the dev terminal renders
|
|
722
749
|
|
|
723
|
-
`PrettyDevDestination`
|
|
750
|
+
`PrettyDevDestination` buffers up to 1000 entries or 4 MiB before `onInit` finished (whichever comes first) and writes raw NDJSON past either, and its constructor takes `{ minLevel?, view? }`.
|
|
724
751
|
|
|
725
752
|
```typescript
|
|
726
753
|
// One line per entry, with the fields your project repeats on every line hidden.
|
|
@@ -796,6 +823,41 @@ Providers are singletons: `AsyncLocalStorage` delivers per-request context witho
|
|
|
796
823
|
|
|
797
824
|
---
|
|
798
825
|
|
|
826
|
+
## 📊 Metrics and health
|
|
827
|
+
|
|
828
|
+
The `@bymax-one/nest-logger/observability` subpath publishes what the logger counts as Prometheus counters and as a readiness check, for an application that runs `@bymax-one/nest-core`. It needs the optional peers `@bymax-one/nest-core` and `prom-client`; the main entry imports neither, and nothing is created unless you import the subpath.
|
|
829
|
+
|
|
830
|
+
```typescript
|
|
831
|
+
import { Module } from '@nestjs/common'
|
|
832
|
+
import { BymaxLoggerModule } from '@bymax-one/nest-logger'
|
|
833
|
+
import { BymaxLoggerObservabilityModule } from '@bymax-one/nest-logger/observability'
|
|
834
|
+
|
|
835
|
+
@Module({
|
|
836
|
+
imports: [
|
|
837
|
+
BymaxLoggerModule.forRoot({ service: { name: 'api', version: '1.0.0' } }),
|
|
838
|
+
BymaxLoggerObservabilityModule
|
|
839
|
+
]
|
|
840
|
+
})
|
|
841
|
+
export class AppModule {}
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
`BymaxLoggerObservabilityModule` provides `LoggerMetricsContributor` and `LoggerHealthIndicator`, which `@bymax-one/nest-core` finds by their markers: the contributor is called once at bootstrap with the registry the scrape endpoint serves, and the indicator is listed in the readiness response under the name `logger` (`LOGGER_HEALTH_INDICATOR_NAME`). With `isGlobal: false` on `BymaxLoggerModule` the token is visible only to the modules that import it, so do not import `BymaxLoggerObservabilityModule`: list `LoggerMetricsContributor` and `LoggerHealthIndicator` in the `providers` of a module of yours that imports the same `forRoot` result.
|
|
845
|
+
|
|
846
|
+
### Metrics
|
|
847
|
+
|
|
848
|
+
| Name | Type | Labels | Meaning |
|
|
849
|
+
| --------------------------------------- | ------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
850
|
+
| `bymax_logger_entries_truncated_total` | counter | `reason`: `max_entry_size`, `max_string_length` | Fields of a log entry cut or replaced for a size bound; one field counts once (see `truncatedTotal`) |
|
|
851
|
+
| `bymax_logger_destination_errors_total` | counter | none | Writes to a log destination that threw or rejected; an entry dropped for want of queue room is not one |
|
|
852
|
+
|
|
853
|
+
The counters read the logger's own counts at scrape time, so a log call costs no more than before and each scrape adds the growth since the previous one. Both `reason` series exist from the first scrape, at zero. The label values are a closed set; no destination name, field name or message is ever a label.
|
|
854
|
+
|
|
855
|
+
### Health
|
|
856
|
+
|
|
857
|
+
`LoggerHealthIndicator` is `up` when at least one log destination finished its `onInit` healthy, so an entry can still be delivered, and `down` when none did, which is also the state before the first has finished. Its details carry counts only: `destinations`, `failedInit` and `writeFailing`. The check reads the state the logger already keeps; it sends nothing to a destination and cannot wait on one. It reports `down` and leaves what the readiness response does with that to `@bymax-one/nest-core`. It needs `LOGGER_OBSERVABILITY_TOKEN`, so `BymaxLoggerModule` must be resolvable from the module that provides it; if it is not, Nest fails at startup on the unresolved dependency.
|
|
858
|
+
|
|
859
|
+
---
|
|
860
|
+
|
|
799
861
|
## 🔐 Security Model
|
|
800
862
|
|
|
801
863
|
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.
|
|
@@ -869,7 +931,7 @@ The OTel mixin passes the active span's identifiers through `isValidTraceId` / `
|
|
|
869
931
|
|
|
870
932
|
### Destination failures are contained
|
|
871
933
|
|
|
872
|
-
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. The line is written for the first failure and then at most once every 10 seconds per destination, with `suppressed` counting the failures it stands in for, and shutdown says how many writes the destination failed in total when it failed more than one. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
|
|
934
|
+
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. The line is written for the first failure and then at most once every 10 seconds per destination, with `suppressed` counting the failures it stands in for, and shutdown says how many writes the destination failed in total when it failed more than one. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot. One whose `onShutdown()` fails is reported as `LOGGER_DESTINATION_SHUTDOWN_FAILED`, and the teardown of the others goes on. These lines are library text: the destination is in the `destination` field and never in `msg`, and the error is in `err` (its type and message, never its stack), where the message passes the censor of the message of an entry (`redactPaths`, `redactCensor`), so a credential in the address a destination could not reach is not written.
|
|
873
935
|
|
|
874
936
|
### What redaction covers, and what it cannot
|
|
875
937
|
|
|
@@ -908,13 +970,13 @@ An interpolated value has no name, so no configuration can redact it. **A value
|
|
|
908
970
|
|
|
909
971
|
### Bounded field size
|
|
910
972
|
|
|
911
|
-
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`.
|
|
973
|
+
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`. A reference back to an ancestor and a `BigInt` are measured as they are written, and a sub-object that is shared by several parents is measured once for each reference, as Pino writes it, so do not log a graph in which large sub-objects are shared widely; an output that cannot be read at all (a `toJSON` or a getter that throws) is written as `{ _redactionFailed: true, _logKey: 'LOGGER_REDACTION_FAILED' }`. With `errorFormat: 'semconv'` or `'both'`, each derived `exception.type`, `exception.message`, `exception.stacktrace` and `error.type` is cut to `maxEntrySizeBytes` UTF-8 bytes as well, ending in `…[truncated]` (omitted under a 14-byte ceiling), on top of the 16 KiB text cap.
|
|
912
974
|
|
|
913
975
|
### Bounded string length
|
|
914
976
|
|
|
915
|
-
`maxEntrySizeBytes` bounds what a serializer returns, and a string under a metadata key is the caller's own data, written as given. `maxStringLength` bounds that string too, and is off until set. A string longer than the limit is cut to that many characters (UTF-16 units, so a cut never splits a surrogate pair) and ends with `…[truncated]`; what is written is the limit plus 12 characters at most, and a string of exactly the limit is written whole.
|
|
977
|
+
`maxEntrySizeBytes` bounds what a serializer returns and the derived exception fields, and a string under a metadata key is the caller's own data, written as given. `maxStringLength` bounds that string too, and is off until set. A string longer than the limit is cut to that many characters (UTF-16 units, so a cut never splits a surrogate pair) and ends with `…[truncated]`; what is written is the limit plus 12 characters at most, and a string of exactly the limit is written whole.
|
|
916
978
|
|
|
917
|
-
It applies to every string value of the record at any depth, in an object or an array, after redaction: a value a redaction rule censors is the censor and not a cut text. It does not apply to a key, to a value that is not text, to the log message (already capped at 16384 characters), to the `logKey` of the entry (an identifier, and `event.name` is derived from it), to the bindings of a logger (the service identity and the `context` of an `@InjectLogger` logger are written once, whole), to anything under a key that has a serializer (`err` and the keys of `serializers`): this limit does not cut the error you log under `err`, and `maxEntrySizeBytes` caps what a serializer returns when that output serializes to JSON. The event name and the `exception.type`, `exception.message`, `exception.stacktrace` and `error.type` fields written from an error are added after the cut, so the limit does not apply to them, and the exception fields among them
|
|
979
|
+
It applies to every string value of the record at any depth, in an object or an array, after redaction: a value a redaction rule censors is the censor and not a cut text. It does not apply to a key, to a value that is not text, to the log message (already capped at 16384 characters), to the `logKey` of the entry (an identifier, and `event.name` is derived from it), to the bindings of a logger (the service identity and the `context` of an `@InjectLogger` logger are written once, whole), to anything under a key that has a serializer (`err` and the keys of `serializers`): this limit does not cut the error you log under `err`, and `maxEntrySizeBytes` caps what a serializer returns when that output serializes to JSON. The event name and the `exception.type`, `exception.message`, `exception.stacktrace` and `error.type` fields written from an error are added after the cut, so the limit does not apply to them, and the exception fields among them are cut by `maxEntrySizeBytes` (in UTF-8 bytes) and by the cap of 16384 characters, and a key of your own with one of those names is cut like any other string. The names left whole are matched on the root key, so a key of your own named like a key of `serializers` is left whole too. An `Error` placed in the metadata under any other key is data of the record when the cut runs, so its message, its stack and its own fields are cut like any other string. The limit is an integer from 64, because the strings the library writes into a record itself (trace and span ids) are shorter than that. A string the caller supplies, such as a `userId`, a `tenantId`, or a `requestId` taken from an inbound request header, is cut like any other when it is longer than the limit. Setting it makes the record walk run even when no field name is covered (`shouldDisableDefaultRedact: true` and no `redactPaths`), and the walk writes a boxed `String` or `Number`, a `Buffer`, a `Uint8Array` and an `Error` in the metadata as the default redaction already does: a two-byte `Buffer` is written as `[Binary 2 bytes]` and not as `{"type":"Buffer","data":[104,105]}`, while a boxed `Number` is written as `{}` and a boxed `String` as a map of its indexes (`{"0":"a","1":"b","2":"c"}` for `new String('abc')`), as the default redaction writes them. A `redactCensor` longer than the limit is refused at startup, because a censor the cut shortened would no longer be the text you look for in place of a secret.
|
|
918
980
|
|
|
919
981
|
### Security Checklist
|
|
920
982
|
|
|
@@ -991,7 +1053,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
991
1053
|
| `warnStructured` | `(logKey, msg, userId?, meta?)` | Structured warn log — takes a **message string** |
|
|
992
1054
|
| `errorStructured` | `(logKey, error, userId?, meta?)` | Structured error log — takes an **`Error`**, serialized to `err` |
|
|
993
1055
|
|
|
994
|
-
`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), `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` are written by the logger itself and are dropped from `meta`, and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field. A key the logger writes from the request context or from the active span (`requestId`, `tenantId`, the trace fields) keeps the logger's value when the payload carries the same key, for `meta`, an object message and the raw Pino logger alike, except `userId`, which a call names as an argument and which wins over the one of the request context; a key the logger does not write, such as a `requestId` outside a request, keeps the payload's own value. The raw Pino logger from `getRawLogger()` bypasses the owned-key guards of `meta` and of an object message, so a payload can still repeat `level`, `service` or `userId` there; the request and trace keys still win, and redaction still applies.
|
|
1056
|
+
`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), `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` are written by the logger itself and are dropped from `meta`, and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field. A key the logger writes from the request context or from the active span (`requestId`, `tenantId`, the trace fields) keeps the logger's value when the payload carries the same key, for `meta`, an object message and the raw Pino logger alike, except `userId`, which a call names as an argument and which wins over the one of the request context; a key the logger does not write, such as a `requestId` outside a request, keeps the payload's own value. A key that only spells one of these keys, or an owned key, is dropped like the key itself (`Level`, `log_key`, `trace_id` for `traceId`, `request.id` for `requestId`): names are compared with the case, the separators `_`, `.` and `-`, white space and the characters that print as nothing folded, the compatibility forms Unicode defines read as the letter they stand for, and a short list of Cyrillic and Greek letters drawn like a Latin one read as it (`trace id`, `trace\u200bId`, `RequestId`, `rеquestId`), and `service_name`, `service-version` and the other spellings of the dotted resource keys are the keys themselves (a key such as `service_tier`, which spells none of them, is yours), so a backend that normalises names cannot read the payload's copy as the logger's field. A lookalike letter that is not on the list is kept: the list is not every lookalike Unicode has. The raw Pino logger from `getRawLogger()` bypasses the owned-key guards of `meta` and of an object message, so a payload can still repeat `level`, `service` or `userId` there; the request and trace keys still win, and redaction still applies.
|
|
995
1057
|
|
|
996
1058
|
**NestJS `LoggerService` bridge** — the variadic contract NestJS calls, so `app.useLogger()` works. These take a message, not a log key.
|
|
997
1059
|
|
|
@@ -1004,15 +1066,16 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
1004
1066
|
| `fatal` | `(message, ...optionalParams)` | → Pino `fatal` |
|
|
1005
1067
|
| `error` | `(message \| Error, stack?, context?)` | An `Error` routes to the serialized `err` path |
|
|
1006
1068
|
|
|
1007
|
-
**An object as the message.** A plain object (an object literal or a parsed JSON object) passed as the message of `log`, `warn`, `error`, `debug`, `verbose` or `fatal` is written as the fields of the entry, through the same redaction and `maxStringLength` pipeline as any other field, so `this.logger.warn({ event: 'QUEUE_DRAINED', jobs: 7, password })` gives an entry with `event`, `jobs` and a censored `password`. The entry text (`msg`) is its `message` string, else its `event` string, else empty; a `message` that is the text is not repeated as a field. `logKey`, `userId`, `context`, `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` in the object are dropped, as they are from `meta`. The text is censored under the names of the field it came from (`event` or `message`), also with `redactStrategy: 'paths'`, and cut at `maxStringLength` like that field, within the 16 KiB cap that bounds every log message. A serializer keyed `event` or `message` shapes the field and not `msg`; redaction by name is what covers the text. An `Error`, and an object shaped like one (a string `name` and a string `message`), keep their own error-only path, and a value that is not plain (a class instance, an array) is still written as its string form.
|
|
1069
|
+
**An object as the message.** A plain object (an object literal or a parsed JSON object) passed as the message of `log`, `warn`, `error`, `debug`, `verbose` or `fatal` is written as the fields of the entry, through the same redaction and `maxStringLength` pipeline as any other field, so `this.logger.warn({ event: 'QUEUE_DRAINED', jobs: 7, password })` gives an entry with `event`, `jobs` and a censored `password`. The entry text (`msg`) is its `message` string, else its `event` string, else empty; a `message` that is the text is not repeated as a field. `logKey`, `userId`, `context`, `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` in the object are dropped, as they are from `meta`. The text is censored under the names of the field it came from (`event` or `message`), also with `redactStrategy: 'paths'`, and cut at `maxStringLength` like that field, within the 16 KiB cap that bounds every log message. A serializer keyed `event` or `message` shapes the field and not `msg`; redaction by name is what covers the text. An `Error`, and an object shaped like one (a string `name` and a string `message`), keep their own error-only path (the text of the entry is the `message`, censored under the name `message` as `err.message` is, and the same text is censored where it opens `err.stack`, the stack of each cause and `exception.stacktrace`, and in `exception.message`; like every log message it is capped at 16 KiB and not cut at `maxStringLength`), and a value that is not plain (a class instance, an array) is still written as its string form. Redaction works on field names and never reads the content of a string, so a text a caller passes as a string, such as ``logger.warn(`card ${number}`)``, is written as it is.
|
|
1008
1070
|
|
|
1009
1071
|
**Helpers**
|
|
1010
1072
|
|
|
1011
|
-
| Method
|
|
1012
|
-
|
|
|
1013
|
-
| `child`
|
|
1014
|
-
| `setContext`
|
|
1015
|
-
| `getRawLogger`
|
|
1073
|
+
| Method | Signature | Notes |
|
|
1074
|
+
| ------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1075
|
+
| `child` | `(bindings)` | New `PinoLoggerService` over a Pino child logger |
|
|
1076
|
+
| `setContext` | `(context)` | Global label — ⚠️ singleton; prefer `@InjectLogger(MyClass.name)` |
|
|
1077
|
+
| `getRawLogger` | `()` | The underlying Pino instance; bypasses the `meta` guards above |
|
|
1078
|
+
| `censorMessageText` | `(text)` | The text with the censor of the `message` of an entry applied (`redactPaths`, `redactCensor`); use it before writing a free-text error to a channel the library does not own |
|
|
1016
1079
|
|
|
1017
1080
|
> [!NOTE]
|
|
1018
1081
|
> There is no `fatalStructured` / `debugStructured`. Structured `fatal` and `debug` helpers are out of scope until a consumer needs them; use `getRawLogger()` in the meantime.
|
|
@@ -1031,26 +1094,58 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
1031
1094
|
|
|
1032
1095
|
### Decorators
|
|
1033
1096
|
|
|
1034
|
-
| Decorator | Target | Description
|
|
1035
|
-
| ------------------------------- | ----------------- |
|
|
1036
|
-
| `@InjectLogger(context?)` | Constructor param | Injects `PinoLoggerService` pre-bound to the given context string
|
|
1037
|
-
| `@LogContext(name)` | Class | **Deprecated.** Records a context label as class metadata that nothing in this package reads, so the label is never applied, and it does NOT open a `logContext.run()` scope. Use `@InjectLogger(MyClass.name)` for a per-class label
|
|
1038
|
-
| `@LogPerformance(thresholdMs?)` | Method | Logs `METHOD_EXECUTION` on completion; `METHOD_SLOW_EXECUTION` if duration
|
|
1097
|
+
| Decorator | Target | Description |
|
|
1098
|
+
| ------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1099
|
+
| `@InjectLogger(context?)` | Constructor param | Injects `PinoLoggerService` pre-bound to the given context string |
|
|
1100
|
+
| `@LogContext(name)` | Class | **Deprecated.** Records a context label as class metadata that nothing in this package reads, so the label is never applied, and it does NOT open a `logContext.run()` scope. Use `@InjectLogger(MyClass.name)` for a per-class label |
|
|
1101
|
+
| `@LogPerformance(thresholdMs?)` | Method | Logs `METHOD_EXECUTION` (`info`, fields `method` and `duration`) on completion; `METHOD_SLOW_EXECUTION` (`warn`, plus `thresholdMs`) if the duration is strictly greater than the threshold (1000 ms by default); the wrapped method always returns a `Promise`, so apply it to async methods. The threshold must be a finite number of zero or more (a `TypeError` at class definition otherwise) |
|
|
1039
1102
|
|
|
1040
1103
|
### Injection tokens and helpers
|
|
1041
1104
|
|
|
1042
|
-
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.
|
|
1043
|
-
|
|
1044
|
-
| Export | Provides
|
|
1045
|
-
| ---------------------------- |
|
|
1046
|
-
| `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions`
|
|
1047
|
-
| `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance
|
|
1048
|
-
| `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]`
|
|
1049
|
-
| `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
|
|
1050
|
-
| `
|
|
1051
|
-
| `
|
|
1052
|
-
| `
|
|
1053
|
-
| `
|
|
1105
|
+
Every token is a `Symbol`, never a string, so it cannot collide with one of yours; `LOGGER_OBSERVABILITY_TOKEN` is registered in the global symbol registry (`Symbol.for`), so a host that loads the package through ESM and CommonJS at once holds one token, and it collides only with a symbol registered under the identical description. Inject with an explicit `@Inject(TOKEN)`: the package is built without decorator metadata, and so is any consumer built the same way.
|
|
1106
|
+
|
|
1107
|
+
| Export | Provides | Use it to |
|
|
1108
|
+
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1109
|
+
| `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions` | read the effective configuration, defaults applied |
|
|
1110
|
+
| `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance | hand it to a library that wants a Pino logger |
|
|
1111
|
+
| `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]` | inspect what is registered; do not mutate it |
|
|
1112
|
+
| `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'`. |
|
|
1113
|
+
| `LOGGER_OBSERVABILITY_TOKEN` | the `ILoggerObservability` view of the logger: its counters and the delivery state (see below). Use it to read the counters and `deliveryState()` of the running logger, for a metric or health check of your own. |
|
|
1114
|
+
| `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class) | inject the context by token |
|
|
1115
|
+
| `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth | extend the defaults by reference instead of copying the list |
|
|
1116
|
+
| `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names | only with `redactStrategy: 'paths'` |
|
|
1117
|
+
| `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 |
|
|
1118
|
+
|
|
1119
|
+
### Application helpers
|
|
1120
|
+
|
|
1121
|
+
| Helper | When to call it | Throws or stays silent |
|
|
1122
|
+
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1123
|
+
| `BymaxLoggerModule.useNestLogger(app)` | right after `NestFactory.create(AppModule, { bufferLogs: true })`; it calls `app.useLogger(logger)` and then `app.flushLogs()` | throws `[BymaxLoggerModule] useNestLogger(app) called but BymaxLoggerModule was not imported`, with the original error as `cause` |
|
|
1124
|
+
| `BymaxLoggerModule.useRequestContext(app)` | before `app.init()`, when only the correlation scope is wanted | mounts the scope alone, with no access log |
|
|
1125
|
+
| `applyAccessLog(app)` | before `app.init()` (or before `app.listen()` when `init()` is not called by you); it mounts the correlation scope and the access log together, ahead of the body parser | throws when the module was not imported. With `http.isEnabled` off it still opens the scope and writes no access entries. A mount after `init()` is not rejected: it mounts behind the parser and a request the parser refuses goes unlogged, with no error |
|
|
1126
|
+
| `applyRequestIdMiddleware(consumer)` | in `configure(consumer)` of a module | mounts the request-id scope and the access log through the Nest middleware consumer |
|
|
1127
|
+
|
|
1128
|
+
### Option and context types (from `@bymax-one/nest-logger`)
|
|
1129
|
+
|
|
1130
|
+
| Type | What it is |
|
|
1131
|
+
| ------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
1132
|
+
| `BymaxLoggerModuleOptions` | the options of `forRoot` (the Configuration tables above) |
|
|
1133
|
+
| `BymaxLoggerModuleAsyncOptions` | the options of `forRootAsync`: a factory, a class or an existing provider that returns them |
|
|
1134
|
+
| `HttpOptions`, `OtelOptions` | the `http` and `otel` groups of the options |
|
|
1135
|
+
| `ErrorOwnFieldsMode` | `'all' \| 'safe'`, the values of `errorOwnFields` |
|
|
1136
|
+
| `LogContextBag` | the store of a request scope: `requestId`, `tenantId`, `userId`, `traceId`, `spanId` and any key of your own |
|
|
1137
|
+
| `IncomingHeaders` | the raw inbound headers an HTTP layer delivers: `Record<string, string \| string[] \| undefined>` |
|
|
1138
|
+
| `LOG_CONTEXT_METADATA_KEY` | the reflect-metadata key under which the deprecated `@LogContext` stores its label |
|
|
1139
|
+
|
|
1140
|
+
### Counters and delivery state (from `@bymax-one/nest-logger`)
|
|
1141
|
+
|
|
1142
|
+
The logger counts what it cuts and what its destinations refuse, and exposes the counts with the state of the fan-out through `LOGGER_OBSERVABILITY_TOKEN`, typed `ILoggerObservability`. Nothing is sent to a destination to read them, and the counts start at zero when the module starts.
|
|
1143
|
+
|
|
1144
|
+
| Method | Returns | What it is |
|
|
1145
|
+
| ------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1146
|
+
| `truncatedTotal(reason)` | `number` | the fields cut or replaced for a size bound, one cut counting once; the text of an object message is the entry's `msg` field, so an `event` is cut twice, as a field and as `msg`. `TruncationReason` is `'max_entry_size'` (a serializer output over `maxEntrySizeBytes` or one that cannot be measured, or a derived `exception.*` field cut to it) or `'max_string_length'` (a string cut at `maxStringLength`, the text of an object message among them) |
|
|
1147
|
+
| `destinationErrorTotal()` | `number` | the writes the destinations refused (they threw or rejected), over all destinations; an entry dropped for want of queue room is not counted here |
|
|
1148
|
+
| `deliveryState()` | `DeliveryState` | `destinations` that finished their `onInit`, how many of them `failedInit`, how many are `writeFailing` (refused a write or had an entry dropped), and whether `hasHealthySink`: at least one destination is healthy |
|
|
1054
1149
|
|
|
1055
1150
|
### Level maps (from `@bymax-one/nest-logger`)
|
|
1056
1151
|
|
|
@@ -1111,6 +1206,8 @@ type LogEntry = {
|
|
|
1111
1206
|
}
|
|
1112
1207
|
```
|
|
1113
1208
|
|
|
1209
|
+
`ReservedLogKey` (also from `/shared`) is the union of every value of `RESERVED_LOG_KEYS`, for constraining a log-key argument.
|
|
1210
|
+
|
|
1114
1211
|
Under `resourceFormat: 'flat'` there is no `service` object: the values arrive as dotted top-level keys (`"service.instance.id"`), which the index signature admits.
|
|
1115
1212
|
|
|
1116
1213
|
### `ILogDestination`
|
|
@@ -1156,15 +1253,17 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
|
|
|
1156
1253
|
|
|
1157
1254
|
### Log keys
|
|
1158
1255
|
|
|
1159
|
-
| Code
|
|
1160
|
-
|
|
|
1161
|
-
| `LOGGER_DESTINATION_INIT_FAILED`
|
|
1162
|
-
| `
|
|
1163
|
-
| `
|
|
1164
|
-
| `
|
|
1165
|
-
| `
|
|
1166
|
-
| `
|
|
1167
|
-
| `
|
|
1256
|
+
| Code | Surfaces as | When | Action |
|
|
1257
|
+
| ------------------------------------ | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
1258
|
+
| `LOGGER_DESTINATION_INIT_FAILED` | NDJSON line on `stderr` | `destination.onInit()` throws or rejects, or `destination.onRegistryReady()` throws, rejects or exceeds `destinationHookTimeoutMs` (a destination whose `onInit` succeeded keeps receiving entries) | Sink is removed from the write fan-out and shutdown; boot continues |
|
|
1259
|
+
| `LOGGER_DESTINATION_SHUTDOWN_FAILED` | NDJSON line on `stderr` | `destination.onShutdown()` throws, rejects or does not settle within the shutdown budget | The teardown of the other destinations goes on; anything the sink still held is lost |
|
|
1260
|
+
| `LOGGER_DESTINATION_WRITE_FAILED` | NDJSON line on `stderr` | `destination.write()` throws or rejects | Entry dropped for that destination; others continue |
|
|
1261
|
+
| `HTTP_UNEXPECTED_ERROR_DROPPED` | NDJSON line on `stderr` | `PinoUnexpectedErrorSink` could not log a report (the logger threw, or the report could not be read) | The report is dropped; the line names why. The response is unaffected |
|
|
1262
|
+
| `LOGGER_OTEL_API_BROKEN` | NDJSON line on `stderr`, once | `@opentelemetry/api` is installed but throws while loading, or exports no usable `trace` namespace | Reinstall it, or turn `otel.shouldAutoInjectTraceContext` off; until then `traceId` and `spanId` are absent |
|
|
1263
|
+
| `LOGGER_BOOTSTRAP_WARNING` | log entry with `reason: 'OTEL_API_UNAVAILABLE'` | `otel.shouldAutoInjectTraceContext` is on and `@opentelemetry/api` cannot be resolved | Install `@opentelemetry/api`, or turn the option off; until then `traceId` and `spanId` are absent |
|
|
1264
|
+
| `LOGGER_BOOTSTRAP_WARNING` | log entry (`warn`) with `shouldDisableDefaultRedact: true` and `redactPathCount` | `shouldDisableDefaultRedact` is on | None; the entry exists so a security review can audit it |
|
|
1265
|
+
| `LOGGER_ENTRY_TRUNCATED` | `_logKey` in the envelope | a serialized field exceeds `maxEntrySizeBytes` | Reduce the payload or raise the ceiling |
|
|
1266
|
+
| `LOGGER_REDACTION_FAILED` | `_logKey` in the envelope, with `_redactionFailed: true` | a record cannot be walked by the redactor (a throwing getter, a hostile proxy in the metadata) | The record is dropped whole, never partly emitted; the message and ambient context stay. Find the value that broke the walk |
|
|
1168
1267
|
|
|
1169
1268
|
---
|
|
1170
1269
|
|
|
@@ -1187,6 +1286,7 @@ Measured by this repository's own benchmark (`pnpm bench`, see [bench/README.md]
|
|
|
1187
1286
|
|
|
1188
1287
|
- **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.
|
|
1189
1288
|
- The legacy `redactStrategy: 'paths'` is about seventy times slower in the same bench run, and its cost grows with the number of default paths.
|
|
1289
|
+
- One call through the shipped configuration, for an entry of four fields (the median of five runs of 200,000 calls, three runs on one machine under Node 24 that was not idle): a string line about 1.2 µs, a structured call with `meta` about 3.9 µs, and an object message between 3.3 and 3.8 µs. That is about 2.8 to 3.1 times the string line, and the same work as `meta`: an object message is a structured call, so the cost is the fields and not the form. The ratio depends on how cheap the string line is on the machine, so compare your own runs of both. Comparing the names of a payload with the keys the logger owns and writes adds a small cost to each structured call and each object message.
|
|
1190
1290
|
|
|
1191
1291
|
Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
|
|
1192
1292
|
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var common = require('@nestjs/common');
|
|
4
|
+
var health = require('@bymax-one/nest-core/health');
|
|
5
|
+
var nestLogger = require('@bymax-one/nest-logger');
|
|
6
|
+
var metrics = require('@bymax-one/nest-core/metrics');
|
|
7
|
+
var promClient = require('prom-client');
|
|
8
|
+
|
|
9
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
10
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
11
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
12
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
13
|
+
if (decorator = decorators[i])
|
|
14
|
+
result = (decorator(result)) || result;
|
|
15
|
+
return result;
|
|
16
|
+
};
|
|
17
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
18
|
+
var LOGGER_HEALTH_INDICATOR_NAME = "logger";
|
|
19
|
+
exports.LoggerHealthIndicator = class LoggerHealthIndicator {
|
|
20
|
+
/**
|
|
21
|
+
* @param observability - The delivery state of the logger, provided by `BymaxLoggerModule`.
|
|
22
|
+
*/
|
|
23
|
+
constructor(observability) {
|
|
24
|
+
this.observability = observability;
|
|
25
|
+
this.name = LOGGER_HEALTH_INDICATOR_NAME;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Read the delivery state of the logger.
|
|
29
|
+
*
|
|
30
|
+
* @returns `up` or `down`, with the counts of the state as details.
|
|
31
|
+
*/
|
|
32
|
+
check() {
|
|
33
|
+
const { destinations, failedInit, writeFailing, hasHealthySink } = this.observability.deliveryState();
|
|
34
|
+
return Promise.resolve({
|
|
35
|
+
status: hasHealthySink ? "up" : "down",
|
|
36
|
+
details: { destinations, failedInit, writeFailing }
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
exports.LoggerHealthIndicator = __decorateClass([
|
|
41
|
+
health.BymaxHealthIndicator(),
|
|
42
|
+
common.Injectable(),
|
|
43
|
+
__decorateParam(0, common.Inject(nestLogger.LOGGER_OBSERVABILITY_TOKEN))
|
|
44
|
+
], exports.LoggerHealthIndicator);
|
|
45
|
+
var TRUNCATION_REASONS = ["max_entry_size", "max_string_length"];
|
|
46
|
+
function growthOf(read) {
|
|
47
|
+
let last = 0;
|
|
48
|
+
return () => {
|
|
49
|
+
const total = read();
|
|
50
|
+
const growth = total - last;
|
|
51
|
+
last = total;
|
|
52
|
+
return growth;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
exports.LoggerMetricsContributor = class LoggerMetricsContributor {
|
|
56
|
+
/**
|
|
57
|
+
* @param observability - The counts of the logger, provided by `BymaxLoggerModule`.
|
|
58
|
+
*/
|
|
59
|
+
constructor(observability) {
|
|
60
|
+
this.observability = observability;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Create the two counters on `registry`. Each `reason` series exists from the first scrape, at
|
|
64
|
+
* zero, so a rate over it never starts from a missing series.
|
|
65
|
+
*
|
|
66
|
+
* @param registry - The registry the scrape endpoint serves.
|
|
67
|
+
*/
|
|
68
|
+
registerMetrics(registry) {
|
|
69
|
+
const observability = this.observability;
|
|
70
|
+
const growth = new Map(
|
|
71
|
+
TRUNCATION_REASONS.map((reason) => [
|
|
72
|
+
reason,
|
|
73
|
+
growthOf(() => observability.truncatedTotal(reason))
|
|
74
|
+
])
|
|
75
|
+
);
|
|
76
|
+
new promClient.Counter({
|
|
77
|
+
name: "bymax_logger_entries_truncated_total",
|
|
78
|
+
help: "Fields of a log entry cut or replaced for a size bound, by reason.",
|
|
79
|
+
labelNames: ["reason"],
|
|
80
|
+
registers: [registry],
|
|
81
|
+
collect() {
|
|
82
|
+
for (const [reason, next] of growth) this.labels(reason).inc(next());
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
const errors = growthOf(() => observability.destinationErrorTotal());
|
|
86
|
+
new promClient.Counter({
|
|
87
|
+
name: "bymax_logger_destination_errors_total",
|
|
88
|
+
help: "Writes to a log destination that threw or rejected.",
|
|
89
|
+
registers: [registry],
|
|
90
|
+
collect() {
|
|
91
|
+
this.inc(errors());
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
exports.LoggerMetricsContributor = __decorateClass([
|
|
97
|
+
metrics.BymaxMetricsContributor(),
|
|
98
|
+
common.Injectable(),
|
|
99
|
+
__decorateParam(0, common.Inject(nestLogger.LOGGER_OBSERVABILITY_TOKEN))
|
|
100
|
+
], exports.LoggerMetricsContributor);
|
|
101
|
+
|
|
102
|
+
// src/observability/observability.module.ts
|
|
103
|
+
exports.BymaxLoggerObservabilityModule = class BymaxLoggerObservabilityModule {
|
|
104
|
+
};
|
|
105
|
+
exports.BymaxLoggerObservabilityModule = __decorateClass([
|
|
106
|
+
common.Module({
|
|
107
|
+
providers: [exports.LoggerMetricsContributor, exports.LoggerHealthIndicator],
|
|
108
|
+
exports: [exports.LoggerMetricsContributor, exports.LoggerHealthIndicator]
|
|
109
|
+
})
|
|
110
|
+
], exports.BymaxLoggerObservabilityModule);
|
|
111
|
+
|
|
112
|
+
exports.LOGGER_HEALTH_INDICATOR_NAME = LOGGER_HEALTH_INDICATOR_NAME;
|