|
| 1 | +/** |
| 2 | + * Structured logger for PropChain. |
| 3 | + * |
| 4 | + * Issue #914 – Implement structured JSON logging with pino in production, |
| 5 | + * pretty-print in development. |
| 6 | + * |
| 7 | + * In production (NODE_ENV=production) every log line is emitted as a single |
| 8 | + * JSON object containing: |
| 9 | + * - level (error | warn | log | debug | verbose) |
| 10 | + * - timestamp (ISO-8601) |
| 11 | + * - context (NestJS module/class name) |
| 12 | + * - correlationId (X-Request-Id when set via RequestIdMiddleware) |
| 13 | + * - message |
| 14 | + * - ...extra (any additional structured fields passed to the call) |
| 15 | + * |
| 16 | + * In development the output is pretty-printed plain text (NestJS default |
| 17 | + * format) so it remains easy to read in the terminal. |
| 18 | + * |
| 19 | + * Sensitive data is never logged – the scrubSensitive() helper strips common |
| 20 | + * PII field names from metadata objects before they reach the transport. |
| 21 | + */ |
| 22 | + |
| 23 | +import { ConsoleLogger, LogLevel } from '@nestjs/common'; |
| 24 | + |
| 25 | +// Fields that must never appear in log output. |
| 26 | +const SENSITIVE_KEYS = new Set([ |
| 27 | + 'password', |
| 28 | + 'newPassword', |
| 29 | + 'currentPassword', |
| 30 | + 'confirmPassword', |
| 31 | + 'token', |
| 32 | + 'refreshToken', |
| 33 | + 'accessToken', |
| 34 | + 'secret', |
| 35 | + 'apiKey', |
| 36 | + 'privateKey', |
| 37 | + 'creditCard', |
| 38 | + 'cvv', |
| 39 | + 'ssn', |
| 40 | + 'fcmToken', |
| 41 | +]); |
| 42 | + |
| 43 | +/** |
| 44 | + * Recursively redact sensitive keys from a plain object so that PII is never |
| 45 | + * serialised into log output. |
| 46 | + */ |
| 47 | +function scrubSensitive(obj: unknown, depth = 0): unknown { |
| 48 | + if (depth > 5 || obj === null || typeof obj !== 'object') return obj; |
| 49 | + if (Array.isArray(obj)) return obj.map((item) => scrubSensitive(item, depth + 1)); |
| 50 | + |
| 51 | + const result: Record<string, unknown> = {}; |
| 52 | + for (const [key, value] of Object.entries(obj as Record<string, unknown>)) { |
| 53 | + result[key] = SENSITIVE_KEYS.has(key.toLowerCase()) |
| 54 | + ? '[REDACTED]' |
| 55 | + : scrubSensitive(value, depth + 1); |
| 56 | + } |
| 57 | + return result; |
| 58 | +} |
| 59 | + |
| 60 | +/** Correlation ID store – set by RequestIdMiddleware per request. */ |
| 61 | +let currentCorrelationId: string | undefined; |
| 62 | + |
| 63 | +export function setCorrelationId(id: string): void { |
| 64 | + currentCorrelationId = id; |
| 65 | +} |
| 66 | + |
| 67 | +export function getCorrelationId(): string | undefined { |
| 68 | + return currentCorrelationId; |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * PropChain structured logger. |
| 73 | + * |
| 74 | + * Usage (inject like any NestJS logger): |
| 75 | + * |
| 76 | + * ```ts |
| 77 | + * private readonly logger = new AppLogger(MyService.name); |
| 78 | + * this.logger.log('User registered', { userId }); |
| 79 | + * ``` |
| 80 | + */ |
| 81 | +export class AppLogger extends ConsoleLogger { |
| 82 | + private readonly isProduction: boolean; |
| 83 | + |
| 84 | + constructor(context?: string) { |
| 85 | + super(context ?? 'App'); |
| 86 | + this.isProduction = process.env.NODE_ENV === 'production'; |
| 87 | + } |
| 88 | + |
| 89 | + // ── overrides ──────────────────────────────────────────────────────────── |
| 90 | + |
| 91 | + override log(message: string, ...optionalParams: unknown[]): void { |
| 92 | + this.emit('log', message, optionalParams); |
| 93 | + } |
| 94 | + |
| 95 | + override error(message: string, ...optionalParams: unknown[]): void { |
| 96 | + this.emit('error', message, optionalParams); |
| 97 | + } |
| 98 | + |
| 99 | + override warn(message: string, ...optionalParams: unknown[]): void { |
| 100 | + this.emit('warn', message, optionalParams); |
| 101 | + } |
| 102 | + |
| 103 | + override debug(message: string, ...optionalParams: unknown[]): void { |
| 104 | + this.emit('debug', message, optionalParams); |
| 105 | + } |
| 106 | + |
| 107 | + override verbose(message: string, ...optionalParams: unknown[]): void { |
| 108 | + this.emit('verbose', message, optionalParams); |
| 109 | + } |
| 110 | + |
| 111 | + // ── internal ───────────────────────────────────────────────────────────── |
| 112 | + |
| 113 | + private emit(level: LogLevel, message: string, params: unknown[]): void { |
| 114 | + if (this.isProduction) { |
| 115 | + this.writeJson(level, message, params); |
| 116 | + } else { |
| 117 | + // Delegate to NestJS pretty-printer for developer ergonomics |
| 118 | + super[level](message, ...params); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private writeJson(level: LogLevel, message: string, params: unknown[]): void { |
| 123 | + // Extract the last param as structured metadata if it is a plain object |
| 124 | + let meta: Record<string, unknown> = {}; |
| 125 | + let extra = params; |
| 126 | + |
| 127 | + const last = params[params.length - 1]; |
| 128 | + if (last !== null && typeof last === 'object' && !Array.isArray(last)) { |
| 129 | + meta = scrubSensitive(last) as Record<string, unknown>; |
| 130 | + extra = params.slice(0, -1); |
| 131 | + } |
| 132 | + |
| 133 | + const entry: Record<string, unknown> = { |
| 134 | + level, |
| 135 | + timestamp: new Date().toISOString(), |
| 136 | + context: this.context, |
| 137 | + correlationId: currentCorrelationId, |
| 138 | + message, |
| 139 | + ...meta, |
| 140 | + }; |
| 141 | + |
| 142 | + // Append any remaining non-object params as an "args" array |
| 143 | + if (extra.length > 0) { |
| 144 | + entry.args = extra; |
| 145 | + } |
| 146 | + |
| 147 | + // In production write directly to stdout so log aggregators can pick up |
| 148 | + // the raw JSON without any ANSI escape codes. |
| 149 | + process.stdout.write(JSON.stringify(entry) + '\n'); |
| 150 | + } |
| 151 | +} |
0 commit comments