https://www.rokrode.com/2021-10-09-logging-in-net-core-console/
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appSettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
Console.WriteLine("Hello, World!");
ConfigurationManager configurationManager = new ConfigurationManager();
//configurationManager.SetBasePath(Directory.GetCurrentDirectory());
configurationManager.AddJsonFile("appSettings.json");
using var loggerFactory = LoggerFactory.Create(builder =>
{
var loggingConfig = configurationManager.GetSection("Logging");
builder.AddConfiguration(loggingConfig);
builder.AddSimpleConsole(options =>
{
options.SingleLine = true;
});
});
Console.WriteLine(configurationManager["Logging:LogLevel:Default"]);
Console.WriteLine(configurationManager.GetSection("Logging:LogLevel").GetChildren().Count());
var builder = configurationManager as IConfigurationBuilder;
var root = builder.Build();
Console.WriteLine(root["Logging:LogLevel:Default"]);
var serviceLogger = loggerFactory.CreateLogger("Demo.Service");
serviceLogger.LogInformation("This is service log");
var customerLogger = loggerFactory.CreateLogger("Demo.Customer");
customerLogger.LogInformation("This is customer log");
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Demo.Service": "Information",
"Demo.Customer": "Information"
}
},
"AllowedHosts": "*"
}