1414
1515namespace Serilog . Extensions . Logging
1616{
17+ using System . Collections . Concurrent ;
1718 using Microsoft . Extensions . Logging ;
1819 using Serilog . Events ;
1920
20- internal sealed class EventIdPropertyCache
21+ static class EventIdPropertyCache
2122 {
22- private readonly object _createLock = new ( ) ;
23- private readonly int _maxCapacity ;
24- private readonly Dictionary < EventKey , LogEventProperty > _propertyCache ;
23+ const int MaxCachedProperties = 1024 ;
2524
26- private int count ;
25+ static readonly ConcurrentDictionary < EventKey , LogEventProperty > s_propertyCache = new ( ) ;
26+ static int s_count ;
2727
28- public EventIdPropertyCache ( int maxCapacity )
29- {
30- _maxCapacity = maxCapacity ;
31- _propertyCache = new Dictionary < EventKey , LogEventProperty > ( capacity : maxCapacity ) ;
32- }
33-
34- public LogEventProperty GetOrCreateProperty ( in EventId eventId )
28+ public static LogEventProperty GetOrCreateProperty ( in EventId eventId )
3529 {
3630 var eventKey = new EventKey ( eventId ) ;
3731
38- if ( _propertyCache . TryGetValue ( eventKey , out var cachedProperty ) )
39- {
40- return cachedProperty ;
41- }
32+ LogEventProperty ? property ;
4233
43- lock ( _createLock )
34+ if ( s_count >= MaxCachedProperties )
4435 {
45- // Double check under lock
46- if ( _propertyCache . TryGetValue ( eventKey , out cachedProperty ) )
36+ if ( ! s_propertyCache . TryGetValue ( eventKey , out property ) )
4737 {
48- return cachedProperty ;
38+ property = CreateCore ( in eventKey ) ;
4939 }
50-
51- cachedProperty = CreateCore ( in eventKey ) ;
52-
53- if ( count < _maxCapacity )
54- {
55- _propertyCache [ eventKey ] = cachedProperty ;
56- count ++ ;
57- }
58-
59- return cachedProperty ;
6040 }
41+ else
42+ {
43+ property = s_propertyCache . GetOrAdd (
44+ eventKey ,
45+ static key =>
46+ {
47+ Interlocked . Increment ( ref s_count ) ;
48+
49+ return CreateCore ( in key ) ;
50+ } ) ;
51+ }
52+
53+ return property ;
6154 }
6255
63- private static LogEventProperty CreateCore ( in EventKey eventKey )
56+ static LogEventProperty CreateCore ( in EventKey eventKey )
6457 {
6558 var properties = new List < LogEventProperty > ( 2 ) ;
6659
@@ -77,9 +70,8 @@ private static LogEventProperty CreateCore(in EventKey eventKey)
7770 return new LogEventProperty ( "EventId" , new StructureValue ( properties ) ) ;
7871 }
7972
80- private readonly record struct EventKey
73+ readonly record struct EventKey
8174 {
82-
8375 public EventKey ( EventId eventId )
8476 {
8577 Id = eventId . Id ;
0 commit comments