14
14
15
15
namespace Serilog . Extensions . Logging
16
16
{
17
+ using System . Collections . Concurrent ;
17
18
using Microsoft . Extensions . Logging ;
18
19
using Serilog . Events ;
19
20
20
- internal sealed class EventIdPropertyCache
21
+ static class EventIdPropertyCache
21
22
{
22
- private readonly object _createLock = new ( ) ;
23
- private readonly int _maxCapacity ;
24
- private readonly Dictionary < EventKey , LogEventProperty > _propertyCache ;
23
+ const int MaxCachedProperties = 1024 ;
25
24
26
- private int count ;
25
+ static readonly ConcurrentDictionary < EventKey , LogEventProperty > s_propertyCache = new ( ) ;
26
+ static int s_count ;
27
27
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 )
35
29
{
36
30
var eventKey = new EventKey ( eventId ) ;
37
31
38
- if ( _propertyCache . TryGetValue ( eventKey , out var cachedProperty ) )
39
- {
40
- return cachedProperty ;
41
- }
32
+ LogEventProperty ? property ;
42
33
43
- lock ( _createLock )
34
+ if ( s_count >= MaxCachedProperties )
44
35
{
45
- // Double check under lock
46
- if ( _propertyCache . TryGetValue ( eventKey , out cachedProperty ) )
36
+ if ( ! s_propertyCache . TryGetValue ( eventKey , out property ) )
47
37
{
48
- return cachedProperty ;
38
+ property = CreateCore ( in eventKey ) ;
49
39
}
50
-
51
- cachedProperty = CreateCore ( in eventKey ) ;
52
-
53
- if ( count < _maxCapacity )
54
- {
55
- _propertyCache [ eventKey ] = cachedProperty ;
56
- count ++ ;
57
- }
58
-
59
- return cachedProperty ;
60
40
}
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 ;
61
54
}
62
55
63
- private static LogEventProperty CreateCore ( in EventKey eventKey )
56
+ static LogEventProperty CreateCore ( in EventKey eventKey )
64
57
{
65
58
var properties = new List < LogEventProperty > ( 2 ) ;
66
59
@@ -77,9 +70,8 @@ private static LogEventProperty CreateCore(in EventKey eventKey)
77
70
return new LogEventProperty ( "EventId" , new StructureValue ( properties ) ) ;
78
71
}
79
72
80
- private readonly record struct EventKey
73
+ readonly record struct EventKey
81
74
{
82
-
83
75
public EventKey ( EventId eventId )
84
76
{
85
77
Id = eventId . Id ;
0 commit comments