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

Add aspnet-request-servervariable and aspnet-request-item layout renders #811

Merged
merged 16 commits into from
Jul 6, 2022
67 changes: 67 additions & 0 deletions src/Shared/LayoutRenderers/AspNetHttpContextItemLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Text;
using NLog.LayoutRenderers;
using NLog.Config;
#if !ASP_NET_CORE
using System.Web;
#else
using Microsoft.AspNetCore.Http;
#endif

namespace NLog.Web.LayoutRenderers
{
/// <summary>
/// ASP.NET HttpContext Item.
/// </summary>
/// <remarks>
/// Use this layout renderer to insert the value of the specified Item of the HttpContext
/// </remarks>
/// <example>
/// <para>Example usage of ${aspnet-httpcontext-item}:</para>
/// <code lang="NLog Layout Renderer">
/// ${aspnet-httpcontext-item:Item=v}
/// </code>
/// </example>
[LayoutRenderer("aspnet-httpcontext-item")]
public class AspNetHttpContextItemLayoutRenderer : AspNetLayoutRendererBase
{
/// <summary>
/// Gets or sets the item name. The Item collection variables having the specified name are rendered.
/// </summary>
[RequiredParameter]
[DefaultParameter]
public string Item { get; set; }

/// <inheritdoc />
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var httpContext = HttpContextAccessor.HttpContext;
if (httpContext == null)
{
return;
}

if (Item != null)
{
builder.Append(LookupItemValue(Item, httpContext));
}
}

#if !ASP_NET_CORE
private static string LookupItemValue(string key, HttpContextBase httpContext)
{
return httpContext?.Request?[key];
}

#else
private static string LookupItemValue(string key, HttpContext httpContext)
{
object itemValue = null;
if (httpContext.Items?.TryGetValue(key, out itemValue) ?? false)
{
return itemValue?.ToString();
}
return null;
}
#endif
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#if !ASP_NET_CORE || ASP_NET_CORE3
using System.Text;
using NLog.LayoutRenderers;
using NLog.Web.Internal;
using NLog.Config;
#if !ASP_NET_CORE
using System.Web;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
#endif

namespace NLog.Web.LayoutRenderers
{
/// <summary>
/// ASP.NET Server Variable.
/// </summary>
/// <remarks>
/// Use this layout renderer to insert the value of the specified Server Variable
/// </remarks>
/// <example>
/// <para>Example usage of ${aspnet-request-servervariable}:</para>
/// <code lang="NLog Layout Renderer">
/// ${aspnet-request-servervariable:Item=v}
/// </code>
/// </example>
[LayoutRenderer("aspnet-request-servervariable")]
public class AspNetRequestServerVariableLayoutRenderer : AspNetLayoutRendererBase
{

/// <summary>
/// Gets or sets the ServerVariables item to be rendered.
/// </summary>
[RequiredParameter]
[DefaultParameter]
public string Item { get; set; }

/// <inheritdoc />
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
if (Item != null)
{
builder.Append(LookupItemValue(Item, HttpContextAccessor.HttpContext));
}
}

#if !ASP_NET_CORE
private static string LookupItemValue(string key, HttpContextBase httpContext)
{
return httpContext?.TryGetRequest()?.ServerVariables?[key];
}

#elif ASP_NET_CORE3
private static string LookupItemValue(string key, HttpContext httpContext)
{
return httpContext?.TryGetFeatureCollection()?.Get<IServerVariablesFeature>()?[key];
}
#endif
}
}
#endif
26 changes: 21 additions & 5 deletions src/Shared/LayoutRenderers/AspNetRequestValueLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using System.Text;
using NLog.Config;
using NLog.LayoutRenderers;
Expand All @@ -7,7 +6,7 @@
using System.Web;
#else
using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Http.Features;
#endif

namespace NLog.Web.LayoutRenderers
Expand Down Expand Up @@ -58,7 +57,7 @@ public class AspNetRequestValueLayoutRenderer : AspNetLayoutRendererBase
/// <docgen category='Rendering Options' order='10' />
public string Cookie { get; set; }

#if !ASP_NET_CORE
#if !ASP_NET_CORE || ASP_NET_CORE3
/// <summary>
/// Gets or sets the ServerVariables item to be rendered.
/// </summary>
Expand Down Expand Up @@ -101,8 +100,12 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
#if !ASP_NET_CORE
else if (ServerVariable != null)
{
value = httpRequest.ServerVariables?.Count > 0 ?
httpRequest.ServerVariables[ServerVariable] : null;
value = LookupServerVariableValue(ServerVariable, httpRequest);
}
#elif ASP_NET_CORE3
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
else if (ServerVariable != null)
{
value = LookupServerVariableValue(ServerVariable, HttpContextAccessor.HttpContext);
}
#endif
else if (Header != null)
Expand Down Expand Up @@ -147,6 +150,12 @@ private static string LookupItemValue(string key, HttpRequestBase httpRequest)
{
return httpRequest[key];
}

