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.
There is an extension method called AddConfiguration() but you need to reference:
So the code looks like this:
Additionally, alias the logger provider name like this:
Then in appsettings.json, you can use the alias "My" to apply filters to your logger provider: