diff --git a/package.json b/package.json index 588b9cb..3d9af89 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@serverless-guru/logger", - "version": "1.0.5", + "version": "1.0.6", "description": "Common logger utility", "main": "./lib/cjs/index.js", "types": "./lib/cjs/index.d.ts", diff --git a/src/index.ts b/src/index.ts index 4b9a508..a390d98 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,7 @@ class Logger { private serviceName: string; private correlationId: string; + private resetCorrelationId: boolean; private applicationName: string; private persistentContext: JSONObject; private console: Console; @@ -35,6 +36,7 @@ class Logger { constructor(serviceName: string, applicationName: string, correlationId: string | null = null) { this.serviceName = serviceName; this.correlationId = correlationId ? correlationId : randomUUID(); + this.resetCorrelationId = correlationId ? false : true; this.applicationName = applicationName; this.persistentContext = {}; this.console = @@ -63,9 +65,7 @@ class Logger { const arrayToLowerCase = (array: StringArray): StringArray => { if (Array.isArray(array)) { - return array - .filter((el) => typeof el === "string") - .map((el) => el.toLowerCase()); + return array.filter((el) => typeof el === "string").map((el) => el.toLowerCase()); } return []; }; @@ -261,6 +261,7 @@ class Logger { setCorrelationId(correlationId: string): void { if (correlationId) { this.correlationId = correlationId; + this.resetCorrelationId = true; } } @@ -275,9 +276,9 @@ class Logger { clearLogContext(): void { this.persistentContext = {}; - this.correlationId = ""; - this.applicationName = ""; - this.serviceName = ""; + if (this.resetCorrelationId) { + this.correlationId = randomUUID(); + } } metric(activity: string, meta: MetricMeta): void { diff --git a/test/logger.test.ts b/test/logger.test.ts index 4bd5176..3122fe5 100644 --- a/test/logger.test.ts +++ b/test/logger.test.ts @@ -115,7 +115,18 @@ describe("Log Outputs", () => { logger.clearLogContext(); logger.info("Simple"); expect(console.info).toHaveBeenCalledWith( - '{"level":"INFO","service":"","correlationId":"","message":"Simple"}' + '{"level":"INFO","service":"testService","correlationId":"testId","message":"Simple"}' + ); + }); + + test("Global Context Reset", () => { + const logger = new Logger("testService", "testApp"); + logger.clearLogContext(); + logger.info("Simple"); + expect(console.info).toHaveBeenCalledWith( + expect.stringMatching( + /{"level":"INFO","service":"testService","correlationId":"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}","message":"Simple"}/ + ) ); });