Skip to content

Commit

Permalink
LogManager.Setup() - SetupBuilderExtension with LoadConfigurationFrom…
Browse files Browse the repository at this point in the history
…AppSettings
  • Loading branch information
snakefoot committed Apr 26, 2020
1 parent ef56917 commit b4e202f
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 1 deletion.
3 changes: 2 additions & 1 deletion examples/ASP.NET Core 3/ASP.NET Core 3 - VS2019/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().LogFactory.GetCurrentClassLogger();

try
{
logger.Debug("init main");
Expand Down
81 changes: 81 additions & 0 deletions src/NLog.Web.AspNetCore/Config/SetupBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;
#if ASP_NET_CORE3
using System.IO;
#endif
using System.Linq;
using Microsoft.Extensions.Configuration;
using NLog.Config;
using NLog.Extensions.Logging;
using NLog.Web.DependencyInjection;

namespace NLog.Web
{
/// <summary>
/// Extension methods to setup LogFactory options
/// </summary>
public static class SetupBuilderExtensions
{
#if ASP_NET_CORE3
/// <summary>
/// Loads NLog LoggingConfiguration from appsettings.json from the NLog-section
/// </summary>
public static ISetupBuilder LoadConfigurationFromAppSettings(this ISetupBuilder setupBuilder, string basePath = null, string environment = null, bool optional = true, bool reloadOnChange = false)
{
var builder = new ConfigurationBuilder()
.SetBasePath(basePath ?? Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional, reloadOnChange)
.AddJsonFile($"appsettings.{(environment ?? GetAspNetCoreEnvironment("DOTNET_ENVIRONMENT") ?? GetAspNetCoreEnvironment("ASPNETCORE_ENVIRONMENT") ?? "Production")}.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: reloadOnChange)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.AddEnvironmentVariables(prefix: "DOTNET_");
var config = builder.Build();
return setupBuilder.RegisterNLogWeb().LoadConfigurationFromSection(config);
}

private static string GetAspNetCoreEnvironment(string variableName)
{
try
{
var environment = Environment.GetEnvironmentVariable(variableName);
if (string.IsNullOrWhiteSpace(environment))
return null;

return environment.Trim();
}
catch (Exception ex)
{
NLog.Common.InternalLogger.Error(ex, "Failed to lookup environment variable {0}", variableName);
return null;
}
}
#endif

/// <summary>
/// Convience method to register aspnet-layoutrenders in NLog.Web as one-liner before loading NLog.config
/// </summary>
/// <remarks>
/// If not providing <paramref name="serviceProvider"/>, then output from aspnet-layoutrenderers will remain empty
/// </remarks>
public static ISetupBuilder RegisterNLogWeb(this ISetupBuilder setupBuilder, IServiceProvider serviceProvider = null)
{
setupBuilder.SetupExtensions(s => s.RegisterNLogWeb());
if (serviceProvider != null)
ServiceLocator.ServiceProvider = serviceProvider;
return setupBuilder;
}

/// <summary>
/// Replace with version from NLog.Extension.Logging when it has been released with NLog 4.7
/// </summary>
internal static ISetupBuilder LoadConfigurationFromSection(this ISetupBuilder setupBuilder, IConfiguration configuration)
{
setupBuilder.SetupExtensions(e => e.RegisterConfigSettings(configuration));
var nlogConfig = configuration.GetSection("NLog");
if (nlogConfig != null && nlogConfig.GetChildren().Any())
{
setupBuilder.LogFactory.Configuration = new NLogLoggingConfiguration(nlogConfig, setupBuilder.LogFactory);
}
return setupBuilder;
}
}
}
30 changes: 30 additions & 0 deletions src/NLog.Web.AspNetCore/Config/SetupExtensionsBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Reflection;
using Microsoft.Extensions.Configuration;
using NLog.Config;
using NLog.Extensions.Logging;

namespace NLog.Web
{
/// <summary>
/// Extension methods to setup NLog extensions, so they are known when loading NLog LoggingConfiguration
/// </summary>
public static class SetupExtensionsBuilderExtensions
{
/// <summary>
/// Replace with version from NLog.Extension.Logging when it has been released with NLog 4.7
/// </summary>
internal static ISetupExtensionsBuilder RegisterConfigSettings(this ISetupExtensionsBuilder setupBuilder, IConfiguration configuration)
{
ConfigSettingLayoutRenderer.DefaultConfiguration = configuration;
return setupBuilder.RegisterLayoutRenderer<ConfigSettingLayoutRenderer>("configsetting");
}

/// <summary>
/// Register the NLog.Web.AspNetCore LayoutRenderers
/// </summary>
public static ISetupExtensionsBuilder RegisterNLogWeb(this ISetupExtensionsBuilder setupBuilder)
{
return setupBuilder.RegisterAssembly(typeof(NLogAspNetCoreOptions).GetTypeInfo().Assembly);
}
}
}
1 change: 1 addition & 0 deletions src/NLog.Web.AspNetCore/NLog.Web.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ See also https://github.com/NLog/NLog.Web/releases
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.2" />
<PackageReference Include="NLog" Version="4.7.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
<Reference Include="System" />
Expand Down

0 comments on commit b4e202f

Please sign in to comment.