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 9 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
101 changes: 101 additions & 0 deletions src/Shared/Internal/RendererReEntrantManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System;
#if !NET35
using System.Threading;
#endif
#if ASP_NET_CORE
using HttpContextBase = Microsoft.AspNetCore.Http.HttpContext;
#else
using System.Web;
#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 struct RendererReEntrantManager : IDisposable
{
internal RendererReEntrantManager(HttpContextBase context)
{
_httpContext = context;
_obtainedLock = false;
TryGetLock();
}

private readonly HttpContextBase _httpContext;

internal bool IsLockAcquired => _obtainedLock;

#if NET35
private static readonly object ReEntrantLock = new object();

private bool IsLocked()
{
return _httpContext?.Items?.Contains(ReEntrantLock) == true;
}

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

private void Unlock()
{
_httpContext?.Items?.Remove(ReEntrantLock);
}
#else
private static readonly AsyncLocal<bool> ReEntrantLock = new AsyncLocal<bool>();

private bool IsLocked()
{
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 lock
// If we were not, we should not unlock in the dispose code
private bool _obtainedLock;
snakefoot marked this conversation as resolved.
Show resolved Hide resolved


private void TryGetLock()
{
// If already locked, return false
if (IsLocked())
{
return;
}
// Get the lock
Lock();
// Mark that we locked it, not another instance locked it
_obtainedLock = true;
}

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

public void Dispose()
{
DisposalImpl();
}
}
}
66 changes: 33 additions & 33 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,33 @@ 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;
}
#endif
if (value != null)

using (var reEntry = new RendererReEntrantManager(context))
{
var formatProvider = GetFormatProvider(logEvent, Culture);
builder.AppendFormattedValue(value, Format, formatProvider, ValueFormatter);
if (!reEntry.IsLockAcquired)
{
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 +126,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

}
}