11using System ;
2+ using System . Collections . Concurrent ;
23using System . Collections . Generic ;
34using System . Linq ;
5+ using System . Threading ;
46using AWS . Lambda . Powertools . Logging . Internal ;
57using AWS . Lambda . Powertools . Logging . Internal . Helpers ;
68
@@ -9,10 +11,25 @@ namespace AWS.Lambda.Powertools.Logging;
911public static partial class Logger
1012{
1113 /// <summary>
12- /// Gets the scope.
14+ /// Thread-safe dictionary for per-thread scope storage.
15+ /// Uses ManagedThreadId as key to ensure isolation when Lambda processes
16+ /// multiple concurrent requests (AWS_LAMBDA_MAX_CONCURRENCY > 1).
17+ /// </summary>
18+ private static readonly ConcurrentDictionary < int , Dictionary < string , object > > _threadScopes = new ( ) ;
19+
20+ /// <summary>
21+ /// Gets the scope for the current thread.
22+ /// Creates a new dictionary if one doesn't exist for this thread.
1323 /// </summary>
1424 /// <value>The scope.</value>
15- private static IDictionary < string , object > Scope { get ; } = new Dictionary < string , object > ( StringComparer . Ordinal ) ;
25+ private static IDictionary < string , object > Scope
26+ {
27+ get
28+ {
29+ var threadId = Environment . CurrentManagedThreadId ;
30+ return _threadScopes . GetOrAdd ( threadId , _ => new Dictionary < string , object > ( StringComparer . Ordinal ) ) ;
31+ }
32+ }
1633
1734 /// <summary>
1835 /// Gets the correlation identifier from the log context.
@@ -70,7 +87,7 @@ public static void AppendKeys(IEnumerable<KeyValuePair<string, string>> keys)
7087 /// Remove additional keys from the log context.
7188 /// </summary>
7289 /// <param name="keys">The list of keys.</param>
73- public static void RemoveKeys ( params string [ ] keys )
90+ public static void RemoveKeys ( params string [ ] keys )
7491 {
7592 if ( keys == null ) return ;
7693 foreach ( var key in keys )
@@ -88,11 +105,15 @@ public static IEnumerable<KeyValuePair<string, object>> GetAllKeys()
88105 }
89106
90107 /// <summary>
91- /// Removes all additional keys from the log context.
108+ /// Removes all additional keys from the log context for the current thread .
92109 /// </summary>
93110 internal static void RemoveAllKeys ( )
94111 {
95- Scope . Clear ( ) ;
112+ var threadId = Environment . CurrentManagedThreadId ;
113+ if ( _threadScopes . TryGetValue ( threadId , out var scope ) )
114+ {
115+ scope . Clear ( ) ;
116+ }
96117 }
97118
98119 /// <summary>
0 commit comments