@@ -139,6 +139,11 @@ class Logger extends Utility implements LoggerInterface {
139
139
* immediately because the logger is not ready yet. This buffer stores those logs until the logger is ready.
140
140
*/
141
141
#buffer: [ number , Parameters < Logger [ 'createAndPopulateLogItem' ] > ] [ ] = [ ] ;
142
+
143
+
144
+ #context: Record < string , Array < Parameters < Logger [ 'createAndPopulateLogItem' ] > > > = { }
145
+
146
+
142
147
/**
143
148
* Flag used to determine if the logger is initialized.
144
149
*/
@@ -183,6 +188,7 @@ class Logger extends Utility implements LoggerInterface {
183
188
this . printLog ( level , this . createAndPopulateLogItem ( ...log ) ) ;
184
189
}
185
190
this . #buffer = [ ] ;
191
+ this . #context = { } ;
186
192
}
187
193
188
194
/**
@@ -868,6 +874,22 @@ class Logger extends Utility implements LoggerInterface {
868
874
extraInput : LogItemExtraInput
869
875
) : void {
870
876
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
+
871
893
if ( this . #isInitialized) {
872
894
this . printLog (
873
895
logLevel ,
@@ -876,6 +898,18 @@ class Logger extends Utility implements LoggerInterface {
876
898
} else {
877
899
this . #buffer. push ( [ logLevel , [ logLevel , input , extraInput ] ] ) ;
878
900
}
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
+ } ;
879
913
}
880
914
}
881
915
0 commit comments