Serilog添加ES配置
服务端Elasticsearch
+Kibana
的部署参考这篇博客,版本都是当前最新版本8.5.0
Serilog
相关文档参考这篇博客
新建一个ASP.NET Core Web项目,添加以下Neget包
Serilog.AspNetCore
Serilog.Extensions.Logging
Serilog.Sinks.Elasticsearch
Program.cs
添加Serilog
并添加ES
相关配置
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using System;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseSerilog((hostingContext, loggerConfiguration) =>
{
string environment = "Development";
loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
//过滤Net Core系统日志
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.WriteTo.Console()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://192.168.1.5:9200/"))
{
//OverwriteTemplate和TypeName一定要加,不然ES8无法写入日志
IndexFormat = "muxue-{0:yyyy.MM.dd}",
//IndexFormat = $"{Assembly.GetExecutingAssembly().GetName().Name.ToLower().Replace(".", "-")}-{environment?.ToLower().Replace(".", "-")}-{DateTime.UtcNow:yyyy-MM}",
AutoRegisterTemplate = true,
OverwriteTemplate = true,
//TemplateName = "",
FailureCallback = e => Console.WriteLine("Unable to submit event " + e.MessageTemplate),
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
TypeName = null,
MinimumLogEventLevel = LogEventLevel.Verbose,
EmitEventFailure = EmitEventFailureHandling.RaiseCallback,
ModifyConnectionSettings =
conn =>
{
//conn.BasicAuthentication("elastic", "123456");
conn.ServerCertificateValidationCallback((source, certificate, chain, sslPolicyErrors) => false);
return conn;
}
});
});
}
}
字段 | 备注 |
---|---|
ElasticsearchSinkOptions(URL) | ES访问地址 |
IndexFormat | ES索引,可自定义。{0:yyyy.MM.dd} 表示日期 |
AutoRegisterTemplate | 是否ES日志自动注册一个索引模板。 |
OverwriteTemplate | 是否覆盖ES日志默认模板,ES8默认不支持写入,需要加此配置 |
TemplateName | ES日志模板 |
EmitEventFailure | 设置了当失败时调用FailureCallback |
FailureCallback | 日志发送失败触发事件 |
AutoRegisterTemplateVersion | ES模板版本 |
MinimumLogEventLevel | 最低日志等级 |
TypeName | ES8默认不支持写入,需要加此配置 |
ModifyConnectionSettings | ES认证,用户登录+是否开启SSL(Https) |
WeatherForecastController.cs
写入日志并访问API
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
_logger.LogInformation("我爱中国");
_logger.LogInformation(Guid.NewGuid().ToString());
return Guid.NewGuid().ToString();
}
}
}
Kibana查询日志
开发工具用API查询ES日志
控制台中输入索引查询日志(*代表所有),查询到日志表示添加成功
GET /muxue-*/_search