ASP.NET Core Serilog ElasticSearch Format

目录

[ASP.NET Core 使用Serilog Format ElasticSearch]
在使用微服务框架EFK收集ASP.NET Core日志的时候,默认Console.Log 打印出来的Log被ElasticSearch+Fluentd收集后颜色属性会产生乱码(低版本ES会直接报错)
本篇将介绍 使用Serilog的ElasticSearch Format收集日志

1. 安装NuGet包

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.ElasticSearch

2. Startup

Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseSerilog((ctx, config) =>
{
config
.MinimumLevel.Information()
.Enrich.FromLogContext();

if (ctx.HostingEnvironment.IsDevelopment())
{
config.WriteTo.Console();
}
else
{
config.WriteTo.Console(new ElasticsearchJsonFormatter());
}
})

参考

writing-logs-to-elasticsearch-with-fluentd-using-serilog-in-asp-net-core