diff --git a/.env.example b/.env.example index e97c15a..42d42c6 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,9 @@ # NODE_ENV=development # PORT=3000 +## Application log output: console (default) or debug (controlled by DEBUG namespaces) +# LOG_MODE=console + ## Optional account authentication (disabled unless explicitly enabled) # AUTH_ENABLED=true ## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control. diff --git a/docs/development.md b/docs/development.md index 5c5d578..252cf4b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,6 +30,7 @@ All settings are validated at startup by `server/src/config/app.config.ts`. | `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins | | `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) | | `PORT` | `3000` | HTTP port | +| `LOG_MODE` | `console` | `console` preserves the default server output; `debug` routes application diagnostics through the `debug` package and only emits namespaces enabled by `DEBUG` (for example, `DEBUG=liqa:*`). | | `DB_PATH` | `data/liqa.db` | SQLite database file | | `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored | | `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept | @@ -191,7 +192,7 @@ Watch mode: npm -w server run test:watch ``` -Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`): +Server application logs use debug output during tests. They remain quiet unless the `test` namespace is enabled. To see NestJS and application logs: ```bash npm -w server run test:debug diff --git a/package-lock.json b/package-lock.json index 56fe5be..58414c0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17464,6 +17464,7 @@ "better-sqlite3": "^12.8.0", "class-transformer": "^0.5.1", "class-validator": "^0.14.4", + "debug": "^4.4.3", "effect": "^3.21.0", "jsdom": "^29.0.2", "playwright": "^1.59.1", @@ -17487,7 +17488,6 @@ "@types/mozilla__readability": "^0.4.2", "@types/node": "^25.5.2", "@types/supertest": "^7.2.0", - "debug": "^4.4.3", "eslint": "^10.2.0", "eslint-config-prettier": "^10.1.8", "jest": "^30.3.0", diff --git a/server/jest.config.js b/server/jest.config.js index 9d58577..046091f 100644 --- a/server/jest.config.js +++ b/server/jest.config.js @@ -6,6 +6,7 @@ module.exports = { transform: { '^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }], }, + setupFiles: ['/test/logging.setup.js'], moduleNameMapper: { '^jsdom$': '/test/__mocks__/jsdom.ts', '^playwright$': '/test/__mocks__/playwright.ts', diff --git a/server/package.json b/server/package.json index 97797d3..b771842 100644 --- a/server/package.json +++ b/server/package.json @@ -38,6 +38,7 @@ "better-sqlite3": "^12.8.0", "class-transformer": "^0.5.1", "class-validator": "^0.14.4", + "debug": "^4.4.3", "effect": "^3.21.0", "jsdom": "^29.0.2", "playwright": "^1.59.1", @@ -61,7 +62,6 @@ "@types/mozilla__readability": "^0.4.2", "@types/node": "^25.5.2", "@types/supertest": "^7.2.0", - "debug": "^4.4.3", "eslint": "^10.2.0", "eslint-config-prettier": "^10.1.8", "jest": "^30.3.0", diff --git a/server/src/common/trace-logger.ts b/server/src/common/trace-logger.ts index e27980e..0edabb6 100644 --- a/server/src/common/trace-logger.ts +++ b/server/src/common/trace-logger.ts @@ -1,9 +1,108 @@ import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common"; +// eslint-disable-next-line @typescript-eslint/no-require-imports +import createDebug = require("debug"); import { getTraceId } from "./trace-context"; +import { LogMode } from "../config/app.config"; export class TraceLogger extends ConsoleLogger { + private readonly loggerContext: string; + constructor(context?: string, options: ConsoleLoggerOptions = {}) { super(context as string, options); + this.loggerContext = context ?? "Application"; + } + + override log(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("log", message, optionalParams); + return; + } + super.log(...args); + } + + override error(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("error", message, optionalParams); + return; + } + super.error(...args); + } + + override warn(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("warn", message, optionalParams); + return; + } + super.warn(...args); + } + + override debug(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("debug", message, optionalParams); + return; + } + super.debug(...args); + } + + override verbose(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("verbose", message, optionalParams); + return; + } + super.verbose(...args); + } + + override fatal(...args: Parameters): void { + if (this.useDebugOutput()) { + const [message, ...optionalParams] = args; + this.writeDebug("fatal", message, optionalParams); + return; + } + super.fatal(...args); + } + + private useDebugOutput(): boolean { + return process.env.LOG_MODE === LogMode.Debug; + } + + private writeDebug( + level: LogLevel, + message: unknown, + optionalParams: unknown[], + ): void { + const last = optionalParams[optionalParams.length - 1]; + const lastIsErrorStack = + level === "error" && + optionalParams.length === 1 && + typeof last === "string" && + /(?:\n|^\s*at\s)/.test(last); + const context = + typeof last === "string" && !lastIsErrorStack + ? last + : this.loggerContext; + const details = + typeof last === "string" && !lastIsErrorStack + ? optionalParams.slice(0, -1) + : optionalParams; + const traceId = getTraceId(); + const tracedContext = traceId ? `${context}:${traceId}` : context; + const namespace = + process.env.NODE_ENV === "test" + ? "test" + : `liqa:${context.toLowerCase()}`; + const messageText = this.stringifyMessage(message, level); + const detailText = details + .map((detail) => this.stringifyMessage(detail, level)) + .filter(Boolean) + .join(" "); + const output = `[${level.toUpperCase()}] [${tracedContext}] ${messageText}${detailText ? ` ${detailText}` : ""}`; + + createDebug(namespace)("%s", output); } protected override getTimestamp(): string { diff --git a/server/src/config/app.config.ts b/server/src/config/app.config.ts index ad7b278..61e1151 100644 --- a/server/src/config/app.config.ts +++ b/server/src/config/app.config.ts @@ -20,6 +20,11 @@ export enum TraceMode { Off = "off", } +export enum LogMode { + Console = "console", + Debug = "debug", +} + export class AppConfig { /** `production` in the Docker image; also selects the default CORS origins. */ @IsString() @@ -40,6 +45,10 @@ export class AppConfig { @IsString() APP_VERSION: string = appPackage().version; + /** Route application diagnostics through `debug` instead of the console. */ + @IsEnum(LogMode) + LOG_MODE: LogMode = LogMode.Console; + @IsString() DB_PATH: string = "data/liqa.db"; diff --git a/server/test/auth-config.spec.ts b/server/test/auth-config.spec.ts index 4e19c7d..a663d0d 100644 --- a/server/test/auth-config.spec.ts +++ b/server/test/auth-config.spec.ts @@ -1,5 +1,5 @@ import "reflect-metadata"; -import { validateAppConfig } from "../src/config/app.config"; +import { LogMode, validateAppConfig } from "../src/config/app.config"; import { durationSeconds } from "../src/common/interval"; describe("Authentication configuration", () => { @@ -12,6 +12,17 @@ describe("Authentication configuration", () => { expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *"); }); + it("defaults to console logging and accepts debug logging", () => { + expect(validateAppConfig({}).LOG_MODE).toBe(LogMode.Console); + expect(validateAppConfig({ LOG_MODE: "debug" }).LOG_MODE).toBe( + LogMode.Debug, + ); + }); + + it("rejects unsupported logging modes", () => { + expect(() => validateAppConfig({ LOG_MODE: "silent" })).toThrow(); + }); + it("parses explicit true and false values without JavaScript truthiness", () => { expect(validateAppConfig({ AUTH_ENABLED: "false" }).AUTH_ENABLED).toBe( false, diff --git a/server/test/logging.setup.js b/server/test/logging.setup.js new file mode 100644 index 0000000..22cffa7 --- /dev/null +++ b/server/test/logging.setup.js @@ -0,0 +1,2 @@ +// Application logs should stay quiet during tests unless DEBUG enables them. +process.env.LOG_MODE = 'debug'; diff --git a/server/test/trace-logger.spec.ts b/server/test/trace-logger.spec.ts new file mode 100644 index 0000000..cce459f --- /dev/null +++ b/server/test/trace-logger.spec.ts @@ -0,0 +1,84 @@ +// eslint-disable-next-line @typescript-eslint/no-require-imports +import createDebug = require("debug"); +import { TraceLogger } from "../src/common/trace-logger"; +import { traceStorage } from "../src/common/trace-context"; +import { LogMode } from "../src/config/app.config"; + +describe("TraceLogger output mode", () => { + const originalLogMode = process.env.LOG_MODE; + const originalNodeEnv = process.env.NODE_ENV; + const originalDebug = createDebug.disable(); + + let stdout: jest.SpyInstance; + let stderr: jest.SpyInstance; + + beforeEach(() => { + stdout = jest + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + stderr = jest + .spyOn(process.stderr, "write") + .mockImplementation(() => true); + createDebug.disable(); + }); + + afterEach(() => { + stdout.mockRestore(); + stderr.mockRestore(); + createDebug.disable(); + if (originalDebug) createDebug.enable(originalDebug); + if (originalLogMode === undefined) delete process.env.LOG_MODE; + else process.env.LOG_MODE = originalLogMode; + if (originalNodeEnv === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = originalNodeEnv; + }); + + it("keeps console output as the default", () => { + delete process.env.LOG_MODE; + new TraceLogger("Runtime").log("visible by default"); + + expect(stdout).toHaveBeenCalled(); + expect(stderr).not.toHaveBeenCalled(); + }); + + it("writes debug-mode output only when its namespace is enabled", () => { + process.env.LOG_MODE = LogMode.Debug; + process.env.NODE_ENV = "production"; + createDebug.enable("liqa:other"); + + new TraceLogger("Runtime").warn("quiet without matching namespace"); + + expect(stdout).not.toHaveBeenCalled(); + expect(stderr).not.toHaveBeenCalled(); + }); + + it("routes matching debug output with level, context, trace id and error detail", () => { + process.env.LOG_MODE = LogMode.Debug; + process.env.NODE_ENV = "production"; + createDebug.enable("liqa:runtime"); + + traceStorage.run({ traceId: "trace-123" }, () => { + new TraceLogger("Runtime").error( + "request failed", + "synthetic stack\n at test()", + "Runtime", + ); + }); + + const output = stderr.mock.calls.flat().join(""); + expect(stdout).not.toHaveBeenCalled(); + expect(output).toContain("[ERROR] [Runtime:trace-123] request failed"); + expect(output).toContain("synthetic stack"); + }); + + it("preserves DEBUG=test for test-process logging", () => { + process.env.LOG_MODE = LogMode.Debug; + process.env.NODE_ENV = "test"; + createDebug.enable("test"); + + new TraceLogger("Unit").debug("test diagnostic"); + + expect(stdout).not.toHaveBeenCalled(); + expect(stderr.mock.calls.flat().join("")).toContain("test diagnostic"); + }); +});