@bymax-one/nest-logger 1.4.23 → 1.4.24
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 +154 -1
- package/README.md +90 -22
- 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 +340 -144
- package/dist/server/index.d.cts +82 -4
- package/dist/server/index.d.ts +82 -4
- package/dist/server/index.mjs +340 -145
- 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/CHANGELOG.md
CHANGED
|
@@ -12,6 +12,158 @@ heading here.
|
|
|
12
12
|
|
|
13
13
|
## [Unreleased]
|
|
14
14
|
|
|
15
|
+
## [1.4.24] - 2026-11-18
|
|
16
|
+
|
|
17
|
+
### Breaking
|
|
18
|
+
|
|
19
|
+
- **A key that only spells a key the logger writes is dropped, like the key itself.** 1.4.23 dropped
|
|
20
|
+
the owned keys and let the logger's value win over a payload key of the same name, but a payload key
|
|
21
|
+
that spelled one differently was written beside it: `trace_id`, `trace.id` or `TraceId` next to
|
|
22
|
+
`traceId`, `request_id` or `request.id` next to `requestId`, `Level` or `log_key` next to `level`
|
|
23
|
+
or `logKey`. A backend that normalises field names reads those as the same field, so a line could
|
|
24
|
+
still be attributed to another request or trace. The case and the separators `_`, `.` and `-` are
|
|
25
|
+
now folded when names are compared, and a spelling of an owned key is dropped from `meta` and from
|
|
26
|
+
an object message, and a spelling of a key the request context or the active span writes on that
|
|
27
|
+
call is dropped from the payload of `meta`, of an object message and of the raw Pino logger. A key
|
|
28
|
+
that is not a spelling of one (`trace_ids`, `levels`, `my_trace`) is kept, and outside a request or
|
|
29
|
+
a span, where the logger writes no such key, a `request_id` is the payload's own field. **Apply:**
|
|
30
|
+
nothing is required; search the `meta` of your calls and your object messages for a field whose
|
|
31
|
+
name, with the case and the `_`, `.` and `-` removed, is `level`, `time`, `msg`, `service`,
|
|
32
|
+
`deployment`, `logkey`, `userid` or `context`, or that starts with `service.` or `deployment.` in
|
|
33
|
+
any case (`Level`, `time_`, `log_key`, `Context`, `user_id`, `user.id`, `Service.x`): it is no
|
|
34
|
+
longer written on any call. Inside a request or a span the same holds, in `meta`, in an object
|
|
35
|
+
message and in the payload of the raw Pino logger, for the spellings of the keys the logger writes
|
|
36
|
+
there (`request_id`, `tenant_id`). Rename those fields (`severity`, `elapsedMs`,
|
|
37
|
+
`legacyRequestId`, `legacyUserId`).
|
|
38
|
+
|
|
39
|
+
- **The lines the library writes about its destinations are library text, with the error of the host
|
|
40
|
+
in `err`, and that error's message is censored.** The lines of `LOGGER_DESTINATION_WRITE_FAILED`
|
|
41
|
+
and `LOGGER_DESTINATION_INIT_FAILED` (a failed `onInit`, a failed `onRegistryReady`) put the name
|
|
42
|
+
of the destination in their `msg`, for example
|
|
43
|
+
`Log destination "audit" failed to write; the entry was dropped`. `msg` is now library text with
|
|
44
|
+
no name in it (for a write, `A log destination failed to write; the entry was dropped`) and the
|
|
45
|
+
name is in `destination` alone. A failed `onShutdown` was
|
|
46
|
+
written as a text line,
|
|
47
|
+
`[DestinationRegistry] Shutdown failed for "audit": <the stack of the error>`, which put the whole
|
|
48
|
+
stack of a host error on stderr outside any censor. It is now a JSON line like the others, under a
|
|
49
|
+
new reserved key, `LOGGER_DESTINATION_SHUTDOWN_FAILED`, with `destination`, `err` and a constant
|
|
50
|
+
`msg`, and its stack is not written. The message of the error in `err` of these lines, of
|
|
51
|
+
`HTTP_UNEXPECTED_ERROR_DROPPED` and of `LOGGER_OTEL_API_BROKEN` was bounded and escaped only; it
|
|
52
|
+
now also passes the censor of the message of an entry (`redactPaths` and `redactCensor`, under the
|
|
53
|
+
name `message`, whatever the strategy), so a credential in an address a driver could not reach is
|
|
54
|
+
no longer written. A censor that cannot answer leaves the line with an empty message. The other
|
|
55
|
+
text lines on stderr (the entries dropped for a full queue, the totals at shutdown, the spent
|
|
56
|
+
shutdown budget) carry counters and the escaped name of a destination, and are unchanged.
|
|
57
|
+
**Apply:** an alert or a search that matches the old text must match the `logKey` and the
|
|
58
|
+
`destination` field instead: `LOGGER_DESTINATION_WRITE_FAILED` and `LOGGER_DESTINATION_INIT_FAILED`
|
|
59
|
+
as before, and `LOGGER_DESTINATION_SHUTDOWN_FAILED` for a failed shutdown, which a match on
|
|
60
|
+
`Shutdown failed for` no longer finds, and a log shipper that read that line as text now receives
|
|
61
|
+
a JSON entry with `level: "error"`. The stack of the error is no longer written there: if you need
|
|
62
|
+
it, log it in your own `onShutdown`. If you list the reserved keys (a dashboard filter, an
|
|
63
|
+
allow-list), add the new one. A `message` in `redactPaths` now also hides the message of the error
|
|
64
|
+
in these lines.
|
|
65
|
+
|
|
66
|
+
### Added
|
|
67
|
+
|
|
68
|
+
- **The logger counts what it cuts and what its destinations refuse.** `LOGGER_OBSERVABILITY_TOKEN`
|
|
69
|
+
provides an `ILoggerObservability`: `truncatedTotal(reason)` (the fields cut or replaced for a size
|
|
70
|
+
bound, with `reason` of `'max_entry_size'` or `'max_string_length'`), `destinationErrorTotal()` (the
|
|
71
|
+
writes the destinations refused) and `deliveryState()` (how many destinations finished their
|
|
72
|
+
`onInit`, how many of them failed it, how many refused a write or had an entry dropped, and whether
|
|
73
|
+
one is healthy). The types `ILoggerObservability`,
|
|
74
|
+
`DeliveryState` and `TruncationReason` are exported with it. Nothing changes for a host that does
|
|
75
|
+
not read them.
|
|
76
|
+
|
|
77
|
+
- **A new `@bymax-one/nest-logger/observability` subpath publishes the counters as Prometheus
|
|
78
|
+
metrics and the delivery state as a readiness check.** `BymaxLoggerObservabilityModule` provides
|
|
79
|
+
`LoggerMetricsContributor`, which registers `bymax_logger_entries_truncated_total{reason}` (with
|
|
80
|
+
`reason` of `max_entry_size` or `max_string_length`) and `bymax_logger_destination_errors_total` on
|
|
81
|
+
the registry `@bymax-one/nest-core` serves, and `LoggerHealthIndicator`, named `logger`, which is
|
|
82
|
+
`up` while at least one destination is healthy. `@bymax-one/nest-core` (`^1.6.10`) and `prom-client`
|
|
83
|
+
(`^15`) are optional peer dependencies, imported only by this subpath; the main entry needs neither. **Apply:**
|
|
84
|
+
nothing is required; to publish the metrics, install the two peers and import
|
|
85
|
+
`BymaxLoggerObservabilityModule` next to `BymaxLoggerModule`.
|
|
86
|
+
|
|
87
|
+
#### Apply to a derived backend
|
|
88
|
+
|
|
89
|
+
Nothing is required. A derived backend that builds the Pino instance itself through
|
|
90
|
+
`buildPinoInstance` passes its `DestinationHealth`, which now counts; one that provides its own
|
|
91
|
+
`LOGGER_OBSERVABILITY_TOKEN` must return the three methods of `ILoggerObservability`.
|
|
92
|
+
|
|
93
|
+
`PinoLoggerService` gains one private member, `errorText`, and one public method,
|
|
94
|
+
`censorMessageText(text)`, in its declaration. A subclass that defines a member of either name no
|
|
95
|
+
longer compiles against it: rename yours. Nothing else about its
|
|
96
|
+
constructor or its public methods changes. A service you build by hand over a Pino instance you built
|
|
97
|
+
yourself censors the text of an `Error` with its own redactor, as it does the text of an object
|
|
98
|
+
message; over a Pino instance from `buildPinoInstance` it uses the function the factory leaves on
|
|
99
|
+
that instance, which also covers `redactStrategy: 'paths'`. The merge of the request and trace keys
|
|
100
|
+
that `buildPinoInstance` installs, and the owned-key guard of the service, now compare names with
|
|
101
|
+
their case and the separators `_`, `.` and `-` folded, and the `err` serializer and the derived
|
|
102
|
+
`exception.*` fields it builds censor the message where it opens a stack; nothing is required beyond
|
|
103
|
+
what the Breaking entry above says.
|
|
104
|
+
|
|
105
|
+
### Fixed
|
|
106
|
+
|
|
107
|
+
- **The text of an entry that comes from an `Error` is censored like `err.message`.** The text of
|
|
108
|
+
`error(err)`, `errorStructured(key, err)` and `warn(err)` (and `log`, `fatal`, `debug`, `verbose`
|
|
109
|
+
with an `Error`) is the error's `message`, and it was written as it was while the field
|
|
110
|
+
`err.message` was censored, so `redactPaths: ['message']` left the secret in `msg`. It is now
|
|
111
|
+
censored under the name `message`, also with `redactStrategy: 'paths'`. It is still capped at
|
|
112
|
+
16 KiB like every log message and not cut at `maxStringLength`, which does not apply to the log
|
|
113
|
+
message. The same text is censored where it opens the stack: in `err.stack`, in the stack of each
|
|
114
|
+
`cause` and of each of the `errors` of an `AggregateError`, and in `exception.message` and
|
|
115
|
+
`exception.stacktrace` with `errorFormat: 'semconv'` or `'both'`. It is replaced where the engine
|
|
116
|
+
writes it, right after the first `: ` of the first line (or at the start, for an error with no
|
|
117
|
+
name), by an exact comparison there, never by a search and never by a pattern built from your
|
|
118
|
+
text, so an error whose name repeats or contains its message is censored in the message and not
|
|
119
|
+
in the name, and so is a message that wraps another error with its frames. It holds for an `Error`,
|
|
120
|
+
a subclass and an `Error` of another realm, and for a message with a control character, which the
|
|
121
|
+
stack escapes. A stack whose header is not in the default form loses its frames when its message
|
|
122
|
+
is censored: it becomes its name, if any, and the censored message, as what it holds may be the
|
|
123
|
+
secret too. A stack of a message that nothing censored is not touched. **What this covers,
|
|
124
|
+
precisely:** redaction works on field names, so it covers a field and the text copied from a named
|
|
125
|
+
field (the `message` or `event` of an object message, and the `message` of an `Error` where it
|
|
126
|
+
appears as the text of the entry, in its stack and in the derived `exception.*` fields); it never
|
|
127
|
+
reads the content of a string, so a text a caller passes as a string, such as
|
|
128
|
+
``logger.warn(`card ${number}`)``, is written as it is, and a secret that an error carries in
|
|
129
|
+
another field (a `code`, an own property) is covered only by the name of that field. 1.4.23 said a
|
|
130
|
+
secret in `event` or `message` does not reach `msg`; that holds for the text of an object message
|
|
131
|
+
and, from this release, for the message of an `Error`, and for no other source of the text. **Apply:** nothing is required; a log search that relied on finding a
|
|
132
|
+
censored value in the `msg` of an `Error` no longer finds it.
|
|
133
|
+
- **The derived exception fields are bounded by `maxEntrySizeBytes`.** With `errorFormat: 'semconv'`
|
|
134
|
+
or `'both'`, `exception.type`, `exception.message`, `exception.stacktrace` and `error.type` were
|
|
135
|
+
cut only by the fixed 16 KiB text cap, so with `maxEntrySizeBytes` set below the 64 KiB default
|
|
136
|
+
each could be larger than the ceiling that bounds a serializer's output. Each
|
|
137
|
+
is now cut to `maxEntrySizeBytes` UTF-8 bytes, ending in `…[truncated]` (omitted under a 14-byte ceiling), at a character boundary.
|
|
138
|
+
**Apply:** nothing is required; a query that reads the full message or stack of a very long error
|
|
139
|
+
through these fields gets the cut text when the ceiling is lower than the error, so raise
|
|
140
|
+
`maxEntrySizeBytes` if you need more of it.
|
|
141
|
+
- **A serializer output that `JSON.stringify` cannot measure is bounded.** A value with a reference
|
|
142
|
+
back to an ancestor, or a `BigInt`, passed the size ceiling unmeasured, so a huge one reached the
|
|
143
|
+
line. It is now measured as it is written (a cycle as `"[Circular]"`, a `BigInt` by its digits) and
|
|
144
|
+
truncated when over the ceiling; a repeated reference without a cycle is counted every time it is
|
|
145
|
+
written. **Apply:** nothing is required; an alert on `LOGGER_ENTRY_TRUNCATED` now also fires for
|
|
146
|
+
these values.
|
|
147
|
+
- **A serializer that is itself `undefined` is refused with its type.** `serializers: { a: undefined }`
|
|
148
|
+
said `options.serializers must map every serializer key to a function` and no more; it now ends in
|
|
149
|
+
`Received undefined`, as the other refused members do. **Apply:** code that matches the text of
|
|
150
|
+
that refusal exactly matches the new one.
|
|
151
|
+
|
|
152
|
+
### Documentation
|
|
153
|
+
|
|
154
|
+
- **The README says what a call costs.** A string line, a structured call and an object message
|
|
155
|
+
are timed in its Performance section, with the cost of comparing the names of a payload with the
|
|
156
|
+
keys the logger writes.
|
|
157
|
+
- **The README names every export of a public subpath.** Some exports of the root entry and one of
|
|
158
|
+
`/shared` (the option and context types, the metadata key of the deprecated `@LogContext` and the
|
|
159
|
+
`ReservedLogKey` union) were never named in it; an "Option and context types" table describes
|
|
160
|
+
each, and a spec reads the barrels through the TypeScript compiler and fails when an export is
|
|
161
|
+
missing, so a new one cannot ship unnamed.
|
|
162
|
+
- **The size measurement is said to count a shared sub-object once per reference.** A sub-object that
|
|
163
|
+
several parents share is measured, and written by Pino, once for each reference, so a graph in
|
|
164
|
+
which large sub-objects are shared widely costs time and size in proportion; keep such graphs out
|
|
165
|
+
of the log.
|
|
166
|
+
|
|
15
167
|
## [1.4.23] - 2026-11-17
|
|
16
168
|
|
|
17
169
|
### Breaking
|
|
@@ -3095,7 +3247,8 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
|
|
|
3095
3247
|
- Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
|
|
3096
3248
|
`release.yml`, Dependabot, and issue templates
|
|
3097
3249
|
|
|
3098
|
-
[Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.
|
|
3250
|
+
[Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.24...HEAD
|
|
3251
|
+
[1.4.24]: https://github.com/bymaxone/nest-logger/compare/v1.4.23...v1.4.24
|
|
3099
3252
|
[1.4.23]: https://github.com/bymaxone/nest-logger/compare/v1.4.22...v1.4.23
|
|
3100
3253
|
[1.4.22]: https://github.com/bymaxone/nest-logger/compare/v1.4.21...v1.4.22
|
|
3101
3254
|
[1.4.21]: https://github.com/bymaxone/nest-logger/compare/v1.4.20...v1.4.21
|
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,6 +105,9 @@ 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]
|
|
@@ -615,7 +621,7 @@ function assertValidLogKey(key: string) {
|
|
|
615
621
|
|
|
616
622
|
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
623
|
|
|
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`
|
|
624
|
+
`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`
|
|
619
625
|
|
|
620
626
|
`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
627
|
|
|
@@ -796,6 +802,41 @@ Providers are singletons: `AsyncLocalStorage` delivers per-request context witho
|
|
|
796
802
|
|
|
797
803
|
---
|
|
798
804
|
|
|
805
|
+
## 📊 Metrics and health
|
|
806
|
+
|
|
807
|
+
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.
|
|
808
|
+
|
|
809
|
+
```typescript
|
|
810
|
+
import { Module } from '@nestjs/common'
|
|
811
|
+
import { BymaxLoggerModule } from '@bymax-one/nest-logger'
|
|
812
|
+
import { BymaxLoggerObservabilityModule } from '@bymax-one/nest-logger/observability'
|
|
813
|
+
|
|
814
|
+
@Module({
|
|
815
|
+
imports: [
|
|
816
|
+
BymaxLoggerModule.forRoot({ service: { name: 'api', version: '1.0.0' } }),
|
|
817
|
+
BymaxLoggerObservabilityModule
|
|
818
|
+
]
|
|
819
|
+
})
|
|
820
|
+
export class AppModule {}
|
|
821
|
+
```
|
|
822
|
+
|
|
823
|
+
`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.
|
|
824
|
+
|
|
825
|
+
### Metrics
|
|
826
|
+
|
|
827
|
+
| Name | Type | Labels | Meaning |
|
|
828
|
+
| --------------------------------------- | ------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
829
|
+
| `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`) |
|
|
830
|
+
| `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 |
|
|
831
|
+
|
|
832
|
+
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.
|
|
833
|
+
|
|
834
|
+
### Health
|
|
835
|
+
|
|
836
|
+
`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.
|
|
837
|
+
|
|
838
|
+
---
|
|
839
|
+
|
|
799
840
|
## 🔐 Security Model
|
|
800
841
|
|
|
801
842
|
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 +910,7 @@ The OTel mixin passes the active span's identifiers through `isValidTraceId` / `
|
|
|
869
910
|
|
|
870
911
|
### Destination failures are contained
|
|
871
912
|
|
|
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.
|
|
913
|
+
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
914
|
|
|
874
915
|
### What redaction covers, and what it cannot
|
|
875
916
|
|
|
@@ -908,13 +949,13 @@ An interpolated value has no name, so no configuration can redact it. **A value
|
|
|
908
949
|
|
|
909
950
|
### Bounded field size
|
|
910
951
|
|
|
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`.
|
|
952
|
+
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
953
|
|
|
913
954
|
### Bounded string length
|
|
914
955
|
|
|
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.
|
|
956
|
+
`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
957
|
|
|
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
|
|
958
|
+
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
959
|
|
|
919
960
|
### Security Checklist
|
|
920
961
|
|
|
@@ -991,7 +1032,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
991
1032
|
| `warnStructured` | `(logKey, msg, userId?, meta?)` | Structured warn log — takes a **message string** |
|
|
992
1033
|
| `errorStructured` | `(logKey, error, userId?, meta?)` | Structured error log — takes an **`Error`**, serialized to `err` |
|
|
993
1034
|
|
|
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.
|
|
1035
|
+
`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 and the separators `_`, `.` and `-` folded, so a backend that normalises names cannot read the payload's copy as the logger's field. 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
1036
|
|
|
996
1037
|
**NestJS `LoggerService` bridge** — the variadic contract NestJS calls, so `app.useLogger()` works. These take a message, not a log key.
|
|
997
1038
|
|
|
@@ -1004,7 +1045,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
1004
1045
|
| `fatal` | `(message, ...optionalParams)` | → Pino `fatal` |
|
|
1005
1046
|
| `error` | `(message \| Error, stack?, context?)` | An `Error` routes to the serialized `err` path |
|
|
1006
1047
|
|
|
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.
|
|
1048
|
+
**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
1049
|
|
|
1009
1050
|
**Helpers**
|
|
1010
1051
|
|
|
@@ -1039,7 +1080,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
|
|
|
1039
1080
|
|
|
1040
1081
|
### Injection tokens and helpers
|
|
1041
1082
|
|
|
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.
|
|
1083
|
+
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.
|
|
1043
1084
|
|
|
1044
1085
|
| Export | Provides | Use it to |
|
|
1045
1086
|
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -1047,11 +1088,34 @@ Every token is a `Symbol`, never a string, so it cannot collide with one of your
|
|
|
1047
1088
|
| `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance | hand it to a library that wants a Pino logger |
|
|
1048
1089
|
| `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]` | inspect what is registered; do not mutate it |
|
|
1049
1090
|
| `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'`. |
|
|
1091
|
+
| `LOGGER_OBSERVABILITY_TOKEN` | the `ILoggerObservability` view of the logger: its counters and the delivery state (see below) |
|
|
1050
1092
|
| `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class) | inject the context by token |
|
|
1051
1093
|
| `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth | extend the defaults by reference instead of copying the list |
|
|
1052
1094
|
| `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names | only with `redactStrategy: 'paths'` |
|
|
1053
1095
|
| `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 |
|
|
1054
1096
|
|
|
1097
|
+
### Option and context types (from `@bymax-one/nest-logger`)
|
|
1098
|
+
|
|
1099
|
+
| Type | What it is |
|
|
1100
|
+
| ------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
1101
|
+
| `BymaxLoggerModuleOptions` | the options of `forRoot` (the Configuration tables above) |
|
|
1102
|
+
| `BymaxLoggerModuleAsyncOptions` | the options of `forRootAsync`: a factory, a class or an existing provider that returns them |
|
|
1103
|
+
| `HttpOptions`, `OtelOptions` | the `http` and `otel` groups of the options |
|
|
1104
|
+
| `ErrorOwnFieldsMode` | `'all' \| 'safe'`, the values of `errorOwnFields` |
|
|
1105
|
+
| `LogContextBag` | the store of a request scope: `requestId`, `tenantId`, `userId`, `traceId`, `spanId` and any key of your own |
|
|
1106
|
+
| `IncomingHeaders` | the raw inbound headers an HTTP layer delivers: `Record<string, string \| string[] \| undefined>` |
|
|
1107
|
+
| `LOG_CONTEXT_METADATA_KEY` | the reflect-metadata key under which the deprecated `@LogContext` stores its label |
|
|
1108
|
+
|
|
1109
|
+
### Counters and delivery state (from `@bymax-one/nest-logger`)
|
|
1110
|
+
|
|
1111
|
+
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.
|
|
1112
|
+
|
|
1113
|
+
| Method | Returns | What it is |
|
|
1114
|
+
| ------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1115
|
+
| `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) |
|
|
1116
|
+
| `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 |
|
|
1117
|
+
| `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 |
|
|
1118
|
+
|
|
1055
1119
|
### Level maps (from `@bymax-one/nest-logger`)
|
|
1056
1120
|
|
|
1057
1121
|
`LogEntry.level` is the Pino string label, not the numeric code. A destination writing a numeric column converts with the exported maps:
|
|
@@ -1111,6 +1175,8 @@ type LogEntry = {
|
|
|
1111
1175
|
}
|
|
1112
1176
|
```
|
|
1113
1177
|
|
|
1178
|
+
`ReservedLogKey` (also from `/shared`) is the union of every value of `RESERVED_LOG_KEYS`, for constraining a log-key argument.
|
|
1179
|
+
|
|
1114
1180
|
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
1181
|
|
|
1116
1182
|
### `ILogDestination`
|
|
@@ -1156,15 +1222,16 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
|
|
|
1156
1222
|
|
|
1157
1223
|
### Log keys
|
|
1158
1224
|
|
|
1159
|
-
| Code
|
|
1160
|
-
|
|
|
1161
|
-
| `LOGGER_DESTINATION_INIT_FAILED`
|
|
1162
|
-
| `
|
|
1163
|
-
| `
|
|
1164
|
-
| `
|
|
1165
|
-
| `
|
|
1166
|
-
| `
|
|
1167
|
-
| `
|
|
1225
|
+
| Code | Surfaces as | When | Action |
|
|
1226
|
+
| ------------------------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
1227
|
+
| `LOGGER_DESTINATION_INIT_FAILED` | NDJSON line on `stderr` | `destination.onInit()` throws or rejects | Sink is removed from the write fan-out and shutdown; boot continues |
|
|
1228
|
+
| `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 |
|
|
1229
|
+
| `LOGGER_DESTINATION_WRITE_FAILED` | NDJSON line on `stderr` | `destination.write()` throws or rejects | Entry dropped for that destination; others continue |
|
|
1230
|
+
| `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 |
|
|
1231
|
+
| `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 |
|
|
1232
|
+
| `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 |
|
|
1233
|
+
| `LOGGER_ENTRY_TRUNCATED` | `_logKey` in the envelope | a serialized field exceeds `maxEntrySizeBytes` | Reduce the payload or raise the ceiling |
|
|
1234
|
+
| `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
1235
|
|
|
1169
1236
|
---
|
|
1170
1237
|
|
|
@@ -1187,6 +1254,7 @@ Measured by this repository's own benchmark (`pnpm bench`, see [bench/README.md]
|
|
|
1187
1254
|
|
|
1188
1255
|
- **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
1256
|
- The legacy `redactStrategy: 'paths'` is about seventy times slower in the same bench run, and its cost grows with the number of default paths.
|
|
1257
|
+
- One call through the shipped configuration, for an entry of four fields (the median of five runs of 300,000 calls on one machine under Node 24): a string line about 1.85 µs, a structured call with `meta` about 3.4 µs, and an object message about 3.3 µs, which is about 1.8 times the string line and costs the same work as `meta`. Comparing the names of a payload with the keys the logger owns and writes adds about 0.2 µs to a structured call and about 0.25 µs to an object message.
|
|
1190
1258
|
|
|
1191
1259
|
Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
|
|
1192
1260
|
|
|
@@ -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;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { IMetricsContributor, MetricsRegistry } from '@bymax-one/nest-core/metrics';
|
|
2
|
+
import { ILoggerObservability } from '@bymax-one/nest-logger';
|
|
3
|
+
import { IHealthIndicator, HealthIndicatorResult } from '@bymax-one/nest-core/health';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Provides {@link LoggerMetricsContributor} and {@link LoggerHealthIndicator}, which
|
|
7
|
+
* `@bymax-one/nest-core` finds by their markers. With `isGlobal: false` on `BymaxLoggerModule`,
|
|
8
|
+
* do not import this module: list both providers in a module of yours that imports the logger module.
|
|
9
|
+
*/
|
|
10
|
+
declare class BymaxLoggerObservabilityModule {
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Registers `bymax_logger_entries_truncated_total{reason}` and
|
|
15
|
+
* `bymax_logger_destination_errors_total` on the registry it is given.
|
|
16
|
+
*/
|
|
17
|
+
declare class LoggerMetricsContributor implements IMetricsContributor {
|
|
18
|
+
private readonly observability;
|
|
19
|
+
/**
|
|
20
|
+
* @param observability - The counts of the logger, provided by `BymaxLoggerModule`.
|
|
21
|
+
*/
|
|
22
|
+
constructor(observability: ILoggerObservability);
|
|
23
|
+
/**
|
|
24
|
+
* Create the two counters on `registry`. Each `reason` series exists from the first scrape, at
|
|
25
|
+
* zero, so a rate over it never starts from a missing series.
|
|
26
|
+
*
|
|
27
|
+
* @param registry - The registry the scrape endpoint serves.
|
|
28
|
+
*/
|
|
29
|
+
registerMetrics(registry: MetricsRegistry): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The name of the indicator in the readiness response. */
|
|
33
|
+
declare const LOGGER_HEALTH_INDICATOR_NAME = "logger";
|
|
34
|
+
/**
|
|
35
|
+
* `up` when at least one log destination finished its `onInit` healthy, so an entry can still be
|
|
36
|
+
* delivered; `down` when none did, which is also the state before the first has finished. The
|
|
37
|
+
* details carry counts only: how many destinations finished their init, how many failed it and how
|
|
38
|
+
* many have refused a write or had an entry dropped.
|
|
39
|
+
*/
|
|
40
|
+
declare class LoggerHealthIndicator implements IHealthIndicator {
|
|
41
|
+
private readonly observability;
|
|
42
|
+
readonly name = "logger";
|
|
43
|
+
/**
|
|
44
|
+
* @param observability - The delivery state of the logger, provided by `BymaxLoggerModule`.
|
|
45
|
+
*/
|
|
46
|
+
constructor(observability: ILoggerObservability);
|
|
47
|
+
/**
|
|
48
|
+
* Read the delivery state of the logger.
|
|
49
|
+
*
|
|
50
|
+
* @returns `up` or `down`, with the counts of the state as details.
|
|
51
|
+
*/
|
|
52
|
+
check(): Promise<HealthIndicatorResult>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export { BymaxLoggerObservabilityModule, LOGGER_HEALTH_INDICATOR_NAME, LoggerHealthIndicator, LoggerMetricsContributor };
|