private static string LookupServerVariableValue(string key, HttpRequestBase httpRequest)
{
var collection = httpRequest.ServerVariables;
return collection?.Count > 0 ? collection[key] : null;
}
#else
private static string LookupQueryString(string key, HttpRequest httpRequest)
{
Expand Down Expand Up @@ -206,5 +215,12 @@ private static string LookupItemValue(string key, HttpRequest httpRequest)
return null;
}
#endif

#if ASP_NET_CORE3
private static string LookupServerVariableValue(string key, HttpContext httpContext)
snakefoot marked this conversation as resolved.
Show resolved Hide resolved
{
return httpContext?.TryGetFeatureCollection()?.Get<IServerVariablesFeature>()?[key];
}
#endif
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.IO;
#if !ASP_NET_CORE
using System.Collections.Specialized;
using System.Web;
using System.Web.Routing;
using System.Web.SessionState;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using HttpContextBase = Microsoft.AspNetCore.Http.HttpContext;
#endif
using NLog.Common;
using NLog.Web.LayoutRenderers;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
using System.Collections.Generic;


namespace NLog.Web.Tests.LayoutRenderers
{
public class AspNetHttpContextItemLayoutRendererTests : TestInvolvingAspNetHttpContext
{
[Fact]
public void KeyNotFoundRendersEmptyString()
{
var httpContext = Substitute.For<HttpContextBase>();

var renderer = new AspNetHttpContextItemLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Empty(result);
}

[Fact]
public void KeyFoundRendersValue()
{
var expectedResult = "value";
var httpContext = Substitute.For<HttpContextBase>();
#if !ASP_NET_CORE
httpContext.Request["key"].Returns(expectedResult);
#else
httpContext.Items.Returns(new Dictionary<object, object>() { { "key", expectedResult } });
#endif

var renderer = new AspNetHttpContextItemLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Equal(expectedResult, result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using System.IO;
#if !ASP_NET_CORE
using System.Collections.Specialized;
using System.Web;
using System.Web.Routing;
using System.Web.SessionState;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using HttpContextBase = Microsoft.AspNetCore.Http.HttpContext;
#endif
using NLog.Common;
using NLog.Web.LayoutRenderers;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
using System.Collections.Generic;


namespace NLog.Web.Tests.LayoutRenderers
{
public class AspNetRequestServerVariableLayoutRendererTests : TestInvolvingAspNetHttpContext
{

#if !ASP_NET_CORE
[Fact]
public void NullRequestRendersEmptyStringWithoutLoggingError()
{
var internalLog = new StringWriter();
InternalLogger.LogWriter = internalLog;
InternalLogger.LogLevel = LogLevel.Error;

var httpContext = Substitute.For<HttpContextBase>();
httpContext.Request.Returns(x => { throw new HttpException(); });

var renderer = new AspNetRequestServerVariableLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Empty(result);
Assert.True(string.IsNullOrEmpty(internalLog.ToString()));
}
#endif

#if !ASP_NET_CORE
[Fact]
public void KeyNotFoundRendersEmptyString()
{
var httpContext = Substitute.For<HttpContextBase>();

var renderer = new AspNetRequestServerVariableLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Empty(result);
}

[Fact]
public void KeyFoundRendersValue()
{
var expectedResult = "value";
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Request.ServerVariables.Returns(new NameValueCollection { { "key", expectedResult } });

var renderer = new AspNetRequestServerVariableLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Equal(expectedResult, result);
}
#endif

#if ASP_NET_CORE3
[Fact]
public void KeyNotFoundRendersEmptyString()
{
var httpContext = Substitute.For<HttpContextBase>();

var serverVariablesFeature = Substitute.For<IServerVariablesFeature>();
var featureCollection = new FeatureCollection();
featureCollection.Set<IServerVariablesFeature>(serverVariablesFeature);
httpContext.Features.Returns(featureCollection);

var renderer = new AspNetRequestServerVariableLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Empty(result);
}

[Fact]
public void KeyFoundRendersValue()
{
var expectedResult = "value";
var httpContext = Substitute.For<HttpContextBase>();

var serverVariablesFeature = Substitute.For<IServerVariablesFeature>();
serverVariablesFeature["key"].Returns(expectedResult);
var featureCollection = new FeatureCollection();
featureCollection.Set<IServerVariablesFeature>(serverVariablesFeature);
httpContext.Features.Returns(featureCollection);

var renderer = new AspNetRequestServerVariableLayoutRenderer();
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);
renderer.Item = "key";

string result = renderer.Render(new LogEventInfo());

Assert.Equal(expectedResult, result);
}
#endif
}
}
Loading