1.19 日志作用域:解决不同请求之间的日志干扰.pdf

    appsettings.json:

    1. {
    2. "Logging": {
    3. "LogLevel": {
    4. "Default": "Debug",
    5. "Microsoft": "Warning",
    6. "Microsoft.Hosting.Lifetime": "Information"
    7. },
    8. "Console": {
    9. "IncludeScopes": true,
    10. "LogLevel": {
    11. "Default": "Information",
    12. "LoggingScopeDemo.Program": "Trace",
    13. "alogger": "Trace"
    14. }
    15. }
    16. }
    17. }

    Scoped 示例代码:

    1. static void Main(string[] args)
    2. {
    3. var configBuilder = new ConfigurationBuilder();
    4. configBuilder.AddCommandLine(args);
    5. configBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    6. var config = configBuilder.Build();
    7. IServiceCollection serviceCollection = new ServiceCollection();
    8. serviceCollection.AddSingleton(p => config); // 用工厂模式将配置对象注册到容器管理
    9. serviceCollection.AddLogging(builder =>
    10. {
    11. builder.AddConfiguration(config.GetSection("Logging"));
    12. builder.AddConsole();
    13. builder.AddDebug();
    14. });
    15. IServiceProvider service = serviceCollection.BuildServiceProvider();
    16. var logger = service.GetService<ILogger<Program>>();
    17. while (Console.ReadKey().Key != ConsoleKey.Escape)
    18. {
    19. using (logger.BeginScope("ScopeId:{scopeId}", Guid.NewGuid()))
    20. {
    21. logger.LogTrace("这是 Trace");
    22. logger.LogInformation("这是 Info");
    23. logger.LogError("这是 Error");
    24. }
    25. System.Threading.Thread.Sleep(100);
    26. Console.WriteLine("============ 分割线 ============");
    27. }
    28. Console.ReadKey();
    29. }

    效果:
    image.png