Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(logger): add human-readable logging format and enhance LoggerSer… (#470)
محفوظ340bd8edeae1
diff --git a/.env.example b/.env.exampleindex 477c35d6f..9ef425c98 100644--- a/.env.example+++ b/.env.example@@ -10,6 +10,9 @@NODE_ENV=productionAPI_PORT=2785LOG_LEVEL=info # error | warn | info | debug+# Console output format. Default: json in production (containers, log aggregators),+# human-readable pretty otherwise. Force one with: json | pretty+# LOG_FORMAT=pretty# Auto-start previously authenticated sessions on server bootAUTO_START_SESSIONS=falsediff --git a/CHANGELOG.md b/CHANGELOG.mdindex be0c38ff0..c22f20cf5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- Human-readable console logs: the `LoggerService` now renders a colorized, NestJS-style line (`[OpenWA] <pid> - <timestamp> <LEVEL> [Context] <message>` with dimmed `key=value` metadata and stack traces on their own line) instead of always emitting raw JSON, so application logs line up visually with NestJS's own framework logs. The format defaults to structured JSON in production (`NODE_ENV=production`, for containers and log aggregators) and human-readable pretty everywhere else, and can be pinned with `LOG_FORMAT=pretty|json`. `NO_COLOR` / `FORCE_COLOR` are honored. JSON output is byte-for-byte unchanged when selected. (#469)+## [0.7.6] - 2026-06-26### Changeddiff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.tsindex bcc68eeef..154da06f2 100644--- a/src/common/services/logger.service.spec.ts+++ b/src/common/services/logger.service.spec.ts@@ -1,4 +1,4 @@-import { LoggerService, LogLevel, createLogger } from './logger.service';+import { LoggerService, LogLevel, LogFormat, createLogger } from './logger.service';interface LogEntry {timestamp: string;@@ -16,6 +16,12 @@ function getLogOutput(spy: jest.SpyInstance): LogEntry {return JSON.parse(calls[0][0]) as LogEntry;}+// Helper to read the raw (unparsed) string a spy was called with.+function getRawOutput(spy: jest.SpyInstance): string {+ const calls = spy.mock.calls as string[][];+ return calls[0][0];+}+describe('LoggerService', () => {let logger: LoggerService;let consoleSpy: jest.SpyInstance;@@ -23,6 +29,8 @@ describe('LoggerService', () => {beforeEach(() => {logger = new LoggerService();logger.setContext('TestContext');+ // Pin JSON so structured-output assertions are deterministic regardless of TTY/LOG_FORMAT.+ LoggerService.setLogFormat(LogFormat.JSON);consoleSpy = jest.spyOn(console, 'log').mockImplementation();jest.spyOn(console, 'warn').mockImplementation();jest.spyOn(console, 'error').mockImplementation();@@ -30,6 +38,8 @@ describe('LoggerService', () => {afterEach(() => {jest.restoreAllMocks();+ LoggerService.setLogFormat(null);+ LoggerService.setLogLevel(LogLevel.INFO);});describe('log', () => {@@ -94,6 +104,44 @@ describe('LoggerService', () => {});});+ describe('pretty format', () => {+ beforeEach(() => {+ LoggerService.setLogFormat(LogFormat.PRETTY);+ });++ it('should render a NestJS-style human-readable line instead of JSON', () => {+ logger.log('Test message');++ const output = getRawOutput(consoleSpy);+ // Not JSON.+ expect(() => {+ JSON.parse(output);+ }).toThrow();+ // NestJS-style prefix, level label, context and message all present.+ expect(output).toContain('[OpenWA]');+ expect(output).toContain('LOG');+ expect(output).toContain('[TestContext]');+ expect(output).toContain('Test message');+ });++ it('should append metadata as key=value pairs', () => {+ logger.log('Test message', { sessionId: '123', action: 'test' });++ const output = getRawOutput(consoleSpy);+ expect(output).toContain('sessionId=123');+ expect(output).toContain('action=test');+ });++ it('should append the stack trace on a new line for errors', () => {+ const errorSpy = jest.spyOn(console, 'error');+ logger.error('Error message', 'stack trace line');++ const output = getRawOutput(errorSpy);+ expect(output).toContain('Error message');+ expect(output).toContain('\nstack trace line');+ });+ });+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 0f4e02916..8ed1f33f2 100644--- a/src/common/services/logger.service.ts+++ b/src/common/services/logger.service.ts@@ -8,6 +8,11 @@ export enum LogLevel {VERBOSE = 'verbose',}+export enum LogFormat {+ JSON = 'json',+ PRETTY = 'pretty',+}+export interface LogContext {sessionId?: string;messageId?: string;@@ -17,15 +22,54 @@ export interface LogContext {[key: string]: unknown;}+// 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 = {+ reset: '\x1b[0m',+ dim: '\x1b[2m',+ red: '\x1b[31m',+ green: '\x1b[32m',+ yellow: '\x1b[33m',+ magenta: '\x1b[35m',+ cyan: '\x1b[36m',+} as const;++const LEVEL_COLOR: Record<LogLevel, string> = {+ [LogLevel.ERROR]: ANSI.red,+ [LogLevel.WARN]: ANSI.yellow,+ [LogLevel.INFO]: ANSI.green,+ [LogLevel.DEBUG]: ANSI.magenta,+ [LogLevel.VERBOSE]: ANSI.cyan,+};++// NestJS prints `info` as `LOG`; match its labels so both log sources line up.+const LEVEL_LABEL: Record<LogLevel, string> = {+ [LogLevel.ERROR]: 'ERROR',+ [LogLevel.WARN]: 'WARN',+ [LogLevel.INFO]: 'LOG',+ [LogLevel.DEBUG]: 'DEBUG',+ [LogLevel.VERBOSE]: 'VERBOSE',+};++// Keys that are rendered in the line prefix rather than the trailing metadata.+const STRUCTURAL_KEYS = new Set(['timestamp', 'level', 'context', 'message', 'trace']);+@Injectable({ scope: Scope.TRANSIENT })export class LoggerService implements NestLoggerService {private context: string = 'Application';private static logLevel: LogLevel = LogLevel.INFO;+ private static logFormat: LogFormat | null = null;static setLogLevel(level: LogLevel): void {LoggerService.logLevel = level;}+ // Explicitly pin the output format. When unset, the format is resolved from+ // LOG_FORMAT / TTY detection (see resolveFormat).+ static setLogFormat(format: LogFormat | null): void {+ LoggerService.logFormat = format;+ }+setContext(context: string): void {this.context = context;}@@ -56,7 +100,7 @@ export class LoggerService implements NestLoggerService {const timestamp = new Date().toISOString();const contextName = typeof context === 'string' ? context : this.context;- const metadata = typeof context === 'object' ? context : {};+ const metadata = typeof context === 'object' && context !== null ? context : {};const logEntry = {timestamp,@@ -66,8 +110,10 @@ export class LoggerService implements NestLoggerService {...metadata,};- // Output as JSON for structured logging (easy to parse by log aggregators)- const output = JSON.stringify(logEntry);+ const output =+ LoggerService.resolveFormat() === LogFormat.PRETTY+ ? this.formatPretty(level, logEntry)+ : JSON.stringify(logEntry);switch (level) {case LogLevel.ERROR:@@ -81,6 +127,64 @@ export class LoggerService implements NestLoggerService {}}+ // Render a single entry as a human-readable line in the same shape NestJS's ConsoleLogger uses+ // (so it lines up with the framework's own output), but tagged honestly as [OpenWA]:+ // [OpenWA] 1896 - 25/06/2026, 4:59:22 PM LOG [AuthService] API Docs: … sessionId=abc+ private formatPretty(level: LogLevel, entry: Record<string, unknown>): string {+ const useColor = LoggerService.colorEnabled();+ const paint = (code: string, text: string): string => (useColor ? `${code}${text}${ANSI.reset}` : text);++ const levelColor = LEVEL_COLOR[level];+ const label = LEVEL_LABEL[level].padStart(7);+ const timestamp = new Date(String(entry.timestamp)).toLocaleString();+ const contextName = String(entry.context);+ const message = String(entry.message);++ // Trailing structured metadata (sessionId, action, duration, …) shown dimmed as key=value pairs.+ const formatValue = (value: unknown): string => (typeof value === 'string' ? value : (JSON.stringify(value) ?? ''));+ const meta = Object.entries(entry)+ .filter(([key, value]) => !STRUCTURAL_KEYS.has(key) && value !== undefined)+ .map(([key, value]) => `${key}=${formatValue(value)}`)+ .join(' ');++ let line =+ `${paint(levelColor, `[OpenWA] ${process.pid} -`)} ${timestamp} ` ++ `${paint(levelColor, label)} ${paint(ANSI.yellow, `[${contextName}]`)} ${paint(levelColor, message)}`;++ if (meta) {+ line += ` ${paint(ANSI.dim, meta)}`;+ }++ // Error stack traces print on their own line(s), like NestJS.+ if (typeof entry.trace === 'string' && entry.trace) {+ line += `\n${paint(levelColor, entry.trace)}`;+ }++ return line;+ }++ private static resolveFormat(): LogFormat {+ if (LoggerService.logFormat) return LoggerService.logFormat;++ const explicit = process.env.LOG_FORMAT?.trim().toLowerCase();+ if (explicit === LogFormat.JSON || explicit === LogFormat.PRETTY) {+ return explicit;+ }++ // No explicit choice: structured JSON in production (containers, log aggregators),+ // human-readable pretty everywhere else. This mirrors NestJS's own logger, which+ // always prints its text format — and unlike a TTY check it stays correct when+ // stdout is piped through a dev runner (e.g. `concurrently` in `npm run dev`).+ return process.env.NODE_ENV === 'production' ? LogFormat.JSON : LogFormat.PRETTY;+ }++ private static colorEnabled(): boolean {+ // Honor the de-facto NO_COLOR / FORCE_COLOR conventions; otherwise colorize only a real TTY.+ if (process.env.NO_COLOR) return false;+ if (process.env.FORCE_COLOR) return true;+ return Boolean(process.stdout.isTTY);+ }+private shouldLog(level: LogLevel): boolean {const levels = [LogLevel.ERROR, LogLevel.WARN, LogLevel.INFO, LogLevel.DEBUG, LogLevel.VERBOSE];const currentIndex = levels.indexOf(LoggerService.logLevel);