Skip to content

Commit 45a67a6

Browse files
committed
feat(logger): add context for low prio logs
1 parent c97d379 commit 45a67a6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

packages/logger/src/Logger.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ class Logger extends Utility implements LoggerInterface {
139139
* immediately because the logger is not ready yet. This buffer stores those logs until the logger is ready.
140140
*/
141141
#buffer: [number, Parameters<Logger['createAndPopulateLogItem']>][] = [];
142+
143+
144+
#context: Record<string, Array<Parameters<Logger['createAndPopulateLogItem']>>> = {}
145+
146+
142147
/**
143148
* Flag used to determine if the logger is initialized.
144149
*/
@@ -183,6 +188,7 @@ class Logger extends Utility implements LoggerInterface {
183188
this.printLog(level, this.createAndPopulateLogItem(...log));
184189
}
185190
this.#buffer = [];
191+
this.#context = {};
186192
}
187193

188194
/**
@@ -868,6 +874,22 @@ class Logger extends Utility implements LoggerInterface {
868874
extraInput: LogItemExtraInput
869875
): void {
870876
if (logLevel >= this.logLevel) {
877+
const xRayTraceId = this.envVarsService.getXrayTraceId();
878+
879+
// Print all log items in the context
880+
if (this.#context[xRayTraceId]) {
881+
for (const contextItem of this.#context[xRayTraceId]) {
882+
this.printLog(
883+
logLevel,
884+
this.createAndPopulateLogItem(...contextItem)
885+
);
886+
}
887+
888+
// Clear the context after flushing
889+
// This also removes entries from other X-Ray trace IDs
890+
this.#context = {};
891+
}
892+
871893
if (this.#isInitialized) {
872894
this.printLog(
873895
logLevel,
@@ -876,6 +898,18 @@ class Logger extends Utility implements LoggerInterface {
876898
} else {
877899
this.#buffer.push([logLevel, [logLevel, input, extraInput]]);
878900
}
901+
} else {
902+
const xRayTraceId = this.envVarsService.getXrayTraceId() as string;
903+
904+
// Add the log item to the context
905+
const context = this.#context[xRayTraceId] ?? [];
906+
context.push([logLevel, input, extraInput]);
907+
908+
// Assign the updated context to the context property
909+
// This also removes other X-Ray trace IDs from the context
910+
this.#context = {
911+
[xRayTraceId]: context,
912+
};
879913
}
880914
}
881915

0 commit comments

Comments
 (0)