feat(logging): add opt-in debug logging mode
- Add validated LOG_MODE configuration and route trace-aware diagnostics through debug. - Select debug mode in shared test setup while preserving DEBUG namespace control. - Add logger/config regression coverage and document runtime configuration.
This commit is contained in:
1 parent
ff9a700c86
commit
ceed27ad9e
10 files changed
+214
-4
No files matched your search
@@ -8,6 +8,9 @@
|
|||||||
# NODE_ENV=development
|
# NODE_ENV=development
|
||||||
# PORT=3000
|
# PORT=3000
|
||||||
|
|
||||||
|
## Application log output: console (default) or debug (controlled by DEBUG namespaces)
|
||||||
|
# LOG_MODE=console
|
||||||
|
|
||||||
## Optional account authentication (disabled unless explicitly enabled)
|
## Optional account authentication (disabled unless explicitly enabled)
|
||||||
# AUTH_ENABLED=true
|
# AUTH_ENABLED=true
|
||||||
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
|
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
|
||||||
|
|||||||
+2
-1
@@ -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 |
|
| `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`) |
|
| `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 |
|
| `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 |
|
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
||||||
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
| `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 |
|
| `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
|
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
|
```bash
|
||||||
npm -w server run test:debug
|
npm -w server run test:debug
|
||||||
|
|||||||
Generated
+1
-1
@@ -17464,6 +17464,7 @@
|
|||||||
"better-sqlite3": "^12.8.0",
|
"better-sqlite3": "^12.8.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.4",
|
"class-validator": "^0.14.4",
|
||||||
|
"debug": "^4.4.3",
|
||||||
"effect": "^3.21.0",
|
"effect": "^3.21.0",
|
||||||
"jsdom": "^29.0.2",
|
"jsdom": "^29.0.2",
|
||||||
"playwright": "^1.59.1",
|
"playwright": "^1.59.1",
|
||||||
@@ -17487,7 +17488,6 @@
|
|||||||
"@types/mozilla__readability": "^0.4.2",
|
"@types/mozilla__readability": "^0.4.2",
|
||||||
"@types/node": "^25.5.2",
|
"@types/node": "^25.5.2",
|
||||||
"@types/supertest": "^7.2.0",
|
"@types/supertest": "^7.2.0",
|
||||||
"debug": "^4.4.3",
|
|
||||||
"eslint": "^10.2.0",
|
"eslint": "^10.2.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"jest": "^30.3.0",
|
"jest": "^30.3.0",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ module.exports = {
|
|||||||
transform: {
|
transform: {
|
||||||
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
|
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
|
||||||
},
|
},
|
||||||
|
setupFiles: ['<rootDir>/test/logging.setup.js'],
|
||||||
moduleNameMapper: {
|
moduleNameMapper: {
|
||||||
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
|
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
|
||||||
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
|
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
|
||||||
|
|||||||
+1
-1
@@ -38,6 +38,7 @@
|
|||||||
"better-sqlite3": "^12.8.0",
|
"better-sqlite3": "^12.8.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.4",
|
"class-validator": "^0.14.4",
|
||||||
|
"debug": "^4.4.3",
|
||||||
"effect": "^3.21.0",
|
"effect": "^3.21.0",
|
||||||
"jsdom": "^29.0.2",
|
"jsdom": "^29.0.2",
|
||||||
"playwright": "^1.59.1",
|
"playwright": "^1.59.1",
|
||||||
@@ -61,7 +62,6 @@
|
|||||||
"@types/mozilla__readability": "^0.4.2",
|
"@types/mozilla__readability": "^0.4.2",
|
||||||
"@types/node": "^25.5.2",
|
"@types/node": "^25.5.2",
|
||||||
"@types/supertest": "^7.2.0",
|
"@types/supertest": "^7.2.0",
|
||||||
"debug": "^4.4.3",
|
|
||||||
"eslint": "^10.2.0",
|
"eslint": "^10.2.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"jest": "^30.3.0",
|
"jest": "^30.3.0",
|
||||||
|
|||||||
@@ -1,9 +1,108 @@
|
|||||||
import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common";
|
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 { getTraceId } from "./trace-context";
|
||||||
|
import { LogMode } from "../config/app.config";
|
||||||
|
|
||||||
export class TraceLogger extends ConsoleLogger {
|
export class TraceLogger extends ConsoleLogger {
|
||||||
|
private readonly loggerContext: string;
|
||||||
|
|
||||||
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
|
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
|
||||||
super(context as string, options);
|
super(context as string, options);
|
||||||
|
this.loggerContext = context ?? "Application";
|
||||||
|
}
|
||||||
|
|
||||||
|
override log(...args: Parameters<ConsoleLogger["log"]>): void {
|
||||||
|
if (this.useDebugOutput()) {
|
||||||
|
const [message, ...optionalParams] = args;
|
||||||
|
this.writeDebug("log", message, optionalParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.log(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
override error(...args: Parameters<ConsoleLogger["error"]>): void {
|
||||||
|
if (this.useDebugOutput()) {
|
||||||
|
const [message, ...optionalParams] = args;
|
||||||
|
this.writeDebug("error", message, optionalParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.error(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
override warn(...args: Parameters<ConsoleLogger["warn"]>): void {
|
||||||
|
if (this.useDebugOutput()) {
|
||||||
|
const [message, ...optionalParams] = args;
|
||||||
|
this.writeDebug("warn", message, optionalParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.warn(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
override debug(...args: Parameters<ConsoleLogger["debug"]>): void {
|
||||||
|
if (this.useDebugOutput()) {
|
||||||
|
const [message, ...optionalParams] = args;
|
||||||
|
this.writeDebug("debug", message, optionalParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.debug(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
override verbose(...args: Parameters<ConsoleLogger["verbose"]>): void {
|
||||||
|
if (this.useDebugOutput()) {
|
||||||
|
const [message, ...optionalParams] = args;
|
||||||
|
this.writeDebug("verbose", message, optionalParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.verbose(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
override fatal(...args: Parameters<ConsoleLogger["fatal"]>): 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 {
|
protected override getTimestamp(): string {
|
||||||
|
|||||||
@@ -20,6 +20,11 @@ export enum TraceMode {
|
|||||||
Off = "off",
|
Off = "off",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum LogMode {
|
||||||
|
Console = "console",
|
||||||
|
Debug = "debug",
|
||||||
|
}
|
||||||
|
|
||||||
export class AppConfig {
|
export class AppConfig {
|
||||||
/** `production` in the Docker image; also selects the default CORS origins. */
|
/** `production` in the Docker image; also selects the default CORS origins. */
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -40,6 +45,10 @@ export class AppConfig {
|
|||||||
@IsString()
|
@IsString()
|
||||||
APP_VERSION: string = appPackage().version;
|
APP_VERSION: string = appPackage().version;
|
||||||
|
|
||||||
|
/** Route application diagnostics through `debug` instead of the console. */
|
||||||
|
@IsEnum(LogMode)
|
||||||
|
LOG_MODE: LogMode = LogMode.Console;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
DB_PATH: string = "data/liqa.db";
|
DB_PATH: string = "data/liqa.db";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import "reflect-metadata";
|
import "reflect-metadata";
|
||||||
import { validateAppConfig } from "../src/config/app.config";
|
import { LogMode, validateAppConfig } from "../src/config/app.config";
|
||||||
import { durationSeconds } from "../src/common/interval";
|
import { durationSeconds } from "../src/common/interval";
|
||||||
|
|
||||||
describe("Authentication configuration", () => {
|
describe("Authentication configuration", () => {
|
||||||
@@ -12,6 +12,17 @@ describe("Authentication configuration", () => {
|
|||||||
expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *");
|
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", () => {
|
it("parses explicit true and false values without JavaScript truthiness", () => {
|
||||||
expect(validateAppConfig({ AUTH_ENABLED: "false" }).AUTH_ENABLED).toBe(
|
expect(validateAppConfig({ AUTH_ENABLED: "false" }).AUTH_ENABLED).toBe(
|
||||||
false,
|
false,
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Application logs should stay quiet during tests unless DEBUG enables them.
|
||||||
|
process.env.LOG_MODE = 'debug';
|
||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user