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

Improved re-entrancy Scope Lock for Session Value Layout Render #850

Merged
merged 18 commits into from
Aug 12, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
120 changes: 120 additions & 0 deletions src/Shared/Internal/RendererReEntrantManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using System;
#if NET35
using System.Web;
#else
using System.Threading;
#endif

namespace NLog.Web.Internal
{
/// <summary>
/// Manages if a LayoutRenderer can be called recursively.
/// Especially used by AspNetSessionValueLayoutRenderer
///
/// Since NET 35 does not support AsyncLocal or even ThreadLocal
/// a different technique must be used for that platform
/// </summary>
internal class RendererReEntrantManager : IDisposable
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
{
#if NET35
private static readonly object ReEntrantLock = new object();

internal RendererReEntrantManager(HttpContextBase context)
{
httpContext = context;
}

private readonly HttpContextBase httpContext;

private bool ReadLock()
{
return httpContext?.Items?.Contains(ReEntrantLock) == true;
}

private void Lock()
{
httpContext.Items[ReEntrantLock] = bool.TrueString;
}

private void Unlock()
{
httpContext?.Items?.Remove(ReEntrantLock);
}
#else
// Manage access to the session re-entrancy, at least above .NET 3.5
private static readonly AsyncLocal<bool> ReEntrantLock = new AsyncLocal<bool>();

internal RendererReEntrantManager()
{

}

private bool ReadLock()
{
return ReEntrantLock.Value;
}

private void Lock()
{
ReEntrantLock.Value = true;
}

private void Unlock()
{
ReEntrantLock.Value = false;
}
#endif

// Need to track if we were successful in the entry
// If we were not, we should not unlock in the dispose code
private bool entrySuccess;


internal bool TryGetLock()
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
{
// If already locked, return false
if (ReadLock())
{
return false;
}
// Get the lock
Lock();
// Mark that we locked it, not another instance locked it
entrySuccess = true;
// Return to the caller that we locked it
return true;
}

private void DisposalImpl()
{
// Only unlock if we were the ones who locked it
if (entrySuccess)
{
Unlock();
}
}

// Dispose methods
// Below code generated by Visual Studio 2022 and Resharper
private bool disposedValue;

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
DisposalImpl();
}
disposedValue = true;
}
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
68 changes: 36 additions & 32 deletions src/Shared/LayoutRenderers/AspNetSessionValueLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
using System;
using System.Globalization;
using System.Text;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Web.Internal;
#if !ASP_NET_CORE
using System.Web;
#else
using NLog.Common;
#if ASP_NET_CORE
using Microsoft.AspNetCore.Http;
#else
using System.Web;
#endif

namespace NLog.Web.LayoutRenderers
Expand Down Expand Up @@ -40,10 +40,6 @@ namespace NLog.Web.LayoutRenderers
[LayoutRenderer("aspnet-session")]
public class AspNetSessionValueLayoutRenderer : AspNetLayoutRendererBase
{
#if ASP_NET_CORE
private static readonly object NLogRetrievingSessionValue = new object();
#endif

/// <summary>
/// Gets or sets the session item name.
/// </summary>
Expand Down Expand Up @@ -78,7 +74,7 @@ public class AspNetSessionValueLayoutRenderer : AspNetLayoutRendererBase

#if ASP_NET_CORE
/// <summary>
/// The hype of the value.
/// The type of the value.
/// </summary>
public SessionValueType ValueType { get; set; } = SessionValueType.String;
#endif
Expand All @@ -93,36 +89,37 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
}

var context = HttpContextAccessor.HttpContext;
var contextSession = context.TryGetSession();
if (contextSession == null)
return;

#if !ASP_NET_CORE
var value = PropertyReader.GetValue(item, contextSession, (session,key) => session.Count > 0 ? session[key] : null, EvaluateAsNestedProperties);
#else
//because session.get / session.getstring also creating log messages in some cases, this could lead to stackoverflow issues.
//We remember on the context.Items that we are looking up a session value so we prevent stackoverflows
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
if (context.Items == null || (context.Items.Count > 0 && context.Items.ContainsKey(NLogRetrievingSessionValue)))
if (context == null)
{
return;
}

context.Items[NLogRetrievingSessionValue] = bool.TrueString;

object value;
try
{
value = PropertyReader.GetValue(item, contextSession, (session, key) => GetSessionValue(session, key), EvaluateAsNestedProperties);
}
finally
var contextSession = context?.TryGetSession();
if (contextSession == null)
{
context.Items.Remove(NLogRetrievingSessionValue);
return;
}

using (var reEntry = new RendererReEntrantManager(
#if NET35
context
#endif
if (value != null)
))
{
var formatProvider = GetFormatProvider(logEvent, Culture);
builder.AppendFormattedValue(value, Format, formatProvider, ValueFormatter);
if (!reEntry.TryGetLock())
{
InternalLogger.Error(
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
$"Reentrant log event detected. Logging when inside the scope of another log event can cause a StackOverflowException. LogEventInfo.Message:{logEvent.Message}");
return;
}

var value = PropertyReader.GetValue(item, contextSession, GetSessionValue, EvaluateAsNestedProperties);

if (value != null)
{
var formatProvider = GetFormatProvider(logEvent, Culture);
builder.AppendFormattedValue(value, Format, formatProvider, ValueFormatter);
}
}
}

Expand All @@ -133,9 +130,16 @@ private object GetSessionValue(ISession session, string key)
{
case SessionValueType.Int32:
return session.GetInt32(key);
default: return session.GetString(key);
default:
return session.GetString(key);
}
}
#else
private object GetSessionValue(HttpSessionStateBase session, string key)
{
return session.Count == 0 ? null : session[key];
}
#endif

}
}