appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Information",
"LoggingScopeDemo.Program": "Trace",
"alogger": "Trace"
}
}
}
}
Scoped 示例代码:
static void Main(string[] args)
{
var configBuilder = new ConfigurationBuilder();
configBuilder.AddCommandLine(args);
configBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = configBuilder.Build();
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(p => config); // 用工厂模式将配置对象注册到容器管理
serviceCollection.AddLogging(builder =>
{
builder.AddConfiguration(config.GetSection("Logging"));
builder.AddConsole();
builder.AddDebug();
});
IServiceProvider service = serviceCollection.BuildServiceProvider();
var logger = service.GetService<ILogger<Program>>();
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
using (logger.BeginScope("ScopeId:{scopeId}", Guid.NewGuid()))
{
logger.LogTrace("这是 Trace");
logger.LogInformation("这是 Info");
logger.LogError("这是 Error");
}
System.Threading.Thread.Sleep(100);
Console.WriteLine("============ 分割线 ============");
}
Console.ReadKey();
}
效果: