@backendkit-labs/observability 0.1.0 → 0.1.1

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.
Files changed (3) hide show
  1. package/LICENSE +184 -0
  2. package/README.md +367 -367
  3. package/package.json +96 -72
package/LICENSE ADDED
@@ -0,0 +1,184 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and the Work's derivative works.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, and
120
+ distribute Your modifications, or for such Derivative Works as a
121
+ whole, subject to the terms and conditions of this License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ Copyright 2024-2026 Mairon José Cuello Martínez
172
+
173
+ Licensed under the Apache License, Version 2.0 (the "License");
174
+ you may not use this file except in compliance with the License.
175
+ You may obtain a copy of the License at
176
+
177
+ http://www.apache.org/licenses/LICENSE-2.0
178
+
179
+ Unless required by applicable law or agreed to in writing, software
180
+ distributed under the License is distributed on an "AS IS" BASIS,
181
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ See the License for the specific language governing permissions and
183
+ limitations under the License.
184
+
package/README.md CHANGED
@@ -1,367 +1,367 @@
1
- # @backendkit-labs/observability
2
-
3
- Structured logging, distributed tracing correlation, metrics shipping, performance interceptors, and exception handling for **NestJS** — with optional OpenTelemetry integration.
4
-
5
- ## Features
6
-
7
- | Feature | Description |
8
- |---|---|
9
- | **CorrelationIdService** | AsyncLocalStorage-based correlation ID propagation across the full async call stack |
10
- | **LoggerService** | Winston-backed structured logger with optional batched HTTP transport |
11
- | **MetricsService** | Fire-and-forget metric event shipping with buffering and circuit breaker |
12
- | **CorrelationInterceptor** | Reads/generates `x-correlation-id` and sets it on the response header |
13
- | **PerformanceInterceptor** | Logs and records HTTP request duration for every route |
14
- | **AllExceptionsFilter** | Unified error response shape with pluggable error mappers |
15
- | **@TrackPerformance** | Method decorator that wraps any async method in an OTel span |
16
- | **OTel optional** | `@opentelemetry/api` is a peer — drop it and everything becomes a no-op |
17
-
18
- ---
19
-
20
- ## Installation
21
-
22
- ```bash
23
- npm install @backendkit-labs/observability
24
-
25
- # optional — only if you use OTel tracing
26
- npm install @opentelemetry/api
27
- ```
28
-
29
- ---
30
-
31
- ## Quick start
32
-
33
- ```typescript
34
- // app.module.ts
35
- import { Module } from '@nestjs/common';
36
- import { ObservabilityModule } from '@backendkit-labs/observability';
37
-
38
- @Module({
39
- imports: [
40
- ObservabilityModule.forRoot({
41
- serviceName: 'my-api',
42
- environment: 'production',
43
- logLevel: 'info',
44
-
45
- // Ship logs to a remote endpoint (optional)
46
- http: {
47
- url: 'https://logs.example.com/ingest',
48
- authToken: process.env.OBS_AUTH_TOKEN,
49
- },
50
-
51
- // Ship metrics to a remote endpoint (optional)
52
- metrics: {
53
- url: 'https://metrics.example.com/ingest',
54
- authToken: process.env.OBS_AUTH_TOKEN,
55
- },
56
- }),
57
- ],
58
- })
59
- export class AppModule {}
60
- ```
61
-
62
- Register interceptors and the exception filter globally in `main.ts`:
63
-
64
- ```typescript
65
- import { NestFactory } from '@nestjs/core';
66
- import {
67
- CorrelationInterceptor,
68
- PerformanceInterceptor,
69
- AllExceptionsFilter,
70
- LoggerService,
71
- } from '@backendkit-labs/observability';
72
- import { AppModule } from './app.module';
73
-
74
- async function bootstrap() {
75
- const app = await NestFactory.create(AppModule);
76
-
77
- app.useGlobalInterceptors(
78
- app.get(CorrelationInterceptor),
79
- app.get(PerformanceInterceptor),
80
- );
81
-
82
- app.useGlobalFilters(app.get(AllExceptionsFilter));
83
-
84
- // Use LoggerService as the NestJS application logger
85
- app.useLogger(app.get(LoggerService));
86
-
87
- await app.listen(3000);
88
- }
89
- bootstrap();
90
- ```
91
-
92
- ---
93
-
94
- ## ObservabilityModule.forRoot options
95
-
96
- ```typescript
97
- interface ObservabilityOptions {
98
- serviceName: string;
99
- environment?: string; // default: "production"
100
- logLevel?: 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly';
101
- http?: HttpTransportOptions;
102
- metrics?: MetricsOptions;
103
- }
104
- ```
105
-
106
- ### HTTP log transport options
107
-
108
- ```typescript
109
- interface HttpTransportOptions {
110
- url: string;
111
- authToken?: string;
112
- headers?: Record<string, string>;
113
- batchSize?: number; // default 100
114
- maxBufferSize?: number; // default 2000
115
- flushIntervalMs?: number; // default 5000
116
- timeoutMs?: number; // default 5000
117
- circuitBreaker?: Partial<CircuitBreakerConfig>; // see below
118
- }
119
- ```
120
-
121
- ### Metrics transport options
122
-
123
- ```typescript
124
- interface MetricsOptions {
125
- url: string;
126
- authToken?: string;
127
- headers?: Record<string, string>;
128
- flushIntervalMs?: number; // default 10000
129
- maxBufferSize?: number; // default 5000
130
- timeoutMs?: number; // default 5000
131
- circuitBreaker?: Partial<CircuitBreakerConfig>; // see below
132
- }
133
- ```
134
-
135
- ---
136
-
137
- ## CorrelationIdService
138
-
139
- Propagates a request-scoped correlation ID through every `await` using `AsyncLocalStorage`.
140
-
141
- ```typescript
142
- @Injectable()
143
- export class OrdersService {
144
- constructor(private readonly correlation: CorrelationIdService) {}
145
-
146
- async processOrder(id: string) {
147
- // Always returns the ID for the current request context
148
- const cid = this.correlation.get();
149
-
150
- // Or undefined when called outside a context
151
- const maybeId = this.correlation.getOrUndefined();
152
-
153
- // OTel trace/span IDs (undefined when OTel not installed)
154
- const trace = this.correlation.getTraceContext();
155
- // => { traceId: 'abc…', spanId: '123…' } | undefined
156
- }
157
- }
158
- ```
159
-
160
- The `CorrelationInterceptor` automatically seeds the context from the incoming `x-correlation-id` header (or generates a fresh UUID) and echoes the ID back in the response header.
161
-
162
- ---
163
-
164
- ## LoggerService
165
-
166
- Drop-in replacement for NestJS's built-in logger. All log entries include `service`, `environment`, and `correlationId` automatically.
167
-
168
- ```typescript
169
- @Injectable()
170
- export class PaymentsService {
171
- constructor(private readonly logger: LoggerService) {}
172
-
173
- async charge(amount: number) {
174
- this.logger.log('Charging card', PaymentsService.name);
175
- this.logger.warn('High amount', PaymentsService.name);
176
- this.logger.error('Card declined', undefined, PaymentsService.name);
177
-
178
- // Arbitrary extra fields
179
- this.logger.logWithMeta('info', 'Payment processed', {
180
- amount,
181
- currency: 'USD',
182
- userId: 'u_123',
183
- });
184
- }
185
- }
186
- ```
187
-
188
- ### Console output format
189
-
190
- ```
191
- 2024-01-15T10:30:00.000Z [info] Charging card {"service":"payments","correlationId":"a1b2…"}
192
- ```
193
-
194
- ### HTTP transport
195
-
196
- When `http` is configured, log entries are buffered in memory and flushed in batches. A built-in circuit breaker pauses sends after repeated failures so logging never blocks your application.
197
-
198
- ---
199
-
200
- ## MetricsService
201
-
202
- ```typescript
203
- @Injectable()
204
- export class CheckoutService {
205
- constructor(private readonly metrics: MetricsService) {}
206
-
207
- async checkout(cart: Cart) {
208
- const start = Date.now();
209
- // ... process ...
210
- this.metrics.record('checkout.duration', Date.now() - start, {
211
- unit: 'ms',
212
- tags: { region: 'us-east-1' },
213
- });
214
-
215
- this.metrics.record('checkout.items', cart.items.length, {
216
- tags: { currency: cart.currency },
217
- });
218
- }
219
- }
220
- ```
221
-
222
- Events are buffered and shipped in batches. The service flushes remaining events on `onModuleDestroy` (graceful shutdown).
223
-
224
- ---
225
-
226
- ## AllExceptionsFilter
227
-
228
- Returns a consistent error shape for every unhandled exception:
229
-
230
- ```json
231
- {
232
- "ok": false,
233
- "statusCode": 404,
234
- "message": "Resource not found",
235
- "code": "NOT_FOUND",
236
- "correlationId": "a1b2c3d4-...",
237
- "timestamp": "2024-01-15T10:30:00.000Z"
238
- }
239
- ```
240
-
241
- ### Custom error mappers
242
-
243
- Register domain-specific error classes so they are mapped to the correct HTTP status:
244
-
245
- ```typescript
246
- import { AllExceptionsFilter, ErrorMapper } from '@backendkit-labs/observability';
247
-
248
- // In main.ts, after app.get(AllExceptionsFilter)
249
- const filter = app.get(AllExceptionsFilter);
250
-
251
- const domainMapper: ErrorMapper = (err) => {
252
- if (err instanceof ResourceNotFoundError) {
253
- return { statusCode: 404, message: err.message, code: 'NOT_FOUND' };
254
- }
255
- if (err instanceof ValidationError) {
256
- return { statusCode: 422, message: err.message, code: 'VALIDATION_ERROR' };
257
- }
258
- return null; // fall through to next mapper or default handling
259
- };
260
-
261
- filter.addMapper(domainMapper);
262
- app.useGlobalFilters(filter);
263
- ```
264
-
265
- Multiple mappers are tried in registration order; the first non-`null` result wins.
266
-
267
- ---
268
-
269
- ## @TrackPerformance decorator
270
-
271
- Wraps any `async` method in an OpenTelemetry span. When OTel is not installed, it becomes a pure pass-through with zero overhead.
272
-
273
- ```typescript
274
- import { TrackPerformance } from '@backendkit-labs/observability';
275
-
276
- @Injectable()
277
- export class ReportsService {
278
- @TrackPerformance()
279
- async generateReport(id: string): Promise<Report> {
280
- // Span name: "ReportsService.generateReport"
281
- return this.db.buildReport(id);
282
- }
283
-
284
- @TrackPerformance({
285
- operation: 'custom-operation-name',
286
- attributes: { team: 'analytics', critical: true },
287
- })
288
- async exportToCsv(id: string): Promise<Buffer> {
289
- return this.db.export(id);
290
- }
291
- }
292
- ```
293
-
294
- ---
295
-
296
- ## OpenTelemetry integration
297
-
298
- Install `@opentelemetry/api` and configure an SDK (e.g. `@opentelemetry/sdk-node`) separately. This package auto-detects the API and attaches spans — no extra configuration needed here.
299
-
300
- ```bash
301
- npm install @opentelemetry/api @opentelemetry/sdk-node
302
- ```
303
-
304
- `CorrelationIdService.getTraceContext()` returns the active `traceId` and `spanId` when OTel is active, useful for log correlation:
305
-
306
- ```typescript
307
- const trace = this.correlation.getTraceContext();
308
- // { traceId: 'abc123…', spanId: 'def456…' }
309
- ```
310
-
311
- ---
312
-
313
- ## Circuit breaker behaviour
314
-
315
- Both the HTTP log transport and the metrics transport use [`@backendkit-labs/circuit-breaker`](../circuit-breaker) to protect your application from cascading failures in the observability backend:
316
-
317
- ```
318
- CLOSED ──(failure rate ≥ threshold)──► OPEN ──(openTimeoutMs)──► HALF_OPEN ──(probe succeeds)──► CLOSED
319
- └─(probe fails)───► OPEN
320
- ```
321
-
322
- ### Transport defaults
323
-
324
- | Option | Default | Description |
325
- |---|---|---|
326
- | `failureThreshold` | `60` | % of calls in the window that must fail to open the circuit |
327
- | `slidingWindowSize` | `5` | Number of calls in the evaluation window |
328
- | `minimumCalls` | `3` | Minimum calls before thresholds are evaluated |
329
- | `openTimeoutMs` | `30 000` | Time to wait in OPEN before transitioning to HALF_OPEN |
330
- | `halfOpenMaxCalls` | `1` | Probe calls allowed in HALF_OPEN |
331
- | `slowCallThreshold` | `100` | % of slow calls to open the circuit (disabled by default) |
332
- | `slowCallDurationMs` | `60 000` | Duration above which a call is considered slow |
333
-
334
- ### Customising the circuit breaker
335
-
336
- Pass any subset of `CircuitBreakerConfig` via the `circuitBreaker` option. `name` and `isFailure` are managed internally.
337
-
338
- ```typescript
339
- import { CircuitBreakerState } from '@backendkit-labs/circuit-breaker';
340
-
341
- ObservabilityModule.forRoot({
342
- serviceName: 'my-api',
343
- metrics: {
344
- url: 'https://metrics.example.com/ingest',
345
- circuitBreaker: {
346
- failureThreshold: 80, // open only when 80% of calls fail
347
- slidingWindowSize: 10,
348
- minimumCalls: 5,
349
- openTimeoutMs: 60_000, // stay open for 60 s
350
- halfOpenMaxCalls: 2, // send 2 probes before closing
351
- onStateChange: (from, to, metrics) => {
352
- if (to === CircuitBreakerState.OPEN) {
353
- alerting.trigger(`Metrics CB opened — failure rate ${metrics.failureRate}%`);
354
- }
355
- },
356
- },
357
- },
358
- });
359
- ```
360
-
361
- The same `circuitBreaker` option is available on the `http` log transport.
362
-
363
- ---
364
-
365
- ## License
366
-
367
- MIT
1
+ # @backendkit-labs/observability
2
+
3
+ Structured logging, distributed tracing correlation, metrics shipping, performance interceptors, and exception handling for **NestJS** — with optional OpenTelemetry integration.
4
+
5
+ ## Features
6
+
7
+ | Feature | Description |
8
+ |---|---|
9
+ | **CorrelationIdService** | AsyncLocalStorage-based correlation ID propagation across the full async call stack |
10
+ | **LoggerService** | Winston-backed structured logger with optional batched HTTP transport |
11
+ | **MetricsService** | Fire-and-forget metric event shipping with buffering and circuit breaker |
12
+ | **CorrelationInterceptor** | Reads/generates `x-correlation-id` and sets it on the response header |
13
+ | **PerformanceInterceptor** | Logs and records HTTP request duration for every route |
14
+ | **AllExceptionsFilter** | Unified error response shape with pluggable error mappers |
15
+ | **@TrackPerformance** | Method decorator that wraps any async method in an OTel span |
16
+ | **OTel optional** | `@opentelemetry/api` is a peer — drop it and everything becomes a no-op |
17
+
18
+ ---
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install @backendkit-labs/observability
24
+
25
+ # optional — only if you use OTel tracing
26
+ npm install @opentelemetry/api
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Quick start
32
+
33
+ ```typescript
34
+ // app.module.ts
35
+ import { Module } from '@nestjs/common';
36
+ import { ObservabilityModule } from '@backendkit-labs/observability';
37
+
38
+ @Module({
39
+ imports: [
40
+ ObservabilityModule.forRoot({
41
+ serviceName: 'my-api',
42
+ environment: 'production',
43
+ logLevel: 'info',
44
+
45
+ // Ship logs to a remote endpoint (optional)
46
+ http: {
47
+ url: 'https://logs.example.com/ingest',
48
+ authToken: process.env.OBS_AUTH_TOKEN,
49
+ },
50
+
51
+ // Ship metrics to a remote endpoint (optional)
52
+ metrics: {
53
+ url: 'https://metrics.example.com/ingest',
54
+ authToken: process.env.OBS_AUTH_TOKEN,
55
+ },
56
+ }),
57
+ ],
58
+ })
59
+ export class AppModule {}
60
+ ```
61
+
62
+ Register interceptors and the exception filter globally in `main.ts`:
63
+
64
+ ```typescript
65
+ import { NestFactory } from '@nestjs/core';
66
+ import {
67
+ CorrelationInterceptor,
68
+ PerformanceInterceptor,
69
+ AllExceptionsFilter,
70
+ LoggerService,
71
+ } from '@backendkit-labs/observability';
72
+ import { AppModule } from './app.module';
73
+
74
+ async function bootstrap() {
75
+ const app = await NestFactory.create(AppModule);
76
+
77
+ app.useGlobalInterceptors(
78
+ app.get(CorrelationInterceptor),
79
+ app.get(PerformanceInterceptor),
80
+ );
81
+
82
+ app.useGlobalFilters(app.get(AllExceptionsFilter));
83
+
84
+ // Use LoggerService as the NestJS application logger
85
+ app.useLogger(app.get(LoggerService));
86
+
87
+ await app.listen(3000);
88
+ }
89
+ bootstrap();
90
+ ```
91
+
92
+ ---
93
+
94
+ ## ObservabilityModule.forRoot options
95
+
96
+ ```typescript
97
+ interface ObservabilityOptions {
98
+ serviceName: string;
99
+ environment?: string; // default: "production"
100
+ logLevel?: 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly';
101
+ http?: HttpTransportOptions;
102
+ metrics?: MetricsOptions;
103
+ }
104
+ ```
105
+
106
+ ### HTTP log transport options
107
+
108
+ ```typescript
109
+ interface HttpTransportOptions {
110
+ url: string;
111
+ authToken?: string;
112
+ headers?: Record<string, string>;
113
+ batchSize?: number; // default 100
114
+ maxBufferSize?: number; // default 2000
115
+ flushIntervalMs?: number; // default 5000
116
+ timeoutMs?: number; // default 5000
117
+ circuitBreaker?: Partial<CircuitBreakerConfig>; // see below
118
+ }
119
+ ```
120
+
121
+ ### Metrics transport options
122
+
123
+ ```typescript
124
+ interface MetricsOptions {
125
+ url: string;
126
+ authToken?: string;
127
+ headers?: Record<string, string>;
128
+ flushIntervalMs?: number; // default 10000
129
+ maxBufferSize?: number; // default 5000
130
+ timeoutMs?: number; // default 5000
131
+ circuitBreaker?: Partial<CircuitBreakerConfig>; // see below
132
+ }
133
+ ```
134
+
135
+ ---
136
+
137
+ ## CorrelationIdService
138
+
139
+ Propagates a request-scoped correlation ID through every `await` using `AsyncLocalStorage`.
140
+
141
+ ```typescript
142
+ @Injectable()
143
+ export class OrdersService {
144
+ constructor(private readonly correlation: CorrelationIdService) {}
145
+
146
+ async processOrder(id: string) {
147
+ // Always returns the ID for the current request context
148
+ const cid = this.correlation.get();
149
+
150
+ // Or undefined when called outside a context
151
+ const maybeId = this.correlation.getOrUndefined();
152
+
153
+ // OTel trace/span IDs (undefined when OTel not installed)
154
+ const trace = this.correlation.getTraceContext();
155
+ // => { traceId: 'abc…', spanId: '123…' } | undefined
156
+ }
157
+ }
158
+ ```
159
+
160
+ The `CorrelationInterceptor` automatically seeds the context from the incoming `x-correlation-id` header (or generates a fresh UUID) and echoes the ID back in the response header.
161
+
162
+ ---
163
+
164
+ ## LoggerService
165
+
166
+ Drop-in replacement for NestJS's built-in logger. All log entries include `service`, `environment`, and `correlationId` automatically.
167
+
168
+ ```typescript
169
+ @Injectable()
170
+ export class PaymentsService {
171
+ constructor(private readonly logger: LoggerService) {}
172
+
173
+ async charge(amount: number) {
174
+ this.logger.log('Charging card', PaymentsService.name);
175
+ this.logger.warn('High amount', PaymentsService.name);
176
+ this.logger.error('Card declined', undefined, PaymentsService.name);
177
+
178
+ // Arbitrary extra fields
179
+ this.logger.logWithMeta('info', 'Payment processed', {
180
+ amount,
181
+ currency: 'USD',
182
+ userId: 'u_123',
183
+ });
184
+ }
185
+ }
186
+ ```
187
+
188
+ ### Console output format
189
+
190
+ ```
191
+ 2024-01-15T10:30:00.000Z [info] Charging card {"service":"payments","correlationId":"a1b2…"}
192
+ ```
193
+
194
+ ### HTTP transport
195
+
196
+ When `http` is configured, log entries are buffered in memory and flushed in batches. A built-in circuit breaker pauses sends after repeated failures so logging never blocks your application.
197
+
198
+ ---
199
+
200
+ ## MetricsService
201
+
202
+ ```typescript
203
+ @Injectable()
204
+ export class CheckoutService {
205
+ constructor(private readonly metrics: MetricsService) {}
206
+
207
+ async checkout(cart: Cart) {
208
+ const start = Date.now();
209
+ // ... process ...
210
+ this.metrics.record('checkout.duration', Date.now() - start, {
211
+ unit: 'ms',
212
+ tags: { region: 'us-east-1' },
213
+ });
214
+
215
+ this.metrics.record('checkout.items', cart.items.length, {
216
+ tags: { currency: cart.currency },
217
+ });
218
+ }
219
+ }
220
+ ```
221
+
222
+ Events are buffered and shipped in batches. The service flushes remaining events on `onModuleDestroy` (graceful shutdown).
223
+
224
+ ---
225
+
226
+ ## AllExceptionsFilter
227
+
228
+ Returns a consistent error shape for every unhandled exception:
229
+
230
+ ```json
231
+ {
232
+ "ok": false,
233
+ "statusCode": 404,
234
+ "message": "Resource not found",
235
+ "code": "NOT_FOUND",
236
+ "correlationId": "a1b2c3d4-...",
237
+ "timestamp": "2024-01-15T10:30:00.000Z"
238
+ }
239
+ ```
240
+
241
+ ### Custom error mappers
242
+
243
+ Register domain-specific error classes so they are mapped to the correct HTTP status:
244
+
245
+ ```typescript
246
+ import { AllExceptionsFilter, ErrorMapper } from '@backendkit-labs/observability';
247
+
248
+ // In main.ts, after app.get(AllExceptionsFilter)
249
+ const filter = app.get(AllExceptionsFilter);
250
+
251
+ const domainMapper: ErrorMapper = (err) => {
252
+ if (err instanceof ResourceNotFoundError) {
253
+ return { statusCode: 404, message: err.message, code: 'NOT_FOUND' };
254
+ }
255
+ if (err instanceof ValidationError) {
256
+ return { statusCode: 422, message: err.message, code: 'VALIDATION_ERROR' };
257
+ }
258
+ return null; // fall through to next mapper or default handling
259
+ };
260
+
261
+ filter.addMapper(domainMapper);
262
+ app.useGlobalFilters(filter);
263
+ ```
264
+
265
+ Multiple mappers are tried in registration order; the first non-`null` result wins.
266
+
267
+ ---
268
+
269
+ ## @TrackPerformance decorator
270
+
271
+ Wraps any `async` method in an OpenTelemetry span. When OTel is not installed, it becomes a pure pass-through with zero overhead.
272
+
273
+ ```typescript
274
+ import { TrackPerformance } from '@backendkit-labs/observability';
275
+
276
+ @Injectable()
277
+ export class ReportsService {
278
+ @TrackPerformance()
279
+ async generateReport(id: string): Promise<Report> {
280
+ // Span name: "ReportsService.generateReport"
281
+ return this.db.buildReport(id);
282
+ }
283
+
284
+ @TrackPerformance({
285
+ operation: 'custom-operation-name',
286
+ attributes: { team: 'analytics', critical: true },
287
+ })
288
+ async exportToCsv(id: string): Promise<Buffer> {
289
+ return this.db.export(id);
290
+ }
291
+ }
292
+ ```
293
+
294
+ ---
295
+
296
+ ## OpenTelemetry integration
297
+
298
+ Install `@opentelemetry/api` and configure an SDK (e.g. `@opentelemetry/sdk-node`) separately. This package auto-detects the API and attaches spans — no extra configuration needed here.
299
+
300
+ ```bash
301
+ npm install @opentelemetry/api @opentelemetry/sdk-node
302
+ ```
303
+
304
+ `CorrelationIdService.getTraceContext()` returns the active `traceId` and `spanId` when OTel is active, useful for log correlation:
305
+
306
+ ```typescript
307
+ const trace = this.correlation.getTraceContext();
308
+ // { traceId: 'abc123…', spanId: 'def456…' }
309
+ ```
310
+
311
+ ---
312
+
313
+ ## Circuit breaker behaviour
314
+
315
+ Both the HTTP log transport and the metrics transport use [`@backendkit-labs/circuit-breaker`](../circuit-breaker) to protect your application from cascading failures in the observability backend:
316
+
317
+ ```
318
+ CLOSED ──(failure rate ≥ threshold)──► OPEN ──(openTimeoutMs)──► HALF_OPEN ──(probe succeeds)──► CLOSED
319
+ └─(probe fails)───► OPEN
320
+ ```
321
+
322
+ ### Transport defaults
323
+
324
+ | Option | Default | Description |
325
+ |---|---|---|
326
+ | `failureThreshold` | `60` | % of calls in the window that must fail to open the circuit |
327
+ | `slidingWindowSize` | `5` | Number of calls in the evaluation window |
328
+ | `minimumCalls` | `3` | Minimum calls before thresholds are evaluated |
329
+ | `openTimeoutMs` | `30 000` | Time to wait in OPEN before transitioning to HALF_OPEN |
330
+ | `halfOpenMaxCalls` | `1` | Probe calls allowed in HALF_OPEN |
331
+ | `slowCallThreshold` | `100` | % of slow calls to open the circuit (disabled by default) |
332
+ | `slowCallDurationMs` | `60 000` | Duration above which a call is considered slow |
333
+
334
+ ### Customising the circuit breaker
335
+
336
+ Pass any subset of `CircuitBreakerConfig` via the `circuitBreaker` option. `name` and `isFailure` are managed internally.
337
+
338
+ ```typescript
339
+ import { CircuitBreakerState } from '@backendkit-labs/circuit-breaker';
340
+
341
+ ObservabilityModule.forRoot({
342
+ serviceName: 'my-api',
343
+ metrics: {
344
+ url: 'https://metrics.example.com/ingest',
345
+ circuitBreaker: {
346
+ failureThreshold: 80, // open only when 80% of calls fail
347
+ slidingWindowSize: 10,
348
+ minimumCalls: 5,
349
+ openTimeoutMs: 60_000, // stay open for 60 s
350
+ halfOpenMaxCalls: 2, // send 2 probes before closing
351
+ onStateChange: (from, to, metrics) => {
352
+ if (to === CircuitBreakerState.OPEN) {
353
+ alerting.trigger(`Metrics CB opened — failure rate ${metrics.failureRate}%`);
354
+ }
355
+ },
356
+ },
357
+ },
358
+ });
359
+ ```
360
+
361
+ The same `circuitBreaker` option is available on the `http` log transport.
362
+
363
+ ---
364
+
365
+ ## License
366
+
367
+ Apache-2.0
package/package.json CHANGED
@@ -1,72 +1,96 @@
1
- {
2
- "name": "@backendkit-labs/observability",
3
- "version": "0.1.0",
4
- "description": "Structured logging, metrics, correlation ID propagation, and exception handling for NestJS — no OTel SDK required",
5
- "type": "module",
6
- "main": "./dist/index.cjs",
7
- "module": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
14
- }
15
- },
16
- "files": ["dist", "README.md", "LICENSE"],
17
- "scripts": {
18
- "build": "tsup",
19
- "dev": "tsup --watch",
20
- "test": "vitest run",
21
- "test:watch": "vitest",
22
- "test:coverage": "vitest run --coverage",
23
- "typecheck": "tsc --noEmit",
24
- "lint": "eslint src/",
25
- "prepublishOnly": "npm run build && npm run test && npm run lint"
26
- },
27
- "keywords": [
28
- "observability", "logging", "metrics", "correlation-id", "nestjs",
29
- "winston", "opentelemetry", "tracing", "structured-logging", "node"
30
- ],
31
- "author": "Mairon José Cuello Martínez",
32
- "license": "MIT",
33
- "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/observability#readme",
34
- "repository": {
35
- "type": "git",
36
- "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
37
- "directory": "packages/observability"
38
- },
39
- "bugs": { "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues" },
40
- "sideEffects": false,
41
- "engines": { "node": ">=18" },
42
- "dependencies": {
43
- "@backendkit-labs/circuit-breaker": "*",
44
- "axios": "^1.7.0",
45
- "winston": "^3.11.0",
46
- "winston-transport": "^4.7.0"
47
- },
48
- "peerDependencies": {
49
- "@nestjs/common": ">=10.0.0",
50
- "@nestjs/core": ">=10.0.0",
51
- "@opentelemetry/api": ">=1.0.0",
52
- "rxjs": ">=7.0.0"
53
- },
54
- "peerDependenciesMeta": {
55
- "@opentelemetry/api": { "optional": true }
56
- },
57
- "devDependencies": {
58
- "@eslint/js": "^9.39.4",
59
- "@nestjs/common": "^10.0.0",
60
- "@nestjs/core": "^10.0.0",
61
- "@opentelemetry/api": "^1.9.0",
62
- "@types/express": "^4.17.21",
63
- "@types/node": "^22.0.0",
64
- "eslint": "^9.0.0",
65
- "reflect-metadata": "^0.2.0",
66
- "rxjs": "^7.8.0",
67
- "tsup": "^8.0.0",
68
- "typescript": "^5.5.0",
69
- "typescript-eslint": "^8.59.3",
70
- "vitest": "^2.0.0"
71
- }
72
- }
1
+ {
2
+ "name": "@backendkit-labs/observability",
3
+ "version": "0.1.1",
4
+ "license": "Apache-2.0",
5
+ "author": {
6
+ "name": "BackendKit Labs",
7
+ "email": "backendkit.dev@gmail.com"
8
+ },
9
+ "description": "Structured logging, metrics, correlation ID propagation, and exception handling for NestJS — no OTel SDK required",
10
+ "type": "module",
11
+ "main": "./dist/index.cjs",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js",
18
+ "require": "./dist/index.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "dev": "tsup --watch",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest",
31
+ "test:coverage": "vitest run --coverage",
32
+ "typecheck": "tsc --noEmit",
33
+ "lint": "eslint src/",
34
+ "prepublishOnly": "npm run build && npm run test && npm run lint"
35
+ },
36
+ "keywords": [
37
+ "observability",
38
+ "logging",
39
+ "metrics",
40
+ "correlation-id",
41
+ "nestjs",
42
+ "winston",
43
+ "opentelemetry",
44
+ "tracing",
45
+ "structured-logging",
46
+ "node"
47
+ ],
48
+ "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/observability#readme",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
52
+ "directory": "packages/observability"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "sideEffects": false,
61
+ "engines": {
62
+ "node": ">=18"
63
+ },
64
+ "dependencies": {
65
+ "@backendkit-labs/circuit-breaker": "*",
66
+ "axios": "^1.7.0",
67
+ "winston": "^3.11.0",
68
+ "winston-transport": "^4.7.0"
69
+ },
70
+ "peerDependencies": {
71
+ "@nestjs/common": ">=10.0.0",
72
+ "@nestjs/core": ">=10.0.0",
73
+ "@opentelemetry/api": ">=1.0.0",
74
+ "rxjs": ">=7.0.0"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@opentelemetry/api": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "devDependencies": {
82
+ "@eslint/js": "^9.39.4",
83
+ "@nestjs/common": "^10.0.0",
84
+ "@nestjs/core": "^10.0.0",
85
+ "@opentelemetry/api": "^1.9.0",
86
+ "@types/express": "^4.17.21",
87
+ "@types/node": "^22.0.0",
88
+ "eslint": "^9.0.0",
89
+ "reflect-metadata": "^0.2.0",
90
+ "rxjs": "^7.8.0",
91
+ "tsup": "^8.0.0",
92
+ "typescript": "^5.5.0",
93
+ "typescript-eslint": "^8.59.3",
94
+ "vitest": "^2.0.0"
95
+ }
96
+ }