Skip to content

Commit

Permalink
NLogProviderOptions with support for RegisterServiceProvider (#535)
Browse files Browse the repository at this point in the history
* NLogProviderOptions with support for RegisterServiceProvider

* Updated to NLog 5 preview 2 to fix unit-test
  • Loading branch information
snakefoot authored Oct 3, 2021
1 parent 039f13a commit e8a8db6
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 12 deletions.
7 changes: 7 additions & 0 deletions src/NLog.Extensions.Hosting/Extensions/ConfigureExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,14 @@ private static void AddNLogLoggerProvider(IServiceCollection services, IConfigur
private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serviceProvider, IConfiguration configuration, NLogProviderOptions options)
{
NLogLoggerProvider provider = new NLogLoggerProvider(options);

configuration = SetupConfiguration(serviceProvider, configuration);

if (serviceProvider != null && provider.Options.RegisterServiceProvider)
{
provider.LogFactory.ServiceRepository.RegisterService(typeof(IServiceProvider), serviceProvider);
}

if (configuration != null)
{
provider.Configure(configuration.GetSection("Logging:NLog"));
Expand Down
7 changes: 7 additions & 0 deletions src/NLog.Extensions.Logging/Extensions/ConfigureExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,14 @@ private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serv
private static NLogLoggerProvider CreateNLogLoggerProvider(IServiceProvider serviceProvider, IConfiguration configuration, NLogProviderOptions options, LogFactory logFactory)
{
NLogLoggerProvider provider = new NLogLoggerProvider(options ?? NLogProviderOptions.Default, logFactory ?? LogManager.LogFactory);

configuration = SetupConfiguration(serviceProvider, configuration);

if (serviceProvider != null && provider.Options.RegisterServiceProvider)
{
provider.LogFactory.ServiceRepository.RegisterService(typeof(IServiceProvider), serviceProvider);
}

if (configuration != null)
{
provider.Configure(configuration.GetSection("Logging:NLog"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ namespace NLog.Extensions.Logging
/// </example>
[LayoutRenderer("configsetting")]
[ThreadAgnostic]
[ThreadSafe]
public class ConfigSettingLayoutRenderer : LayoutRenderer
{
private IConfiguration _serviceConfiguration;

/// <summary>
/// Global Configuration Container
/// </summary>
Expand Down Expand Up @@ -66,14 +67,34 @@ public string Item
///</summary>
public string Default { get; set; }

/// <inheritdoc/>
protected override void InitializeLayoutRenderer()
{
try
{
// Avoid NLogDependencyResolveException when possible
if (!ReferenceEquals(ResolveService<IServiceProvider>(), LoggingConfiguration?.LogFactory?.ServiceRepository))
{
_serviceConfiguration = ResolveService<IConfiguration>();
}
}
catch (NLogDependencyResolveException ex)
{
_serviceConfiguration = null;
InternalLogger.Debug("ConfigSetting - Fallback to DefaultConfiguration: {0}", ex.Message);
}

base.InitializeLayoutRenderer();
}

/// <inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (string.IsNullOrEmpty(_itemLookup))
return;

string value = null;
var configurationRoot = DefaultConfiguration;
var configurationRoot = _serviceConfiguration ?? DefaultConfiguration;
if (configurationRoot != null)
{
value = configurationRoot[_itemLookup];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace NLog.Extensions.Logging
/// Renders output that simulates simple Microsoft Console Logger. Useful for Hosting Lifetime Startup Messages.
/// </summary>
[LayoutRenderer("MicrosoftConsoleLayout")]
[ThreadSafe]
[ThreadAgnostic]
class MicrosoftConsoleLayoutRenderer : LayoutRenderer
{
Expand Down
12 changes: 7 additions & 5 deletions src/NLog.Extensions.Logging/Logging/NLogProviderOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@ public class NLogProviderOptions
public string EventIdSeparator { get; set; } = "_";

/// <summary>
/// Skip allocation of <see cref="LogEventInfo.Properties" />-dictionary
/// Skip creating "EventId_Id" and "EventId_Name" as <see cref="LogEventInfo.Properties" /> when <c>default(EventId)</c>
/// </summary>
/// <remarks>
/// using
/// <c>default(EventId)</c></remarks>
public bool IgnoreEmptyEventId { get; set; } = true;

/// <summary>
Expand Down Expand Up @@ -79,7 +76,7 @@ public class NLogProviderOptions
public bool RemoveLoggerFactoryFilter { get; set; } = true;

/// <summary>
/// Replace Microsoft LoggerFactory with a pure <see cref="NLogLoggerFactory" />, and disables Microsoft Filter Logic and multiple LoggingProvider support.
/// Replace Microsoft LoggerFactory with a pure <see cref="NLogLoggerFactory" />, and disables Microsoft Filter Logic and removes other LoggingProviders.
/// </summary>
/// <remarks>This option affects the building of service configuration, so assigning it from appsettings.json has no effect (loaded after).</remarks>
public bool ReplaceLoggerFactory { get; set; }
Expand All @@ -98,6 +95,11 @@ public class NLogProviderOptions
/// </remarks>
public bool CaptureEntireEventId { get; set; }

/// <summary>
/// Enable NLog Targets and Layouts to perform dependency lookup using the Microsoft Dependency Injection IServiceProvider
/// </summary>
public bool RegisterServiceProvider { get; set; } = true;

/// <summary>Initializes a new instance NLogProviderOptions with default values.</summary>
public NLogProviderOptions()
{
Expand Down
2 changes: 1 addition & 1 deletion src/NLog.Extensions.Logging/NLog.Extensions.Logging.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Full changelog: https://github.com/NLog/NLog.Extensions.Logging/blob/master/CHAN
<DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0-preview.1" />
<PackageReference Include="NLog" Version="5.0.0-preview.2" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
Expand Down
3 changes: 3 additions & 0 deletions test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ public void UseNLog_LoadConfigurationFromSection()

var loggerFact = host.Services.GetService<ILoggerFactory>();
var logger = loggerFact.CreateLogger("logger1");

ConfigSettingLayoutRenderer.DefaultConfiguration = null; // See dependency resolving is working

logger.LogError("error1");

var loggerProvider = host.Services.GetService<ILoggerProvider>() as NLogLoggerProvider;
Expand Down
6 changes: 3 additions & 3 deletions test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class CustomBeginScopeTest : NLogTestBase
public void TestNonSerializableSayHello()
{
var runner = GetRunner<CustomBeginScopeTestRunner>();
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${ndlc}" };
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${scopenested}" };
ConfigureNLog(target);
runner.SayHello().Wait();
Assert.Single(target.Logs);
Expand All @@ -24,7 +24,7 @@ public void TestNonSerializableSayHello()
public void TestNonSerializableSayHelloWithScope()
{
var runner = GetRunner<CustomBeginScopeTestRunner>(new NLogProviderOptions { IncludeScopes = false });
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${ndlc}" };
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${scopenested}" };
ConfigureNLog(target);
runner.SayHello().Wait();
Assert.Single(target.Logs);
Expand All @@ -35,7 +35,7 @@ public void TestNonSerializableSayHelloWithScope()
public void TestNonSerializableSayHi()
{
var runner = GetRunner<CustomBeginScopeTestRunner>();
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${ndlc}" };
var target = new Targets.MemoryTarget { Layout = "${message} ${scopeproperty:World}. Welcome ${scopenested}" };
ConfigureNLog(target);
var scopeString = runner.SayHi().Result;
Assert.Single(target.Logs);
Expand Down

0 comments on commit e8a8db6

Please sign in to comment.