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

ILoggingBuilder AddNLog extension method with correct dispose and no double logging #325

Merged
merged 1 commit into from
Sep 5, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
9 changes: 7 additions & 2 deletions src/NLog.Extensions.Hosting/Extensions/ConfigureExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Config;
Expand Down Expand Up @@ -41,7 +42,11 @@ public static IHostBuilder UseNLog(this IHostBuilder builder, NLogProviderOption
ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(ConfigureExtensions).GetTypeInfo()
.Assembly);

services.AddSingleton<ILoggerProvider>(serviceProvider =>
if (hostbuilder.Configuration != null)
ConfigSettingLayoutRenderer.DefaultConfiguration = hostbuilder.Configuration;

// Try adding Singleton-implementation if not already exists
services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, NLogLoggerProvider>(serviceProvider =>
{
var provider = new NLogLoggerProvider(options ?? new NLogProviderOptions());
if (hostbuilder.Configuration != null)
Expand All @@ -51,7 +56,7 @@ public static IHostBuilder UseNLog(this IHostBuilder builder, NLogProviderOption
provider.Configure(hostbuilder.Configuration.GetSection("Logging:NLog"));
}
return provider;
});
}));
});

return builder;
Expand Down
11 changes: 8 additions & 3 deletions src/NLog.Extensions.Logging/Extensions/ConfigureExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Configuration;
#if !NETCORE1_0
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
#endif
using Microsoft.Extensions.Logging;
using NLog.Common;
using NLog.Config;
Expand Down Expand Up @@ -67,8 +71,8 @@ public static ILoggingBuilder AddNLog(this ILoggingBuilder factory)
/// <returns>ILoggerFactory for chaining</returns>
public static ILoggingBuilder AddNLog(this ILoggingBuilder factory, IConfiguration configuration)
{
var provider = CreateNLogProvider(configuration);
factory.AddProvider(provider);
// Try adding Singleton-implementation if not already exists
factory.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, NLogLoggerProvider>(s => CreateNLogProvider(configuration)));
return factory;
}

Expand All @@ -80,7 +84,8 @@ public static ILoggingBuilder AddNLog(this ILoggingBuilder factory, IConfigurati
/// <returns>ILoggerFactory for chaining</returns>
public static ILoggingBuilder AddNLog(this ILoggingBuilder factory, NLogProviderOptions options)
{
factory.AddProvider(new NLogLoggerProvider(options));
// Try adding Singleton-implementation if not already exists
factory.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, NLogLoggerProvider>(s => new NLogLoggerProvider(options)));
return factory;
}
#endif
Expand Down
41 changes: 33 additions & 8 deletions test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ public class ExtensionMethodTests
public void UseNLog_noParams_WorksWithNLog()
{
var actual = new HostBuilder().UseNLog().Build();
TestHostingResult(actual);
TestHostingResult(actual, true);
}

[Fact]
public void UseNLog_withOptionsParam_WorksWithNLog()
{
var someParam = new NLogProviderOptions {CaptureMessageProperties = false, CaptureMessageTemplates = false};
var actual = new HostBuilder().UseNLog(someParam).Build();
TestHostingResult(actual);
TestHostingResult(actual, true);
}

[Fact]
Expand All @@ -35,26 +35,51 @@ public void UseNLog_withConfiguration_WorksWithNLog()

var someParam = new NLogProviderOptions { CaptureMessageProperties = false, CaptureMessageTemplates = false };
var actual = new HostBuilder().ConfigureHostConfiguration(config => config.AddInMemoryCollection(memoryConfig)).UseNLog(someParam).Build();
TestHostingResult(actual);
TestHostingResult(actual, true);
}

private static void TestHostingResult(IHost host)
[Fact]
public void AddNLog_withShutdownOnDispose_worksWithNLog()
{
var someParam = new NLogProviderOptions { ShutdownOnDispose = true };
var actual = new HostBuilder().ConfigureLogging(l => l.AddNLog(someParam)).Build();
try
{
TestHostingResult(actual, false);
Assert.NotNull(LogManager.Configuration);
}
finally
{
actual.Dispose();
Assert.Null(LogManager.Configuration);
}
}

[Fact]
public void UseNLog_withAddNLog_worksWithNLog()
{
var actual = new HostBuilder().UseNLog().ConfigureServices((h,s) => s.AddLogging(l => l.AddNLog())).Build();
TestHostingResult(actual, true);
}

private static void TestHostingResult(IHost host, bool resetConfiguration)
304NotModified marked this conversation as resolved.
Show resolved Hide resolved
{
try
{
var nlogTarget = new Targets.MemoryTarget() { Name = "Output" };
Config.SimpleConfigurator.ConfigureForTargetLogging(nlogTarget);
Config.SimpleConfigurator.ConfigureForTargetLogging(nlogTarget, LogLevel.Fatal);

var loggerFactory = host.Services.GetService<ILoggerFactory>();
Assert.NotNull(loggerFactory);

var logger = loggerFactory.CreateLogger("Hello");
logger.LogError("World");
Assert.NotEmpty(nlogTarget.Logs);
logger.LogCritical("World");
Assert.Single(nlogTarget.Logs);
}
finally
{
LogManager.Configuration = null;
if (resetConfiguration)
LogManager.Configuration = null;
}
}
}
Expand Down