如何为Elastic.Serilog.Sinks配置ApiKey认证以写入Elasticsearch
如何为Elastic.Serilog.Sinks配置ApiKey认证以写入Elasticsearch
在配置Elastic.Serilog.Sinks将日志写入Elasticsearch集群时,会遇到ApiKey认证的配置难题——Elasticsearch官方文档对此相关说明较少。
解决方法是在Elasticsearch Sink的Transport全局请求头中添加Authorization头,值格式为ApiKey <你的ApiKey>。具体实现代码如下:
const string url = "https://elk-xxxx-uat.es.westus2.azure.elastic-cloud.com"; Serilog.Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithElasticApmCorrelationInfo() .WriteTo.Elasticsearch(new[] { new Uri(url) }, opts => { opts.MinimumLevel = Serilog.Events.LogEventLevel.Debug; opts.ConfigureChannel = channel => { channel.ExportResponseCallback = (response, buffer) => Console.WriteLine($"Written {buffer.Count} logs to Elasticsearch: {response.ApiCallDetails.HttpStatusCode} {getStringFromResponseBites(response)}"); }; }, trans => { var headers = new System.Collections.Specialized.NameValueCollection(); headers.Add("Authorization", "ApiKey <insert your apikey here>"); trans.GlobalHeaders(headers); } ) .CreateLogger();
注意:将代码中的
<insert your apikey here>替换为你在Elasticsearch中生成的有效ApiKey。
内容的提问来源于stack exchange,提问作者Ivan Maia
相关产品推荐
相关产品推荐

