Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(logging): route Nest framework lines through the app logger
Yudhi Armyndharis7884f4d815cc
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex 9847dfcdd..77309ead5 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -1053,6 +1053,10 @@ defaulting to `json` under `NODE_ENV=production` and `pretty` elsewhere. Metadatlooks like a secret (password, token, api-key, authorization, …) keeps the key and has its **value**replaced with `[REDACTED]` before the line is written.+The same logger is installed as Nest's framework logger, so framework lines (route mapping, unhandled+exception stacks from the exception handler) follow `LOG_LEVEL` and `LOG_FORMAT` and carry the+request id like every other line; they are tagged `[OpenWA]` in pretty output, not `[Nest]`.+There is no in-app Loki transport: in the stack above, logs reach Loki because **promtail** scrapesthe container's stdout and stderr from `/var/lib/docker/containers`.diff --git a/eslint.config.mjs b/eslint.config.mjsindex c9fcbc425..c330cb499 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -4,6 +4,15 @@ import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'import globals from 'globals';import tseslint from 'typescript-eslint';+// Nest's Logger prints through its own ConsoleLogger until main.ts installs the app logger, and passes+// metadata objects on as the context name; createLogger() applies LOG_LEVEL, LOG_FORMAT, redaction and+// the request id everywhere. Shared with the controller block below, because a later block's+// no-restricted-syntax replaces this one's options instead of merging with them.+const NO_NEST_LOGGER = {+ selector: "NewExpression[callee.name='Logger']",+ message: 'Use createLogger() from common/services/logger.service instead of new Logger().',+};+export default tseslint.config({ignores: ['eslint.config.mjs'],@@ -32,6 +41,13 @@ export default tseslint.config("prettier/prettier": ["error", { endOfLine: "auto" }],},},+ {+ files: ['src/**/*.ts'],+ ignores: ['**/*.spec.ts'],+ rules: {+ 'no-restricted-syntax': ['error', NO_NEST_LOGGER],+ },+ },{// Architecture guard: HTTP controllers must go through a per-capability service and// never reach for the raw WhatsApp engine. This keeps the "session not started" guard,@@ -42,6 +58,7 @@ export default tseslint.config(rules: {'no-restricted-syntax': ['error',+ NO_NEST_LOGGER,{selector: "CallExpression[callee.property.name='getEngine']",message:diff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.tsindex 8def36d5b..97a68831a 100644--- a/src/common/services/logger.service.spec.ts+++ b/src/common/services/logger.service.spec.ts@@ -1,4 +1,8 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { ConsoleLogger, Logger } from '@nestjs/common';import { LoggerService, LogLevel, LogFormat, createLogger } from './logger.service';+import { runWithRequestId } from './request-context';interface LogEntry {timestamp: string;@@ -206,6 +210,85 @@ describe('LoggerService', () => {});});+ describe('non-string input (the call shapes Nest uses)', () => {+ it('renders an Error passed as the message with its stack as the trace', () => {+ const errorSpy = jest.spyOn(console, 'error');+ logger.error(new Error('boom'));++ const output = getLogOutput(errorSpy);+ expect(output.message).toBe('boom');+ expect(output.trace).toContain('Error: boom');+ expect(output.trace).toMatch(/\n\s+at /);+ });++ it('turns an Error or other value passed as the trace into a string', () => {+ const errorSpy = jest.spyOn(console, 'error');+ logger.error('failed', new Error('inner'));+ logger.error('failed', 42);++ const calls = errorSpy.mock.calls as string[][];+ expect((JSON.parse(calls[0][0]) as LogEntry).trace).toContain('Error: inner');+ expect((JSON.parse(calls[1][0]) as LogEntry).trace).toBe('42');+ });++ it('serializes an object message with secret-named keys redacted', () => {+ logger.log({ a: 1, password: 'p' });++ expect(getLogOutput(consoleSpy).message).toBe('{"a":1,"password":"[REDACTED]"}');+ });++ it('does not throw on a circular object message', () => {+ const circular: Record<string, unknown> = {};+ circular.self = circular;++ expect(() => logger.log(circular)).not.toThrow();+ expect(typeof getLogOutput(consoleSpy).message).toBe('string');+ });++ it('writes fatal() at error level', () => {+ const errorSpy = jest.spyOn(console, 'error');+ logger.fatal('down');++ const output = getLogOutput(errorSpy);+ expect(output.level).toBe('error');+ expect(output.message).toBe('down');+ });+ });++ describe('as the Nest framework logger', () => {+ beforeEach(() => {+ Logger.overrideLogger(createLogger('Nest'));+ });+ afterEach(() => {+ Logger.overrideLogger(new ConsoleLogger());+ });++ it("keeps the exception handler's message, stack, context and request id", () => {+ const errorSpy = jest.spyOn(console, 'error');+ runWithRequestId('req-1', () => new Logger('ExceptionsHandler').error(new Error('boom')));++ const output = getLogOutput(errorSpy) as LogEntry & { requestId?: string };+ expect(output.context).toBe('ExceptionsHandler');+ expect(output.message).toBe('boom');+ expect(output.trace).toContain('Error: boom');+ expect(output.requestId).toBe('req-1');+ });++ it('applies LOG_LEVEL to framework lines', () => {+ new Logger('X').debug('d');+ expect(consoleSpy).not.toHaveBeenCalled();++ new Logger('X').log('m');+ expect(getLogOutput(consoleSpy).context).toBe('X');+ });+ });++ // Without the option Nest keeps its ConsoleLogger, which ignores LOG_LEVEL and LOG_FORMAT.+ it('is installed as the framework logger by main.ts', () => {+ const mainSrc = readFileSync(join(__dirname, '..', '..', 'main.ts'), 'utf8');+ expect(mainSrc).toMatch(/await NestFactory\.create\(AppModule, \{[^}]*\blogger: createLogger\('Nest'\)/);+ });+describe('createLogger', () => {it('should create logger with context', () => {const testLogger = createLogger('MyContext');diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.tsindex 05c1f8046..0b7b94217 100644--- a/src/common/services/logger.service.ts+++ b/src/common/services/logger.service.ts@@ -39,6 +39,15 @@ function redactSecrets(value: unknown, depth = 0): unknown {return out;}+/** A non-string, non-Error message as one line of text (redacted like metadata, never throwing). */+function stringifyMessage(message: unknown): string {+ try {+ return JSON.stringify(redactSecrets(message)) ?? String(message);+ } catch {+ return String(message);+ }+}+// ANSI color codes — mirrors the palette NestJS's built-in ConsoleLogger uses so our// pretty output blends in with the framework's own `[Nest] … LOG [Context]` lines.const ANSI = {@@ -91,29 +100,48 @@ export class LoggerService implements NestLoggerService {this.context = context;}- log(message: string, context?: string | LogContext): void {+ // Messages and traces are `unknown` because this is also Nest's framework logger (main.ts), and Nest+ // passes the thrown Error itself as the message of an unhandled-exception line; writeLog normalizes.+ log(message: unknown, context?: string | LogContext): void {this.writeLog(LogLevel.INFO, message, context);}- error(message: string, trace?: string, context?: string | LogContext): void {+ error(message: unknown, trace?: unknown, context?: string | LogContext): void {this.writeLog(LogLevel.ERROR, message, context, trace);}- warn(message: string, context?: string | LogContext): void {+ fatal(message: unknown, context?: string | LogContext): void {+ this.writeLog(LogLevel.ERROR, message, context);+ }++ warn(message: unknown, context?: string | LogContext): void {this.writeLog(LogLevel.WARN, message, context);}- debug(message: string, context?: string | LogContext): void {+ debug(message: unknown, context?: string | LogContext): void {this.writeLog(LogLevel.DEBUG, message, context);}- verbose(message: string, context?: string | LogContext): void {+ verbose(message: unknown, context?: string | LogContext): void {this.writeLog(LogLevel.VERBOSE, message, context);}- private writeLog(level: LogLevel, message: string, context?: string | LogContext, trace?: string): void {+ private writeLog(level: LogLevel, rawMessage: unknown, context?: string | LogContext, rawTrace?: unknown): void {if (!this.shouldLog(level)) return;+ // An Error serializes to `{}`, so take its message and stack apart instead of losing both.+ if (rawMessage instanceof Error) {+ rawTrace ??= rawMessage.stack;+ rawMessage = rawMessage.message;+ }+ const message = typeof rawMessage === 'string' ? rawMessage : stringifyMessage(rawMessage);+ const trace =+ rawTrace === undefined || typeof rawTrace === 'string'+ ? rawTrace+ : rawTrace instanceof Error+ ? (rawTrace.stack ?? rawTrace.message)+ : stringifyMessage(rawTrace);+const timestamp = new Date().toISOString();const contextName = typeof context === 'string' ? context : this.context;const metadata =diff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.tsindex 04b9cd0c8..af3f5be4a 100644--- a/src/core/hooks/hook-manager.service.ts+++ b/src/core/hooks/hook-manager.service.ts@@ -1,4 +1,5 @@-import { Injectable, Logger } from '@nestjs/common';+import { Injectable } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import { AsyncLocalStorage } from 'node:async_hooks';import { HookEvent, HookHandler, HookContext, HookRegistration } from './hook.interfaces';@@ -21,7 +22,7 @@ export interface HookExecuteOptions<T> {@Injectable()export class HookManager {- private readonly logger = new Logger(HookManager.name);+ private readonly logger = createLogger(HookManager.name);private readonly hooks = new Map<HookEvent, HookRegistration[]>();private readonly pluginHooks = new Map<string, Set<string>>(); // pluginId -> hookIds// Events in-flight on the active async context. A handler that re-fires the SAME eventdiff --git a/src/database/sqlite-file-permissions.ts b/src/database/sqlite-file-permissions.tsindex 19d298de3..d03b286a5 100644--- a/src/database/sqlite-file-permissions.ts+++ b/src/database/sqlite-file-permissions.ts@@ -1,5 +1,6 @@import { chmodSync, existsSync } from 'fs';-import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';+import { Injectable, OnApplicationBootstrap } from '@nestjs/common';+import { createLogger } from '../common/services/logger.service';import { ConfigService } from '@nestjs/config';// better-sqlite3 creates its database files with 0666 & umask (0644 under the usual 022), so the@@ -44,7 +45,7 @@ export function tightenSqliteFilePermissions(paths: string[], warn: (message: st*/@Injectable()export class SqlitePermissionsBoot implements OnApplicationBootstrap {- private readonly logger = new Logger('SqlitePermissions');+ private readonly logger = createLogger('SqlitePermissions');constructor(private readonly config: ConfigService) {}diff --git a/src/main.ts b/src/main.tsindex 07c01bf6b..610ab538d 100644--- a/src/main.ts+++ b/src/main.ts@@ -122,8 +122,10 @@ async function bootstrap() {// must be started before it, not from DockerService.onModuleInit (see the helper).await prestartBuiltinDatabase();- // Disable Nest's default body parser so we can set an explicit size cap below.- const app = await NestFactory.create(AppModule, { bodyParser: false });+ // Disable Nest's default body parser so we can set an explicit size cap below. Framework lines+ // (route mapping, unhandled-exception stacks) go through the app logger so LOG_LEVEL, LOG_FORMAT and+ // the request id apply to them too.+ const app = await NestFactory.create(AppModule, { bodyParser: false, logger: createLogger('Nest') });appInstance = app;// Cross-replica WebSocket fan-out: when Redis is enabled, broadcasts reach clients on everydiff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 923ce93b8..6221ff1c0 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -1,4 +1,5 @@-import { Injectable, Logger, OnModuleInit } from '@nestjs/common';+import { Injectable, OnModuleInit } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import Docker from 'dockerode';import { isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';import { readGeneratedEnv } from '../infra/generated-env';@@ -28,7 +29,7 @@ interface OrchestrationResult {@Injectable()export class DockerService implements OnModuleInit {- private readonly logger = new Logger(DockerService.name);+ private readonly logger = createLogger(DockerService.name);private docker: Docker | null = null;private isAvailable = false;private reinitInFlight = false;@@ -93,10 +94,9 @@ export class DockerService implements OnModuleInit {this.isAvailable = true;this.logger.log('Docker API connected successfully');} catch (error) {- this.logger.warn(- 'Docker not available. Container orchestration disabled.',- error instanceof Error ? error.message : error,- );+ this.logger.warn('Docker not available. Container orchestration disabled.', {+ error: error instanceof Error ? error.message : String(error),+ });this.isAvailable = false;}}@@ -640,7 +640,7 @@ export async function prestartBuiltinDatabase(timeoutMs = 15_000,): Promise<void> {if (env.DATABASE_TYPE !== 'postgres' || env.POSTGRES_BUILTIN !== 'true') return;- const logger = new Logger('DockerService');+ const logger = createLogger('DockerService');let timer: NodeJS.Timeout | undefined;const deadline = new Promise<void>(resolve => {timer = setTimeout(() => {diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex d1f244214..f5d2ea9ce 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -9,7 +9,8 @@ import {ConnectedSocket,} from '@nestjs/websockets';import { Server, Socket } from 'socket.io';-import { Logger, OnModuleDestroy } from '@nestjs/common';+import { OnModuleDestroy } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import { ConfigService } from '@nestjs/config';import { AuthService } from '../auth/auth.service';import { AuditService } from '../audit/audit.service';@@ -117,7 +118,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate@WebSocketServer()server!: Server;- private logger = new Logger('EventsGateway');+ private logger = createLogger('EventsGateway');/*** Active sockets keyed by their validating API-key id, so a key revoked/disableddiff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex 6af8f3af6..ae7956950 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -1,4 +1,5 @@-import { ForbiddenException, HttpException, Logger, UnauthorizedException } from '@nestjs/common';+import { ForbiddenException, HttpException, UnauthorizedException } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import type { HttpAdapterHost } from '@nestjs/core';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import type { AnySchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';@@ -17,7 +18,7 @@ import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';import { resolveBodyLimit } from '../../config/bootstrap-security';import { bearerToken } from '../../common/security/bearer-token';-const logger = new Logger('McpServer');+const logger = createLogger('McpServer');type HttpAdapter = NonNullable<HttpAdapterHost['httpAdapter']>;type ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;diff --git a/src/modules/mcp/tool-result.ts b/src/modules/mcp/tool-result.tsindex 3fa60d54b..ff7e3ab47 100644--- a/src/modules/mcp/tool-result.ts+++ b/src/modules/mcp/tool-result.ts@@ -1,8 +1,9 @@import { randomUUID } from 'node:crypto';-import { HttpException, Logger } from '@nestjs/common';+import { HttpException } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';-const logger = new Logger('Mcp');+const logger = createLogger('Mcp');/*** Format a tool result, inlining small payloads as text and offloading largediff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex d4987e31d..b711027bf 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -1,5 +1,6 @@import { Test, TestingModule } from '@nestjs/testing';-import { BadRequestException, HttpException, Logger, PayloadTooLargeException } from '@nestjs/common';+import { BadRequestException, HttpException, PayloadTooLargeException } from '@nestjs/common';+import { LoggerService } from '../../common/services/logger.service';import { getRepositoryToken } from '@nestjs/typeorm';import { In, Not } from 'typeorm';import {@@ -124,7 +125,7 @@ describe('BulkMessageService.onApplicationBootstrap', () => {repo.update.mockImplementation((where: { id: string }) =>Promise.resolve({ affected: where.id === 'b-dead' ? 1 : 0 }),);- const warn = jest.spyOn((service as unknown as { logger: Logger }).logger, 'warn').mockImplementation();+ const warn = jest.spyOn((service as unknown as { logger: LoggerService }).logger, 'warn').mockImplementation();await service.onApplicationBootstrap();diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 1e247127c..2e6003294 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -1,11 +1,5 @@-import {- Injectable,- Logger,- BadRequestException,- NotFoundException,- Optional,- OnApplicationBootstrap,-} from '@nestjs/common';+import { Injectable, BadRequestException, NotFoundException, Optional, OnApplicationBootstrap } from '@nestjs/common';+import { createLogger } from '../../common/services/logger.service';import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';@@ -103,7 +97,7 @@ interface BatchExecutionState {@Injectable()export class BulkMessageService implements OnApplicationBootstrap {- private readonly logger = new Logger(BulkMessageService.name);+ private readonly logger = createLogger(BulkMessageService.name);private readonly processingBatches = new Map<string, boolean>(); // Track active batches for cancellationprivate inFlightBatches = 0; // count of batches currently in processBatch (memory bound, see cap above)diff --git a/src/modules/search/providers/builtin-fts.provider.postgres.spec.ts b/src/modules/search/providers/builtin-fts.provider.postgres.spec.tsindex 5864ed145..ec14f24b2 100644--- a/src/modules/search/providers/builtin-fts.provider.postgres.spec.ts+++ b/src/modules/search/providers/builtin-fts.provider.postgres.spec.ts@@ -1,5 +1,6 @@import 'reflect-metadata';-import { Logger, NotImplementedException } from '@nestjs/common';+import { NotImplementedException } from '@nestjs/common';+import { LoggerService } from '../../../common/services/logger.service';import { DataSource } from 'typeorm';import { BuiltInFtsProvider } from './builtin-fts.provider';@@ -49,12 +50,12 @@ function makePostgresDataSource(script: ProbeScript) {const sqlOf = (query: jest.Mock): string[] => query.mock.calls.map(call => String((call as unknown[])[0]));describe('BuiltInFtsProvider (postgres probe)', () => {- // The provider logs through Nest's Logger on the warn/error paths exercised here; keep the test+ // The provider logs through LoggerService on the warn/error paths exercised here; keep the test// output quiet without touching the assertions.beforeEach(() => {- jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);- jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);- jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);+ jest.spyOn(LoggerService.prototype, 'log').mockImplementation(() => undefined);+ jest.spyOn(LoggerService.prototype, 'warn').mockImplementation(() => undefined);+ jest.spyOn(LoggerService.prototype, 'error').mockImplementation(() => undefined);});afterEach(() => jest.restoreAllMocks());diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsindex 20d5f9a2f..4a6eee06e 100644--- a/src/modules/search/providers/builtin-fts.provider.ts+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -1,4 +1,5 @@-import { BadRequestException, Injectable, Logger, NotImplementedException, OnModuleInit } from '@nestjs/common';+import { BadRequestException, Injectable, NotImplementedException, OnModuleInit } from '@nestjs/common';+import { createLogger } from '../../../common/services/logger.service';import { InjectDataSource } from '@nestjs/typeorm';import { DataSource } from 'typeorm';import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';@@ -38,7 +39,7 @@ type PlaceholderFn = () => string;export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {readonly id = 'builtin-fts';readonly label = 'Built-in database full-text search';- private readonly logger = new Logger('BuiltInFtsProvider');+ private readonly logger = createLogger('BuiltInFtsProvider');// OpenWA has two TypeORM connections (main: auth/audit SQLite, data: messages). Bind explicitly to// 'data' so the provider queries the connection that owns the `messages` table + the FTS migration,