|
| 1 | +// Copyright (c) Serilog Contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +using System; |
| 17 | +using Serilog.Events; |
| 18 | +using Serilog.Parsing; |
| 19 | +using System.Collections; |
| 20 | + |
| 21 | +namespace Serilog.Extensions.Logging |
| 22 | +{ |
| 23 | + class CachingMessageTemplateParser |
| 24 | + { |
| 25 | + readonly MessageTemplateParser _innerParser = new MessageTemplateParser(); |
| 26 | + |
| 27 | + readonly object _templatesLock = new object(); |
| 28 | + readonly Hashtable _templates = new Hashtable(); |
| 29 | + |
| 30 | + const int MaxCacheItems = 1000; |
| 31 | + const int MaxCachedTemplateLength = 1024; |
| 32 | + |
| 33 | + public MessageTemplate Parse(string messageTemplate) |
| 34 | + { |
| 35 | + if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate)); |
| 36 | + |
| 37 | + if (messageTemplate.Length > MaxCachedTemplateLength) |
| 38 | + return _innerParser.Parse(messageTemplate); |
| 39 | + |
| 40 | + // ReSharper disable once InconsistentlySynchronizedField |
| 41 | + // ignored warning because this is by design |
| 42 | + var result = (MessageTemplate)_templates[messageTemplate]; |
| 43 | + if (result != null) |
| 44 | + return result; |
| 45 | + |
| 46 | + result = _innerParser.Parse(messageTemplate); |
| 47 | + |
| 48 | + lock (_templatesLock) |
| 49 | + { |
| 50 | + // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory |
| 51 | + // conditions when the library is used incorrectly. Correct use (templates, rather than |
| 52 | + // direct message strings) should barely, if ever, overflow this cache. |
| 53 | + |
| 54 | + // Changing workloads through the lifecycle of an app instance mean we can gain some ground by |
| 55 | + // potentially dropping templates generated only in startup, or only during specific infrequent |
| 56 | + // activities. |
| 57 | + |
| 58 | + if (_templates.Count == MaxCacheItems) |
| 59 | + _templates.Clear(); |
| 60 | + |
| 61 | + _templates[messageTemplate] = result; |
| 62 | + } |
| 63 | + |
| 64 | + return result; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments