.net core 日志作用域:解决不同请求之间的日志干扰 电脑版发表于:2020/7/17 16:22 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 日志作用域:解决不同请求之间的日志干扰 [TOC] <br/> 作用域的场景 ------------ - 一个事务包含多条操作时 - 复杂流程的日志关联时 - 调用链追踪域请求处理过程对应时 内容示例 ------------ >###项目架构 ![项目架构](https://img.tnblog.net/arcimg/hb/9e4498debd614f2bb004064d3aaafb63.png) >###内容示例 <br/> ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp class Program { static void Main(string[] args) { //必要的包 //从文件中读取配置 IConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.AddCommandLine(args); configBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); var config = configBuilder.Build(); IServiceCollection serviceCollection = new ServiceCollection(); //用工厂模式将配置对象注册到容器管理 serviceCollection.AddSingleton<IConfiguration>(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.LogInformation("这是Info"); logger.LogError("这是Error"); logger.LogTrace("这是Trace"); } System.Threading.Thread.Sleep(100); Console.WriteLine("=====================分割线====================="); } Console.ReadKey(); } } ``` ><font style="color:#f1c40f;font-weight:bold;">appsetting.json</font> ```json { "Logging": { "LogLevel": { "Default": "Debug", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }, //下面是针对 Console 的输出提供程序 "Console": { "IncludeScopes": true, "LogLevel": { "Default": "Information", "LoggingSimpleDemo.Program": "Trace", "alogger": "Trace" } } } } ``` >运行结果(中途有经多次修改) ![](https://img.tnblog.net/arcimg/hb/68e4ad27ca9d47c58b88f2fbd709cf71.png)