Skip to content

Commit

Permalink
Merge pull request #428 from NLog/register-lambda
Browse files Browse the repository at this point in the history
Added AspNetLayoutRendererBase.Register for registering lambdas with httpcontext
  • Loading branch information
repo-ranger[bot] authored Jun 5, 2019
2 parents a3f67ff + 12cf47a commit dab12cc
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog.Web.AspNetCore2.Example.Models;
using NLog.Web.LayoutRenderers;

namespace NLog.Web.AspNetCore2.Example.Controllers
{
Expand Down
2 changes: 1 addition & 1 deletion src/NLog.Web.AspNetCore/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74d5915b-bea9-404c-b4d0-b663164def37")]
[assembly:InternalsVisibleTo("NLog.Web.AspNetCore.Tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100ef8eab4fbdeb511eeb475e1659fe53f00ec1c1340700f1aa347bf3438455d71993b28b1efbed44c8d97a989e0cb6f01bcb5e78f0b055d311546f63de0a969e04cf04450f43834db9f909e566545a67e42822036860075a1576e90e1c43d43e023a24c22a427f85592ae56cac26f13b7ec2625cbc01f9490d60f16cfbb1bc34d9")]
[assembly: InternalsVisibleTo("NLog.Web.AspNetCore.Tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100772391e63c104728adcf18e2390474262559fa7f34a4215848f43288cde875dcc92a06222e9be0592b211ff74adbb5d21a7aab5522b540b1735f2f03279221056fedbe7e534073dabee9db48f8ecebcf1dc98a95576e45cbeff5fe7c4842859451ab2dae7a8370f1b2f7a529d2ca210e3e844d973523d73d193df6c17f1314a6")]
1 change: 1 addition & 0 deletions src/NLog.Web/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74d5915b-bea9-404c-b4d0-b663164def37")]
[assembly: InternalsVisibleTo("NLog.Web.Tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100772391e63c104728adcf18e2390474262559fa7f34a4215848f43288cde875dcc92a06222e9be0592b211ff74adbb5d21a7aab5522b540b1735f2f03279221056fedbe7e534073dabee9db48f8ecebcf1dc98a95576e45cbeff5fe7c4842859451ab2dae7a8370f1b2f7a529d2ca210e3e844d973523d73d193df6c17f1314a6")]
51 changes: 30 additions & 21 deletions src/Shared/LayoutRenderers/AspNetLayoutRendererBase.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,34 @@
using System;
using System.Linq;
using System.Text;

using NLog.Common;
using NLog.Config;
using NLog.LayoutRenderers;
#if ASP_NET_CORE
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using NLog.Web.DependencyInjection;

using HttpContextBase = Microsoft.AspNetCore.Http.HttpContext;
#else
using System.Web;
#endif



namespace NLog.Web.LayoutRenderers
{
/// <summary>
/// Base class for ASP.NET layout renderers.
/// </summary>
public abstract class AspNetLayoutRendererBase : LayoutRenderer
{
/// <summary>
/// Initializes the <see cref="AspNetLayoutRendererBase" />.
/// </summary>
protected AspNetLayoutRendererBase()
{
#if !ASP_NET_CORE
HttpContextAccessor = new DefaultHttpContextAccessor();
#endif
}


#if ASP_NET_CORE

/// <summary>
/// Context for DI
/// </summary>
private IHttpContextAccessor _httpContextAccessor;


/// <summary>
/// Provides access to the current request HttpContext.
/// </summary>
Expand All @@ -47,6 +40,13 @@ public IHttpContextAccessor HttpContextAccessor
set => _httpContextAccessor = value;
}

#if !ASP_NET_CORE

internal static IHttpContextAccessor DefaultHttpContextAccessor { get; set; } = new DefaultHttpContextAccessor();

private static IHttpContextAccessor RetrieveHttpContextAccessor() => DefaultHttpContextAccessor;
#else

private static IHttpContextAccessor RetrieveHttpContextAccessor()
{
var serviceProvider = ServiceLocator.ServiceProvider;
Expand All @@ -73,12 +73,7 @@ private static IHttpContextAccessor RetrieveHttpContextAccessor()
}
}

#else
/// <summary>
/// Provides access to the current request HttpContext.
/// </summary>
[NLog.Config.NLogConfigurationIgnorePropertyAttribute]
public IHttpContextAccessor HttpContextAccessor { get; set; }


#endif

Expand Down Expand Up @@ -122,5 +117,19 @@ protected override void CloseLayoutRenderer()
base.CloseLayoutRenderer();
}
#endif


