You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:40:56