I was struggling to find a way to pass an apikey to ElasticSearch APM (Elastic.Serilog.Sinks) in order to authenticate and sink logs tho my Elasticsearch stack.
The Elasticsearch Docs do not provide much information on how to do that.
But, I found a hint on the last response in this serilog-sinks-elasticsearch issue, wich also points to the this Elasticsearch Docs.
Solution
So, here’s how I’ve achieved my objective.
The trick is to add the Authorization header whith the value “apikey ” in Globalheaders on the Transport of ElasticSearch sink.
Example:
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();