/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="func" />. The callback recieves the logEvent and the current configuration.
/// </summary>
/// <param name="name">Name of the layout renderer - without ${}.</param>
/// <param name="func">Callback that returns the value for the layout renderer.</param>
public static void Register(string name, Func<LogEventInfo, HttpContextBase, LoggingConfiguration, object> func)
{
object NewFunc(LogEventInfo logEventInfo, LoggingConfiguration configuration) => func(logEventInfo, RetrieveHttpContextAccessor()?.HttpContext, configuration);

Register(name, NewFunc);
}
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
<InformationalVersion>1.2.3.2</InformationalVersion>
<DebugType Condition=" '$(TargetFramework)' == 'net461' ">Full</DebugType>
<DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../../NLog.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.1' ">
<DefineConstants>$(DefineConstants);ASP_NET_CORE;ASP_NET_CORE1</DefineConstants>
Expand Down
2 changes: 2 additions & 0 deletions tests/NLog.Web.Tests/NLog.Web.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<AssemblyVersion>1.2.3.0</AssemblyVersion>
<FileVersion>1.2.3.1</FileVersion>
<DebugType>full</DebugType>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../../NLog.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.*" />
Expand Down
42 changes: 11 additions & 31 deletions tests/Shared/LayoutRenderers/AspNetCookieLayoutRendererTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,52 +329,32 @@ public void KeyFoundRendersValue_Multiple_Cookies_And_Cookie_Values_Json_Formatt
[Fact]
public void CommaSeperatedCookieNamesTest_Multiple_Cookie_Values_Flat_Formatting()
{
// Arrange
var expectedResult = "key=TEST&Key1=TEST1";

string config = @"<nlog>
<extensions>
<add assembly='NLog.Web' />
</extensions>
<targets><target name='debug' type='Debug' layout='${aspnet-request-cookie:CookieNames=key,key1}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
LogManager.Configuration = CreateConfigurationFromString(config);

var cookie = new HttpCookie("key", "TEST");
cookie["Key1"] = "TEST1";
var cookie = new HttpCookie("key", "TEST") {["Key1"] = "TEST1"};

HttpContext.Request.Cookies.Add(cookie);
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var renderer = ((SimpleLayout)t.Layout).Renderers[0] as AspNetRequestCookieLayoutRenderer;
Layout layout = "${aspnet-request-cookie:CookieNames=key,key1}";

var result = renderer.Render(LogEventInfo.CreateNullEvent());
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());

// Assert
Assert.Equal(expectedResult, result);
}

[Fact]
public void CommaSeperatedCookieNamesTest_Multiple_Cookie_Values_Json_Formatting()
{
var expectedResult = "[{\"key\":\"TEST\"},{\"Key1\":\"TEST1\"}]";

string config = @"<nlog>
<extensions>
<add assembly='NLog.Web' />
</extensions>
<targets><target name='debug' type='Debug' layout='${aspnet-request-cookie:CookieNames=key,key1:OutputFormat=Json}' /></targets>
</nlog>";
LogManager.Configuration = CreateConfigurationFromString(config);

var cookie = new HttpCookie("key", "TEST");
cookie["Key1"] = "TEST1";


var cookie = new HttpCookie("key", "TEST") {["Key1"] = "TEST1"};
HttpContext.Request.Cookies.Add(cookie);
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var renderer = ((SimpleLayout)t.Layout).Renderers[0] as AspNetRequestCookieLayoutRenderer;

var result = renderer.Render(LogEventInfo.CreateNullEvent());
Layout layout = "${aspnet-request-cookie:CookieNames=key,key1:OutputFormat=Json}";

var result = layout.Render(LogEventInfo.CreateNullEvent());

Assert.Equal(expectedResult, result);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,6 @@ public void NullVarname()
ExecTest("a", o, "", appSettingLayoutRenderer);
}


