.NET Non-host LoggerFactory configuration

1.9k Views Asked by At

I am trying to add logging to an existing .NET Framework application. I have added my own logger (called MyLogger) and put the config settings into appsettings.json like this:

{
  "LogFilePath": "C:\\Temp\\Logs\\%yyyy-%MM-%dd.txt",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    },
    "MyLogger": {
      "LogLevel": {
        "Default": "Error"
      }
    }
  }
}

I am able to read the config settings like this:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json");

var configuration = configurationBuilder.Build();

I want to keep it simple and not use a host. I am able to create a LoggerFactory like this:

var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
    loggingBuilder
        .ClearProviders()
        .AddMyLogger(loggerConfig =>
        {
            loggerConfig.FilePath = configuration["LogFilePath"];
        });
});
ILogger logger = loggerFactory.CreateLogger("Global");
logger.LogInformation("Application starting");

How do I wire up configuration settings from appsettings.json to the LoggerFactory? For example, in the above code, LogInformation() should not log anything because my appsettings.json sets the minimum log level to Error for MyLogger.

1

There are 1 best solutions below

0
On

There is an extension method called AddConfiguration() but you need to reference:

using Microsoft.Extensions.Configuration;

So the code looks like this:

//Create logger factory
var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
    loggingBuilder
        .ClearProviders()
        .AddConfiguration(configuration.GetSection("Logging"))
        .AddMyLogger(loggerConfig =>
        {
            loggerConfig.FilePath = configuration["LogFilePath"];
        });
});

//Create logger
ILogger logger = loggerFactory.CreateLogger("Global");
logger.LogInformation("Application starting");

Additionally, alias the logger provider name like this:

[ProviderAlias("My")]
public sealed class MyLoggerProvider : ILoggerProvider
{ ... }

Then in appsettings.json, you can use the alias "My" to apply filters to your logger provider:

{
  "LogFilePath": "C:\\Temp\\Logs\\%yyyy-%MM-%dd.txt",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    },
    "My": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Warning"
      }
    }
  }
}