Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache parsed message templates #166

Merged
merged 2 commits into from
May 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright (c) Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


using System;
using Serilog.Events;
using Serilog.Parsing;
using System.Collections;

namespace Serilog.Extensions.Logging
{
class CachingMessageTemplateParser
{
readonly MessageTemplateParser _innerParser = new MessageTemplateParser();

readonly object _templatesLock = new object();
readonly Hashtable _templates = new Hashtable();

const int MaxCacheItems = 1000;
const int MaxCachedTemplateLength = 1024;

public MessageTemplate Parse(string messageTemplate)
{
if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate));

if (messageTemplate.Length > MaxCachedTemplateLength)
return _innerParser.Parse(messageTemplate);

// ReSharper disable once InconsistentlySynchronizedField
// ignored warning because this is by design
var result = (MessageTemplate)_templates[messageTemplate];
if (result != null)
return result;

result = _innerParser.Parse(messageTemplate);

lock (_templatesLock)
{
// Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory
// conditions when the library is used incorrectly. Correct use (templates, rather than
// direct message strings) should barely, if ever, overflow this cache.

// Changing workloads through the lifecycle of an app instance mean we can gain some ground by
// potentially dropping templates generated only in startup, or only during specific infrequent
// activities.

if (_templates.Count == MaxCacheItems)
_templates.Clear();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line gives race condition with var result = (MessageTemplate)_templates[messageTemplate];

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking a look, @sungam3r.

The two lines above mention this:

            // ReSharper disable once InconsistentlySynchronizedField
            // ignored warning because this is by design
            var result = (MessageTemplate)_templates[messageTemplate];

Although there may be undocumented bugs in Hashtable, it was originally intended to be used in this manner, and we've not observed any problems with this particular pattern in several years of very heavy usage in Serilog.

There's a little more discussion here: JamesNK/Newtonsoft.Json#1163 (comment) (it's never been clear which of the Hashtable APIs have threading bugs, unfortunately).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok


_templates[messageTemplate] = result;
}

return result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Serilog.Events;
using FrameworkLogger = Microsoft.Extensions.Logging.ILogger;
using System.Reflection;
using Serilog.Parsing;

namespace Serilog.Extensions.Logging
{
Expand All @@ -18,7 +17,7 @@ class SerilogLogger : FrameworkLogger
readonly SerilogLoggerProvider _provider;
readonly ILogger _logger;

static readonly MessageTemplateParser MessageTemplateParser = new MessageTemplateParser();
static readonly CachingMessageTemplateParser MessageTemplateParser = new CachingMessageTemplateParser();

// It's rare to see large event ids, as they are category-specific
static readonly LogEventProperty[] LowEventIdValues = Enumerable.Range(0, 48)
Expand Down Expand Up @@ -159,4 +158,4 @@ internal static LogEventProperty CreateEventIdProperty(EventId eventId)
return new LogEventProperty("EventId", new StructureValue(properties));
}
}
}
}