.net core 结构化日志组件Serilog:记录对查询分析友好的日志 电脑版发表于:2020/7/22 10:17 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 结构化日志组件Serilog:记录对查询分析友好的日志 [TOC] <br/> 结构化日志的好处 ------------ - 易于检索 - 易于分析统计 场景举例 ------------ - 实现日志警告 - 实现上下文的关联 - 实现与追踪系统集成 内容实践 ------------ >安装相关依赖包 https://www.nuget.org/packages/Serilog.AspNetCore >配置日志级别 <font style="color:#f1c40f;font-weight:bold;">appsetting.json</font> ```json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Information", "System": "Information" } } }, "AllowedHosts": "*" } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp public class Program { public static IConfiguration Configuration => new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCOre_ENVIRONMENT") ?? "Production"}.json") .AddEnvironmentVariables() .Build(); public static int Main(string[] args) { Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration) .MinimumLevel.Debug()//最小级别 .Enrich.FromLogContext()//使用Serilog.Context.LogContext中的属性来丰富日志事件。 .WriteTo.Console(new RenderedCompactJsonFormatter())//控制台使用Json格式输出 .WriteTo.File(formatter: new CompactJsonFormatter(), "logs\\myapp.txt", rollingInterval: RollingInterval.Day)//天为单位以Json格式输出到指定的文件中去 .CreateLogger();//创建日志 try { Log.Information("Starting web host"); CreateHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseSerilog(dispose:true); } ``` ><font style="color:#2ecc71;font-weight:bold;">WeatherForecastController.cs</font> ```csharp [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("Create a log data"); var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } ``` >运行效果 ![运1](https://img.tnblog.net/arcimg/hb/0ff12b85632e43cd8dc48efde01647fd.png "运1") >这里我们在最后一行看得到`Create a log data`,但日志太多了很难看到我们想要的东西,所以我们可以对<font style="color:#f1c40f;font-weight:bold;">appsetting.json</font>进行修改,将日志级别调高为`Error` ```json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "Serilog": { "MinimumLevel": { "Default": "Error", "Override": { "Microsoft": "Error", "System": "Information" } } }, "AllowedHosts": "*" } ``` >第二次运行 ![](https://img.tnblog.net/arcimg/hb/7004bf07f5494092b0ae43640503176f.png)