|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +namespace Serilog.Extensions.Logging |
| 5 | +{ |
| 6 | + using Microsoft.Extensions.Logging; |
| 7 | + using Serilog.Events; |
| 8 | + |
| 9 | + internal sealed class EventIdPropertyCache |
| 10 | + { |
| 11 | + private readonly object _createLock = new(); |
| 12 | + private readonly int _maxCapacity; |
| 13 | + private readonly Dictionary<int, LogEventProperty> _propertyCache; |
| 14 | + |
| 15 | + private int count; |
| 16 | + |
| 17 | + public EventIdPropertyCache(int maxCapacity) |
| 18 | + { |
| 19 | + this._maxCapacity = maxCapacity; |
| 20 | + this._propertyCache = new Dictionary<int, LogEventProperty>(capacity: maxCapacity); |
| 21 | + } |
| 22 | + |
| 23 | + public LogEventProperty GetOrCreateProperty(in EventId eventId) |
| 24 | + { |
| 25 | + if (_propertyCache.TryGetValue(eventId.Id, out var cachedProperty)) |
| 26 | + { |
| 27 | + return cachedProperty; |
| 28 | + } |
| 29 | + |
| 30 | + lock (_createLock) |
| 31 | + { |
| 32 | + return GetOrCreateSynchronized(in eventId); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private static LogEventProperty CreateCore(in EventId eventId) |
| 37 | + { |
| 38 | + var properties = new List<LogEventProperty>(2); |
| 39 | + |
| 40 | + if (eventId.Id != 0) |
| 41 | + { |
| 42 | + properties.Add(new LogEventProperty("Id", new ScalarValue(eventId.Id))); |
| 43 | + } |
| 44 | + |
| 45 | + if (eventId.Name != null) |
| 46 | + { |
| 47 | + properties.Add(new LogEventProperty("Name", new ScalarValue(eventId.Name))); |
| 48 | + } |
| 49 | + |
| 50 | + return new LogEventProperty("EventId", new StructureValue(properties)); |
| 51 | + } |
| 52 | + |
| 53 | + private LogEventProperty GetOrCreateSynchronized(in EventId eventId) |
| 54 | + { |
| 55 | + // Double check under lock |
| 56 | + if (_propertyCache.TryGetValue(eventId.Id, out var cachedProperty)) |
| 57 | + { |
| 58 | + return cachedProperty; |
| 59 | + } |
| 60 | + |
| 61 | + cachedProperty = CreateCore(in eventId); |
| 62 | + |
| 63 | + if (count < _maxCapacity) |
| 64 | + { |
| 65 | + _propertyCache[eventId.Id] = cachedProperty; |
| 66 | + count++; |
| 67 | + } |
| 68 | + |
| 69 | + return cachedProperty; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments