Asp.Net Core 项目中使用 Serilog 输出日志到 Elasticsearch
环境说明
服务器:CentOS 7,IP:172.17.79.83
开发环境:Win10 + VS2019
Docker 启动 Elasticsearch
docker run --name elasticsearch --restart always -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.5.0
Docker 启动 Kibana
docker run --name kibana --restart always -d --link elasticsearch:elasticsearch -p 5601:5601 kibana:7.5.0
项目配置
创建一个 WebAPI 项目,添加 nuget 包 Serilog.AspNetCore(目前最新版本 3.4.0)、Serilog.Sinks.Elasticsearch(v8.2.0)、Serilog.Exceptions(v5.6.0)。
将默认的 appsettings.json 中的内容替换成一下内容。
{ "Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Information", "System": "Warning" } } }, "ElasticConfiguration": { "Uri": "http://172.17.79.83:9200" }, "AllowedHosts": "*" }
Program.cs 中配置 Serilog
1 using System; 2 using System.Reflection; 3 using Microsoft.AspNetCore.Hosting; 4 using Microsoft.Extensions.Configuration; 5 using Microsoft.Extensions.Hosting; 6 using Serilog; 7 using Serilog.Sinks.Elasticsearch; 8 using Serilog.Exceptions; 9 10 namespace EFKlog 11 { 12 public class Program 13 { 14 private static readonly string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); 15 public static void Main(string[] args) 16 { 17 ConfigureLogging(); 18 19 CreateHostBuilder(args).Build().Run(); 20 } 21 22 public static IHostBuilder CreateHostBuilder(string[] args) => 23 Host.CreateDefaultBuilder(args) 24 .ConfigureWebHostDefaults(webBuilder => 25 { 26 webBuilder.UseStartup<Startup>() 27 .ConfigureAppConfiguration(cfg=> 28 { 29 cfg.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); 30 cfg.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true); 31 }) 32 .UseSerilog(); 33 }); 34 35 private static void ConfigureLogging() 36 { 37 var cfg = new ConfigurationBuilder() 38 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 39 .AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true) 40 .Build(); 41 Log.Logger = new LoggerConfiguration() 42 .Enrich.FromLogContext() 43 .Enrich.WithExceptionDetails() 44 .Enrich.WithProperty("Environment",env) 45 .WriteTo.Debug() 46 .WriteTo.Console() 47 .WriteTo.Elasticsearch(ConfigureElasticSink(cfg, env)) 48 .ReadFrom.Configuration(cfg) 49 .CreateLogger(); 50 } 51 52 private static ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot cfg,string env) 53 { 54 return new ElasticsearchSinkOptions(new Uri(cfg["ElasticConfiguration:Uri"])) 55 { 56 AutoRegisterTemplate = true, 57 IndexFormat = $"{Assembly.GetExecutingAssembly().GetName().Name.ToLower().Replace(".", "-")}-{env?.ToLower().Replace(".", "-")}-{DateTime.UtcNow:yyyy-MM}" 58 }; 59 } 60 } 61 }
在 api 中记录日志。
public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("WeatherForecast api executed at {date}",DateTime.UtcNow); try { throw new Exception("some bad code was executed..."); } catch (Exception ex) { _logger.LogError(ex, "调用天气预报 api 出现错误!"); } 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(); }
启动项目,可以看到控制台日志格式发生了一点变化,同时日志消息使用了不同的颜色来区分。
在 kibana 中查看日志,需要先创建一个索引。index 格式在Program.cs 中有设置,这里保持写法一致就好。
查看 kibana 面板,需要展示的列可以自定义,比如添加 exception 列。