@nathapp/nestjs-logging 2.1.4 → 3.0.0-rc.4

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 (40) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +144 -0
  3. package/dist/config/config.resolver.js +26 -7
  4. package/dist/config/config.resolver.js.map +1 -1
  5. package/dist/config/logging.config.js +1 -1
  6. package/dist/config/logging.config.js.map +1 -1
  7. package/dist/constant/logging.constant.js +12 -0
  8. package/dist/constant/logging.constant.js.map +1 -1
  9. package/dist/interceptor/logging.interceptor.d.ts +0 -1
  10. package/dist/interceptor/logging.interceptor.js +20 -16
  11. package/dist/interceptor/logging.interceptor.js.map +1 -1
  12. package/dist/module/logging.interface.d.ts +1 -1
  13. package/dist/module/logging.module.d.ts +6 -3
  14. package/dist/module/logging.module.js +12 -4
  15. package/dist/module/logging.module.js.map +1 -1
  16. package/dist/provider/default-logger.service.d.ts +3 -2
  17. package/dist/provider/default-logger.service.js +2 -0
  18. package/dist/provider/default-logger.service.js.map +1 -1
  19. package/dist/provider/logger.service.d.ts +7 -3
  20. package/dist/provider/logger.service.js +0 -7
  21. package/dist/provider/logger.service.js.map +1 -1
  22. package/dist/provider/pino-logger.service.d.ts +3 -2
  23. package/dist/provider/pino-logger.service.js +5 -0
  24. package/dist/provider/pino-logger.service.js.map +1 -1
  25. package/dist/provider/provider.interface.d.ts +4 -15
  26. package/dist/provider/winston-logger.service.d.ts +4 -2
  27. package/dist/provider/winston-logger.service.js +36 -1
  28. package/dist/provider/winston-logger.service.js.map +1 -1
  29. package/dist/serialize/serializer.d.ts +21 -1
  30. package/dist/serialize/serializer.js +8 -1
  31. package/dist/serialize/serializer.js.map +1 -1
  32. package/dist/util/file-rotation.utils.d.ts +1 -1
  33. package/dist/util/file-rotation.utils.js +2 -4
  34. package/dist/util/file-rotation.utils.js.map +1 -1
  35. package/dist/util/options.util.d.ts +5 -5
  36. package/dist/util/options.util.js.map +1 -1
  37. package/docs/20260215-fix-plan-logging.md +177 -0
  38. package/docs/20260215-review-logging-deep.md +264 -0
  39. package/docs/20260215-test-plan-logging.md +37 -0
  40. package/package.json +3 -3