[Fact]
public void SessionWithPadding()
{
Layout layout = "${aspnet-session:a.b:padding=5:evaluateAsNestedProperties=true}";

var o = new { b = "c" };
//set in "a"
ExecTest("a", o, " c", layout);
}


[Fact]
public void SessionWithCulture()
{
Expand All @@ -202,11 +190,12 @@ public void SessionWithCulture()
/// <remarks>IRenderable is internal</remarks>
private void ExecTest(string key, object value, object expected, Layout appSettingLayoutRenderer)
{
Session[key] = value;
var simpleLayout = (appSettingLayoutRenderer as SimpleLayout);
var renderer = simpleLayout?.Renderers[0] as AspNetLayoutRendererBase;

var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent());
Assert.NotNull(renderer);

Assert.Equal(expected, rendered);
ExecTest(key, value, expected, renderer);
}

/// <summary>
Expand All @@ -217,9 +206,9 @@ private void ExecTest(string key, object value, object expected, Layout appSetti
/// <param name="expected">expected</param>
/// <param name="appSettingLayoutRenderer"></param>
/// <remarks>IRenderable is internal</remarks>
private void ExecTest(string key, object value, object expected, LayoutRenderer appSettingLayoutRenderer)
private void ExecTest(string key, object value, object expected, AspNetLayoutRendererBase appSettingLayoutRenderer)
{
Session[key] = value;
appSettingLayoutRenderer.HttpContextAccessor.HttpContext.Session[key] = value;

var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent());

Expand Down
85 changes: 85 additions & 0 deletions tests/Shared/RegisterCustomLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


using NLog.Layouts;
#if ASP_NET_CORE
using Microsoft.AspNetCore.Http;
using NLog.Web.DependencyInjection;
#else
using System.Web;
#endif
using NLog.Web.LayoutRenderers;
using NLog.Web.Tests.LayoutRenderers;
using NSubstitute;
using Xunit;

namespace NLog.Web.AspNetCore.Tests
{
public class RegisterCustomLayoutRenderer : TestBase
{
#if !ASP_NET_CORE
~RegisterCustomLayoutRenderer()
{
AspNetLayoutRendererBase.DefaultHttpContextAccessor = new DefaultHttpContextAccessor();
}
#endif

[Fact]
public void RegisterLayoutRendererTest()
{
var httpcontextMock = SetupHttpAccessorWithHttpContext();
#if ASP_NET_CORE
httpcontextMock.Connection.LocalPort.Returns(123);
#else
httpcontextMock.Request.RawUrl.Returns("123");

#endif

// Act
AspNetLayoutRendererBase.Register("test-web",
(logEventInfo, httpContext, loggingConfiguration) =>
#if ASP_NET_CORE
httpContext.Connection.LocalPort);
#else
httpContext.Request.RawUrl);
#endif
Layout l = "${test-web}";
var restult = l.Render(LogEventInfo.CreateNullEvent());

// Assert
Assert.Equal("123", restult);
}

private static
#if ASP_NET_CORE
HttpContext
#else
HttpContextBase
#endif

SetupHttpAccessorWithHttpContext()
{
var httpContextAccessorMock = Substitute.For<IHttpContextAccessor>();


#if ASP_NET_CORE
var serviceProviderMock = Substitute.For<IServiceProvider>();
serviceProviderMock.GetService(typeof(IHttpContextAccessor)).Returns(httpContextAccessorMock);
var httpcontext = Substitute.For<HttpContext>();
ServiceLocator.ServiceProvider = serviceProviderMock;
#else
var httpcontext = Substitute.For<HttpContextBase>();
httpContextAccessorMock.HttpContext.Returns(httpcontext);
AspNetLayoutRendererBase.DefaultHttpContextAccessor = httpContextAccessorMock;
#endif


httpContextAccessorMock.HttpContext.Returns(httpcontext);
return httpcontext;
}
}
}

0 comments on commit dab12cc

Please sign in to comment.