Skip to content
This repository was archived by the owner on Jun 1, 2024. It is now read-only.

Commit f6286c0

Browse files
author
Nenad Vicentic
committed
Automatically handle TypeName for Elasticsearch version <7, 7 and 8+, when DetectElasticsearchVersion option is set to true
1 parent 71f5031 commit f6286c0

File tree

5 files changed

+22
-12
lines changed

5 files changed

+22
-12
lines changed

src/Serilog.Sinks.Elasticsearch/LoggerConfigurationElasticSearchExtensions.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ public static LoggerConfiguration Elasticsearch(
143143
/// <param name="failureSink">Sink to use when Elasticsearch is unable to accept the events. This is optionally and depends on the EmitEventFailure setting.</param>
144144
/// <param name="singleEventSizePostingLimit"><see cref="ElasticsearchSinkOptions.SingleEventSizePostingLimit"/>The maximum length of an event allowed to be posted to Elasticsearch.default null</param>
145145
/// <param name="templateCustomSettings">Add custom elasticsearch settings to the template</param>
146+
/// <param name="detectElasticsearchVersion">Turns on detection of elasticsearch version via background HTTP call. This will also set `TypeName` automatically, according to the version of Elasticsearch.</param>
146147
/// <param name="batchAction">Configures the OpType being used when inserting document in batch. Must be set to create for data streams.</param>
147148
/// <returns>LoggerConfiguration object</returns>
148149
/// <exception cref="ArgumentNullException"><paramref name="nodeUris"/> is <see langword="null" />.</exception>
@@ -151,7 +152,7 @@ public static LoggerConfiguration Elasticsearch(
151152
string nodeUris,
152153
string indexFormat = null,
153154
string templateName = null,
154-
string typeName = "logevent",
155+
string typeName = null,
155156
int batchPostingLimit = 50,
156157
int period = 2,
157158
bool inlineFields = false,
@@ -182,7 +183,8 @@ public static LoggerConfiguration Elasticsearch(
182183
long? singleEventSizePostingLimit = null,
183184
int? bufferFileCountLimit = null,
184185
Dictionary<string,string> templateCustomSettings = null,
185-
ElasticOpType batchAction = ElasticOpType.Index)
186+
ElasticOpType batchAction = ElasticOpType.Index,
187+
bool detectElasticsearchVersion = false)
186188
{
187189
if (string.IsNullOrEmpty(nodeUris))
188190
throw new ArgumentNullException(nameof(nodeUris), "No Elasticsearch node(s) specified.");
@@ -204,8 +206,6 @@ public static LoggerConfiguration Elasticsearch(
204206
options.TemplateName = templateName;
205207
}
206208

207-
options.TypeName = !string.IsNullOrWhiteSpace(typeName) ? typeName : null;
208-
209209
options.BatchPostingLimit = batchPostingLimit;
210210
options.BatchAction = batchAction;
211211
options.SingleEventSizePostingLimit = singleEventSizePostingLimit;
@@ -272,6 +272,8 @@ public static LoggerConfiguration Elasticsearch(
272272

273273
options.TemplateCustomSettings = templateCustomSettings;
274274

275+
options.DetectElasticsearchVersion = detectElasticsearchVersion;
276+
275277
return Elasticsearch(loggerSinkConfiguration, options);
276278
}
277279
}

src/Serilog.Sinks.Elasticsearch/Sinks/ElasticSearch/ElasticsearchSinkOptions.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public class ElasticsearchSinkOptions
110110
public string DeadLetterIndexName { get; set; }
111111

112112
///<summary>
113-
/// The default elasticsearch type name to use for the log events. Defaults to: "_doc".
113+
/// The default elasticsearch type name to use for the log events. Defaults to: null.
114114
/// </summary>
115115
public string TypeName { get; set; }
116116

@@ -288,7 +288,6 @@ public ElasticsearchSinkOptions()
288288
{
289289
this.IndexFormat = "logstash-{0:yyyy.MM.dd}";
290290
this.DeadLetterIndexName = "deadletter-{0:yyyy.MM.dd}";
291-
this.TypeName = DefaultTypeName;
292291
this.Period = TimeSpan.FromSeconds(2);
293292
this.BatchPostingLimit = 50;
294293
this.SingleEventSizePostingLimit = null;
@@ -308,7 +307,7 @@ public ElasticsearchSinkOptions()
308307
/// The default Elasticsearch type name used for Elasticsearch versions prior to 7.
309308
/// <para>As of <c>Elasticsearch 7</c> and up <c>_type</c> has been removed.</para>
310309
/// </summary>
311-
public static string DefaultTypeName { get; } = "_doc";
310+
public static string DefaultTypeName { get; } = "logevent";
312311

313312
/// <summary>
314313
/// Instructs the sink to auto detect the running Elasticsearch version.

src/Serilog.Sinks.Elasticsearch/Sinks/ElasticSearch/ElasticsearchSinkState.cs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -241,10 +241,10 @@ private object GetTemplateData()
241241
public void DiscoverClusterVersion()
242242
{
243243
if (!_options.DetectElasticsearchVersion) return;
244+
if (_options.TypeName != null) return; // Do not do anything if user explicitly configured `TypeName`
244245

245246
try
246247
{
247-
248248
var response = _client.Cat.Nodes<StringResponse>(new CatNodesRequestParameters()
249249
{
250250
Headers = new[] { "v" }
@@ -254,8 +254,17 @@ public void DiscoverClusterVersion()
254254
_discoveredVersion = response.Body.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
255255
.FirstOrDefault();
256256

257-
if (_discoveredVersion?.StartsWith("7.") ?? false)
258-
_options.TypeName = "_doc";
257+
if (_discoveredVersion == null)
258+
return;
259+
260+
if (int.TryParse(_discoveredVersion.Substring(0, _discoveredVersion.IndexOf('.')), out int majorVersion))
261+
{
262+
if (majorVersion < 7)
263+
_options.TypeName = ElasticsearchSinkOptions.DefaultTypeName; // "logevent"
264+
if (majorVersion == 7)
265+
_options.TypeName = "_doc";
266+
// Version 8 or higher leave `_options.TypeName` to be `null` (condition is already at the start of the method), so that `_type` is not sent to Elasticsearch at all.
267+
}
259268
}
260269
catch (Exception ex)
261270
{

test/Serilog.Sinks.Elasticsearch.Tests/BulkActionTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public void DefaultBulkActionV7()
3030
public void BulkActionV7OverrideTypeName()
3131
{
3232
_options.IndexFormat = "logs";
33-
_options.TypeName = "logevent"; // This is the default value when creating the sink via configuration
33+
_options.TypeName = null; // This is the default value, starting v9.0.0
3434
_options.AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7;
3535
_options.PipelineName = null;
3636
using (var sink = new ElasticsearchSink(_options))

test/Serilog.Sinks.Elasticsearch.Tests/ElasticsearchSinkTestsBase.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ protected IList<SerilogElasticsearchEvent> GetPostedLogEvents(int expectedCount)
7575
}
7676
action.IndexAction.Should().NotBeNull();
7777
action.IndexAction.Index.Should().NotBeNullOrEmpty().And.StartWith("logstash-");
78-
action.IndexAction.Type.Should().NotBeNullOrEmpty().And.Be("_doc");
78+
action.IndexAction.Type.Should().BeNull();
7979

8080
SerilogElasticsearchEvent actionMetaData;
8181
try

0 commit comments

Comments
 (0)