@@ -0,0 +1,264 @@
1
+ # Deep Code Review: @nathapp/nestjs-logging
2
+
3
+ **Date:** 2026-02-15
4
+ **Reviewer:** Subrina (AI)
5
+ **Version:** 2.1.5
6
+ **Branch:** feat/monorepo-enterprise-upgrade
7
+ **Files:** 35 (lib: ~1480 LOC, test: ~380 LOC)
8
+ **Baseline:** 21 tests, 3 test files, 0% coverage reported (jest config issue)
9
+
10
+ ---
11
+
12
+ ## Overall Grade: C+ (72/100)
13
+
14
+ The package provides a solid multi-provider logging abstraction (default/pino/winston) with request context, auto-logging interceptor, and centralized logging support. However, it has significant issues in security, memory safety, type safety, and test coverage.
15
+
16
+ ---
17
+
18
+ ## Findings
19
+
20
+ ### 🔴 CRITICAL
21
+
22
+ #### SEC-1: JSON.parse on env vars without try/catch (config.resolver.ts:27, 96)
23
+ **Severity:** CRITICAL | **Category:** Security/Stability
24
+ ```typescript
25
+ // Line 27 - crashes if malformed
26
+ const additionalLabels = process.env.LOGGING_CENTRALIZED_LABELS
27
+ ? JSON.parse(process.env.LOGGING_CENTRALIZED_LABELS)
28
+ : {};
29
+
30
+ // Line 96 - crashes if malformed
31
+ headers: process.env.LOGGING_CENTRALIZED_HEADERS
32
+ ? JSON.parse(process.env.LOGGING_CENTRALIZED_HEADERS)
33
+ : {},
34
+ ```
35
+ **Risk:** Malformed JSON in an environment variable will crash the entire application at startup. No error handling, no fallback.
36
+ **Fix:** Wrap in try/catch, log a warning, and fall back to empty object.
37
+
38
+ #### SEC-2: fast-redact mutates objects in place (logging.interceptor.ts:76-87)
39
+ **Severity:** CRITICAL | **Category:** Security/Data Corruption
40
+ ```typescript
41
+ if (body && !isUndefinedOrNullOrEmpty(body)) {
42
+ metadata.requestData = this.redact(body); // MUTATES the original request body!
43
+ }
44
+ ```
45
+ **Risk:** `fast-redact` with `serialize: false` **mutates the original object**. This means the actual `req.body` gets its sensitive fields permanently replaced with `[REDACTED]`, breaking downstream handlers, validation pipes, and any middleware that reads the body after the interceptor.
46
+ **Fix:** Clone before redacting: `this.redact(structuredClone(body))` or use `serialize: (value) => JSON.parse(JSON.stringify(value))`.
47
+
48
+ #### MEM-1: Winston/Pino transports never destroyed (winston-logger.service.ts, pino-logger.service.ts)
49
+ **Severity:** CRITICAL | **Category:** Memory Leak
50
+ Neither `WinstonLoggerService` nor `PinoLoggerService` implements `OnModuleDestroy`. When the module is destroyed (hot reload, graceful shutdown):
51
+ - Winston Loki transport keeps HTTP connections open
52
+ - Pino Loki transport keeps batching timers alive
53
+ - Rotating file streams keep file handles open
54
+ - Pino worker threads stay alive
55
+
56
+ **Fix:** Implement `OnModuleDestroy` on both services. Call `winston.close()`, `pino.destination.end()`, or equivalent cleanup.
57
+
58
+ #### MEM-2: Rotating file stream never closed (file-rotation.utils.ts)
59
+ **Severity:** CRITICAL | **Category:** Memory Leak
60
+ ```typescript
61
+ export const createRotatingStream = (options: FileLoggingOptions): Writable => {
62
+ // Creates a stream but there's no cleanup mechanism
63
+ return rfs.createStream(filenameGenerator, rfsOptions);
64
+ }
65
+ ```
66
+ The rotating file stream is created but never stored in a way that allows cleanup. On app shutdown or hot reload, file handles leak.
67
+
68
+ #### SEC-3: requestData overwritten by params then body (logging.interceptor.ts:76-83)
69
+ **Severity:** HIGH | **Category:** Bug
70
+ ```typescript
71
+ if (query && !isUndefinedOrNullOrEmpty(query)) {
72
+ metadata.requestData = this.redact(query); // set to query
73
+ }
74
+ if (params && !isUndefinedOrNullOrEmpty(params)) {
75
+ metadata.requestData = this.redact(params); // OVERWRITTEN by params
76
+ }
77
+ if (body && !isUndefinedOrNullOrEmpty(body)) {
78
+ metadata.requestData = this.redact(body); // OVERWRITTEN by body
79
+ }
80
+ ```
81
+ Only the last non-empty source wins. If a request has both query params and a body, only the body is logged. Query and params data is silently lost.
82
+ **Fix:** Use separate fields: `metadata.query`, `metadata.params`, `metadata.body`.
83
+
84
+ ---
85
+
86
+ ### 🟡 MEDIUM
87
+
88
+ #### BUG-1: `file.maxFiles` is NaN when env var is not set (config.resolver.ts:87)
89
+ **Severity:** MEDIUM | **Category:** Bug
90
+ ```typescript
91
+ maxFiles: parseInt(process.env.LOGGING_FILE_MAX_FILES), // NaN if undefined
92
+ ```
93
+ `parseInt(undefined)` returns `NaN`. This gets passed to the file rotation library and may cause unexpected behavior.
94
+ **Fix:** `parseInt(process.env.LOGGING_FILE_MAX_FILES) || undefined`
95
+
96
+ #### BUG-2: `basicAuth.password` can be undefined (config.resolver.ts:48-52)
97
+ **Severity:** MEDIUM | **Category:** Bug
98
+ ```typescript
99
+ if(basicAuthUsername) {
100
+ basicAuth = {
101
+ username: basicAuthUsername,
102
+ password: basicAuthPassword // undefined if env var not set
103
+ }
104
+ }
105
+ ```
106
+ If username is set but password isn't, the basicAuth object has `password: undefined`, which may cause authentication failures at the Loki endpoint.
107
+ **Fix:** Require both or neither. Warn if only one is set.
108
+
109
+ #### BUG-3: `enrichContext` always returns empty object (logger.service.ts:57-63)
110
+ **Severity:** MEDIUM | **Category:** Dead Code
111
+ ```typescript
112
+ protected enrichContext(meta: Record<string, any>) {
113
+ if(this.contextService && !isUndefinedOrNullOrEmpty(meta)) {
114
+ this.contextService.updateContext(meta)
115
+ }
116
+ return {} // Always returns empty - what's the point?
117
+ }
118
+ ```
119
+ This method updates context as a side effect but always returns `{}`. It's never called from any subclass either. Dead code that indicates an incomplete feature.
120
+
121
+ #### TYPE-1: Logger services not typed (pino-logger.service.ts:24, winston-logger.service.ts:12)
122
+ **Severity:** MEDIUM | **Category:** Type Safety
123
+ ```typescript
124
+ private readonly logger: any; // Both Pino and Winston loggers are typed as `any`
125
+ ```
126
+ **Fix:** Use proper types: `import pino from 'pino'` → `pino.Logger`, or at minimum define a minimal interface.
127
+
128
+ #### TYPE-2: LoggingModuleOptionsFactory missing AdditionalFactoryOptions param (logging.interface.ts:89)
129
+ **Severity:** MEDIUM | **Category:** API Inconsistency
130
+ ```typescript
131
+ export interface LoggingModuleOptionsFactory {
132
+ createOptions(): Promise<LoggingModuleOptions> | LoggingModuleOptions;
133
+ }
134
+ ```
135
+ But `DefaultLoggingModuleOptionsFactory` implements:
136
+ ```typescript
137
+ createOptions(options?: AdditionalFactoryOptions): LoggingModuleOptions
138
+ ```
139
+ The interface doesn't declare the optional parameter.
140
+
141
+ #### PERF-1: process.hrtime called twice in log() (logging.interceptor.ts:103)
142
+ **Severity:** LOW | **Category:** Performance
143
+ ```typescript
144
+ metadata.responseTime = Number(
145
+ (process.hrtime(startAt)[0] * 1e3 + process.hrtime(startAt)[1] * 1e-6).toFixed(2)
146
+ );
147
+ ```
148
+ `process.hrtime(startAt)` is called twice, giving slightly different values for seconds and nanoseconds. Should capture once:
149
+ ```typescript
150
+ const diff = process.hrtime(startAt);
151
+ metadata.responseTime = Number((diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2));
152
+ ```
153
+
154
+ #### ENH-1: Default redact paths only go 3 levels deep (logging.constant.ts)
155
+ **Severity:** MEDIUM | **Category:** Security
156
+ ```typescript
157
+ 'password', '*.password', '*.*.password' // Only 3 levels
158
+ ```
159
+ Nested objects deeper than 3 levels won't be redacted. This is a common surprise for developers.
160
+ **Fix:** Use `fast-redact` wildcard patterns if supported, or document the limitation clearly. Consider adding `**.password` style patterns.
161
+
162
+ #### ENH-2: No structured error logging (interceptor catches error but loses context)
163
+ **Severity:** MEDIUM | **Category:** Best Practice
164
+ ```typescript
165
+ catchError(async (error: any) => {
166
+ metadata.statusCode = error?.status || 500;
167
+ if(this.loggingOptions.error) {
168
+ const errorResponse = error?.response;
169
+ metadata.error = typeof errorResponse === 'object' ? ... : errorResponse;
170
+ }
171
+ // Stack trace is NOT captured!
172
+ this.log(metadata, 'error', startAt);
173
+ throw error;
174
+ })
175
+ ```
176
+ The error stack trace is never logged. In production, you get "500 Internal Server Error" but not where it happened.
177
+ **Fix:** Add `metadata.stack = error?.stack` when error logging is enabled.
178
+
179
+ #### ENH-3: No `onApplicationShutdown` or graceful drain
180
+ **Severity:** MEDIUM | **Category:** Enterprise
181
+ Centralized logging (Loki) with batching may lose the final batch of logs on shutdown. There's no flush/drain mechanism.
182
+ **Fix:** Implement `OnApplicationShutdown` to flush pending logs before exit.
183
+
184
+ ---
185
+
186
+ ### 🟢 LOW / IMPROVEMENTS
187
+
188
+ #### STYLE-1: Typo "middlwareOptions" (logging.module.ts:72)
189
+ ```typescript
190
+ const middlwareOptions = this.options.middleware; // Should be: middlewareOptions
191
+ ```
192
+
193
+ #### STYLE-2: Inconsistent spacing and formatting throughout
194
+ Mixed use of `if(` vs `if (`, inconsistent semicolons, and non-standard whitespace.
195
+
196
+ #### STYLE-3: TODO left in default-logger.service.ts:18
197
+ ```typescript
198
+ /**
199
+ * TODO: Implement as async console logger
200
+ */
201
+ ```
202
+
203
+ #### ENH-4: No JSDoc on public APIs
204
+ Most public classes, methods, and interfaces lack documentation. Critical for a library package.
205
+
206
+ #### ENH-5: `LoggingConfigSchema` uses `@IsBooleanString` for `LOGGING_TYPE` (logging.config.ts:21)
207
+ ```typescript
208
+ @IsBooleanString() // LOGGING_TYPE is 'pino' | 'winston' | 'default', not a boolean!
209
+ LOGGING_TYPE: string;
210
+ ```
211
+
212
+ #### ENH-6: Provider interface duplication (provider.interface.ts)
213
+ `DefaultLoggerOptions`, `PinoLoggerOptions`, and `WinstonLoggerOptions` are identical interfaces. Should be a single `LoggerProviderOptions` type.
214
+
215
+ #### ENH-7: `context` field clobbered on each interceptor call (logging.interceptor.ts:55)
216
+ ```typescript
217
+ this.context = context.getClass().name || context.constructor.name;
218
+ ```
219
+ This is an instance field set on each request. If concurrent requests hit, they'll overwrite each other's context name. Should be a local variable instead.
220
+
221
+ #### ENH-8: No test for LoggingInterceptor, ContextMiddleware, serializer, or file rotation
222
+ Coverage is effectively 0% for the most critical code paths. Only module registration is tested.
223
+
224
+ #### ENH-9: Missing `@Global()` option
225
+ Unlike other NestJS logging libraries (e.g., nestjs-pino), there's no way to make the module global. Consumers must import in every module.
226
+
227
+ ---
228
+
229
+ ## Priority Fix Order
230
+
231
+ | Priority | ID | Effort | Description |
232
+ |:---|:---|:---|:---|
233
+ | P0 | SEC-2 | S | fast-redact object mutation (data corruption) |
234
+ | P0 | MEM-1 | M | Transport cleanup on destroy |
235
+ | P0 | MEM-2 | S | Rotating stream cleanup |
236
+ | P0 | SEC-1 | S | JSON.parse crash on malformed env |
237
+ | P1 | SEC-3 | S | requestData overwrite bug |
238
+ | P1 | ENH-2 | S | Error stack trace logging |
239
+ | P1 | ENH-7 | S | Race condition on context field |
240
+ | P1 | BUG-1 | S | NaN maxFiles |
241
+ | P1 | PERF-1 | S | Double hrtime call |
242
+ | P2 | BUG-2 | S | basicAuth password validation |
243
+ | P2 | BUG-3 | S | Dead enrichContext method |
244
+ | P2 | TYPE-1 | M | Type the logger instances |
245
+ | P2 | TYPE-2 | S | Fix factory interface |
246
+ | P2 | ENH-1 | S | Document redact depth limitation |
247
+ | P2 | ENH-3 | M | Graceful shutdown flush |
248
+ | P2 | ENH-5 | S | Fix LOGGING_TYPE validator |
249
+ | P2 | ENH-6 | S | Deduplicate provider interfaces |
250
+ | P3 | ENH-4 | L | JSDoc documentation |
251
+ | P3 | ENH-8 | L | Test coverage (target 80%+) |
252
+ | P3 | ENH-9 | S | Global module option |
253
+ | P3 | STYLE-* | S | Formatting cleanup |
254
+
255
+ **S** = Small (<30 min), **M** = Medium (30-120 min), **L** = Large (2+ hours)
256
+
257
+ ---
258
+
259
+ ## Recommendations
260
+
261
+ 1. **Immediate**: Fix SEC-2 (data corruption) and MEM-1/MEM-2 (memory leaks) — these are production-impacting.
262
+ 2. **Before 3.0.0**: Fix all P0 and P1 items. This is a logging library — silent data loss and memory leaks undermine its core purpose.
263
+ 3. **Test coverage**: Currently at effectively 0% for business logic. The interceptor, middleware, serializer, and file rotation are completely untested. Target 80%+ for 3.0.0.
264
+ 4. **Consider**: Breaking the provider options interface duplication to simplify maintenance.
@@ -0,0 +1,37 @@
1
+ # Test Plan: nestjs-logging Business Logic Coverage
2
+
3
+ **Date:** 2026-02-15
4
+ **Branch:** feat/monorepo-enterprise-upgrade
5
+ **Package:** `packages/nestjs-logging`
6
+
7
+ ## Target Coverage Areas
8
+
9
+ ### 1. LoggingInterceptor (`lib/interceptor/logging.interceptor.ts`)
10
+ - **Fix Verification**: Verify `structuredClone` is used (redacting metadata doesn't mutate original `req.body`).
11
+ - **Data Isolation**: Verify `query`, `params`, and `body` are logged into separate fields.
12
+ - **Error Handling**: Verify `error.stack` is captured when present.
13
+ - **Concurrency**: Verify `context` is correctly isolated between parallel requests.
14
+ - **Filtering**: Verify `@SkipAutoLogging()` decorator and `exclude` config work.
15
+
16
+ ### 2. ContextMiddleware & RequestContextService (`lib/middleware/`, `lib/context/`)
17
+ - **Request ID**: Verify `x-request-id` or `x-correlation-id` headers are used or generated.
18
+ - **Async Store**: Verify `RequestContextService.set/get` works across async boundaries.
19
+ - **Fastify Support**: Verify compatibility with `req.raw`.
20
+
21
+ ### 3. File Rotation Utility (`lib/util/file-rotation.utils.ts`)
22
+ - **Initialization**: Verify directory creation.
23
+ - **Rotation**: Verify `rotating-file-stream` is correctly configured with `maxFiles`, `size`, etc.
24
+
25
+ ### 4. Serializer (`lib/serialize/serializer.ts`)
26
+ - **Structure**: Verify `defaultSerializer` produces the expected nested object structure.
27
+
28
+ ## Test Strategy
29
+ - **Mode:** two-session-tdd
30
+ - **TDD Targets:**
31
+ - `packages/nestjs-logging/test/interceptor/logging.interceptor.spec.ts`
32
+ - `packages/nestjs-logging/test/middleware/context.middleware.spec.ts`
33
+ - `packages/nestjs-logging/test/util/file-rotation.spec.ts`
34
+
35
+ ## Commits
36
+ - Session 1: `test(nestjs-logging): add failing tests for interceptor, middleware, and utils`
37
+ - Session 2: `test(nestjs-logging): implement tests and verify business logic [ENH-8]`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-logging",
3
- "version": "2.1.4",
3
+ "version": "3.0.0-rc.4",
4
4
  "description": "nestjs-logging",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -28,7 +28,7 @@
28
28
  "winston-loki": "^6.1.3"
29
29
  },
30
30
  "peerDependencies": {
31
- "@nathapp/nestjs-common": "^2.1.1",
31
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
32
32
  "fast-redact": "^3.0.0",
33
33
  "pino": "^7.5.0 || ^8.0.0 || ^9.0.0",
34
34
  "rotating-file-stream": "^3.0.0",
@@ -55,7 +55,7 @@
55
55
  "lib": "lib"
56
56
  },
57
57
  "dependencies": {
58
- "@nathapp/nestjs-common": "^2.1.1",
58
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
59
59
  "fast-redact": "^3.0.0"
60
60
  }
61
61
  }