diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpan.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpan.cs index e9a6ce6e34..159baf28cf 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpan.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpan.cs @@ -23,11 +23,11 @@ internal enum SpanKind internal class InstanaSpan { - private InstanaSpanTransformInfo transformInfo = new InstanaSpanTransformInfo(); + private InstanaSpanTransformInfo transformInfo = new(); private string n = string.Empty; private string t = string.Empty; private string lt = string.Empty; - private From f = new From(); + private From f = new(); private string p = string.Empty; private string s = string.Empty; private SpanKind k = SpanKind.NOT_SET; @@ -35,7 +35,7 @@ internal class InstanaSpan private long d; private bool tp; private int ec; - private Data data = new Data() + private Data data = new() { data = new Dictionary(8), Events = new List(8), @@ -197,9 +197,9 @@ internal bool IsEmpty() internal class Data #pragma warning restore SA1402 // File may only contain a single type { - private List events = new List(8); - private Dictionary dataField = new Dictionary(8); - private Dictionary tags = new Dictionary(2); + private List events = new(8); + private Dictionary dataField = new(8); + private Dictionary tags = new(2); #pragma warning disable SA1300 // Element should begin with upper-case letter @@ -241,7 +241,7 @@ internal class SpanEvent #pragma warning restore SA1402 // File may only contain a single type { private string name = string.Empty; - private Dictionary tags = new Dictionary(); + private Dictionary tags = []; public string Name { diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanFactory.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanFactory.cs index 0d106cd0d5..fe3dbf4843 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanFactory.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanFactory.cs @@ -7,12 +7,12 @@ internal class InstanaSpanFactory { internal static InstanaSpan CreateSpan() { - InstanaSpan instanaSpan = new InstanaSpan + var instanaSpan = new InstanaSpan { Data = new Data() { - data = new Dictionary(), - Tags = new Dictionary(), + data = [], + Tags = [], Events = new List(8), }, diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanSerializer.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanSerializer.cs index 55d8626dad..3046fa58ba 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanSerializer.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/InstanaSpanSerializer.cs @@ -68,7 +68,7 @@ internal static async Task SerializeToStreamWriterAsync(InstanaSpan instanaSpan, await writer.WriteAsync(COMMA).ConfigureAwait(false); await AppendPropertyAsync(DateToUnixMillis(instanaSpan.Ts), "ts", writer).ConfigureAwait(false); await writer.WriteAsync(COMMA).ConfigureAwait(false); - await AppendPropertyAsync((long)(instanaSpan.D / 10_000), "d", writer).ConfigureAwait(false); + await AppendPropertyAsync(instanaSpan.D / 10_000L, "d", writer).ConfigureAwait(false); await writer.WriteAsync(COMMA).ConfigureAwait(false); await AppendObjectAsync(SerializeDataAsync, "data", instanaSpan, writer).ConfigureAwait(false); await writer.WriteAsync(COMMA).ConfigureAwait(false); @@ -227,55 +227,53 @@ private static async Task SerializeEventsAsync(InstanaSpan instanaSpan, StreamWr return; } - using (var enumerator = instanaSpan.Data.Events.GetEnumerator()) + using var enumerator = instanaSpan.Data.Events.GetEnumerator(); + byte i = 0; + try { - byte i = 0; - try + await writer.WriteAsync("[").ConfigureAwait(false); + while (enumerator.MoveNext()) { - await writer.WriteAsync("[").ConfigureAwait(false); - while (enumerator.MoveNext()) + if (i > 0) { - if (i > 0) - { - await writer.WriteAsync(COMMA).ConfigureAwait(false); - } - else - { - i = 1; - } + await writer.WriteAsync(COMMA).ConfigureAwait(false); + } + else + { + i = 1; + } - await writer.WriteAsync(OPEN_BRACE).ConfigureAwait(false); + await writer.WriteAsync(OPEN_BRACE).ConfigureAwait(false); + await writer.WriteAsync(QUOTE).ConfigureAwait(false); + await writer.WriteAsync(InstanaExporterConstants.EVENT_NAME_FIELD).ConfigureAwait(false); + await writer.WriteAsync(QUOTE_COLON_QUOTE).ConfigureAwait(false); + await writer.WriteAsync(enumerator.Current.Name).ConfigureAwait(false); + await writer.WriteAsync(QUOTE_COMMA_QUOTE).ConfigureAwait(false); + await writer.WriteAsync(InstanaExporterConstants.EVENT_TIMESTAMP_FIELD).ConfigureAwait(false); + await writer.WriteAsync(QUOTE_COLON_QUOTE).ConfigureAwait(false); + await writer.WriteAsync(DateToUnixMillis(enumerator.Current.Ts).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await writer.WriteAsync(QUOTE).ConfigureAwait(false); + + if (enumerator.Current.Tags.Count > 0) + { + await writer.WriteAsync(COMMA).ConfigureAwait(false); await writer.WriteAsync(QUOTE).ConfigureAwait(false); - await writer.WriteAsync(InstanaExporterConstants.EVENT_NAME_FIELD).ConfigureAwait(false); - await writer.WriteAsync(QUOTE_COLON_QUOTE).ConfigureAwait(false); - await writer.WriteAsync(enumerator.Current.Name).ConfigureAwait(false); - await writer.WriteAsync(QUOTE_COMMA_QUOTE).ConfigureAwait(false); - await writer.WriteAsync(InstanaExporterConstants.EVENT_TIMESTAMP_FIELD).ConfigureAwait(false); - await writer.WriteAsync(QUOTE_COLON_QUOTE).ConfigureAwait(false); - await writer.WriteAsync(DateToUnixMillis(enumerator.Current.Ts).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await writer.WriteAsync(InstanaExporterConstants.TAGS_FIELD).ConfigureAwait(false); await writer.WriteAsync(QUOTE).ConfigureAwait(false); - - if (enumerator.Current.Tags.Count > 0) - { - await writer.WriteAsync(COMMA).ConfigureAwait(false); - await writer.WriteAsync(QUOTE).ConfigureAwait(false); - await writer.WriteAsync(InstanaExporterConstants.TAGS_FIELD).ConfigureAwait(false); - await writer.WriteAsync(QUOTE).ConfigureAwait(false); - await writer.WriteAsync(COLON).ConfigureAwait(false); - await SerializeTagsLogicAsync(enumerator.Current.Tags, writer).ConfigureAwait(false); - } - - await writer.WriteAsync(CLOSE_BRACE).ConfigureAwait(false); + await writer.WriteAsync(COLON).ConfigureAwait(false); + await SerializeTagsLogicAsync(enumerator.Current.Tags, writer).ConfigureAwait(false); } - await writer.WriteAsync("]").ConfigureAwait(false); - } - catch (InvalidOperationException) - { - // if the collection gets modified while serializing, we might get a collision. - // There is no good way of preventing this and continuing normally except locking - // which needs investigation + await writer.WriteAsync(CLOSE_BRACE).ConfigureAwait(false); } + + await writer.WriteAsync("]").ConfigureAwait(false); + } + catch (InvalidOperationException) + { + // if the collection gets modified while serializing, we might get a collision. + // There is no good way of preventing this and continuing normally except locking + // which needs investigation } } } diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/ActivityProcessorBase.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/ActivityProcessorBase.cs index e4dbea1f3a..ff86416aae 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/ActivityProcessorBase.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/ActivityProcessorBase.cs @@ -19,19 +19,13 @@ public virtual async Task ProcessAsync(Activity activity, InstanaSpan instanaSpa protected virtual void PreProcess(Activity activity, InstanaSpan instanaSpan) { - if (instanaSpan.TransformInfo == null) - { - instanaSpan.TransformInfo = new InstanaSpanTransformInfo(); - } + instanaSpan.TransformInfo ??= new InstanaSpanTransformInfo(); - if (instanaSpan.Data == null) + instanaSpan.Data ??= new Data() { - instanaSpan.Data = new Data() - { - data = new Dictionary(), - Events = new List(8), - Tags = new Dictionary(), - }; - } + data = [], + Events = new List(8), + Tags = [], + }; } } diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/DefaultActivityProcessor.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/DefaultActivityProcessor.cs index fd430b9b6a..3c6447bcec 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/DefaultActivityProcessor.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/DefaultActivityProcessor.cs @@ -13,7 +13,7 @@ public override async Task ProcessAsync(Activity activity, InstanaSpan instanaSp instanaSpan.N = InstanaExporterConstants.OTEL_SPAN_TYPE; - string traceId = activity.TraceId.ToHexString(); + var traceId = activity.TraceId.ToHexString(); if (traceId.Length == 32) { instanaSpan.T = traceId.Substring(16); @@ -24,8 +24,8 @@ public override async Task ProcessAsync(Activity activity, InstanaSpan instanaSp instanaSpan.T = traceId; } - bool hasParent = false; - string parentSpanId = activity.ParentSpanId.ToHexString(); + var hasParent = false; + var parentSpanId = activity.ParentSpanId.ToHexString(); if (!string.IsNullOrEmpty(parentSpanId) && GetLongFromHex(parentSpanId) != 0) { hasParent = true; @@ -52,19 +52,13 @@ public override async Task ProcessAsync(Activity activity, InstanaSpan instanaSp private static SpanKind GetSpanKind(ActivityKind activityKind) { - switch (activityKind) + return activityKind switch { - case ActivityKind.Consumer: - case ActivityKind.Server: - return SpanKind.ENTRY; - case ActivityKind.Client: - case ActivityKind.Producer: - return SpanKind.EXIT; - case ActivityKind.Internal: - return SpanKind.INTERMEDIATE; - default: - return SpanKind.NOT_SET; - } + ActivityKind.Consumer or ActivityKind.Server => SpanKind.ENTRY, + ActivityKind.Client or ActivityKind.Producer => SpanKind.EXIT, + ActivityKind.Internal => SpanKind.INTERMEDIATE, + _ => SpanKind.NOT_SET, + }; } private static long GetLongFromHex(string hexValue) @@ -73,7 +67,7 @@ private static long GetLongFromHex(string hexValue) { try { - string[] ids = hexValue.Split(','); + var ids = hexValue.Split(','); return Convert.ToInt64(ids[ids.Length - 1].Trim(), 16); } catch (Exception) @@ -86,7 +80,7 @@ private static long GetLongFromHex(string hexValue) private static void SetKind(Activity activity, InstanaSpan instanaSpan) { - bool isEntrySpan = false; + var isEntrySpan = false; if (instanaSpan.Data.data != null) { diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/EventsActivityProcessor.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/EventsActivityProcessor.cs index 1c1fb00c61..df3e8decf8 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/EventsActivityProcessor.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/EventsActivityProcessor.cs @@ -22,7 +22,7 @@ public override async Task ProcessAsync(Activity activity, InstanaSpan instanaSp { Name = activityEvent.Name, Ts = activityEvent.Timestamp.Ticks, - Tags = new Dictionary(), + Tags = [], }; foreach (var eventTag in activityEvent.Tags) diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/TagsActivityProcessor.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/TagsActivityProcessor.cs index 0f6763c1a9..1d6341e7a9 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/TagsActivityProcessor.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/Processors/TagsActivityProcessor.cs @@ -21,20 +21,20 @@ public override async Task ProcessAsync(Activity activity, InstanaSpan instanaSp this.PreProcess(activity, instanaSpan); - string statusCode = string.Empty; - string statusDesc = string.Empty; - Dictionary tags = new Dictionary(); + var statusCode = string.Empty; + var statusDesc = string.Empty; + var tags = new Dictionary(); foreach (var tag in activity.Tags) { if (tag.Key == "otel.status_code") { - statusCode = (tag.Value as string) ?? string.Empty; + statusCode = tag.Value ?? string.Empty; continue; } if (tag.Key == "otel.status_description") { - statusDesc = (tag.Value as string) ?? string.Empty; + statusDesc = tag.Value ?? string.Empty; continue; } diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/SpanSender.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/SpanSender.cs index 0381b25a5a..9e20b6e805 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/SpanSender.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/SpanSender.cs @@ -10,7 +10,7 @@ internal sealed class SpanSender : ISpanSender #pragma warning restore CA1001 // Types that own disposable fields should be disposable { private readonly Task queueSenderTask; - private readonly ConcurrentQueue spansQueue = new ConcurrentQueue(); + private readonly ConcurrentQueue spansQueue = new(); public SpanSender() { @@ -33,7 +33,7 @@ private async void TaskSpanSender() while (true) { // check if we can send spans - if (this.spansQueue.TryPeek(out InstanaSpan _)) + if (this.spansQueue.TryPeek(out var _)) { // actually send spans await Transport.SendSpansAsync(this.spansQueue).ConfigureAwait(false); diff --git a/src/OpenTelemetry.Exporter.Instana/Implementation/Transport.cs b/src/OpenTelemetry.Exporter.Instana/Implementation/Transport.cs index f39c6b2da7..97cee57f7b 100644 --- a/src/OpenTelemetry.Exporter.Instana/Implementation/Transport.cs +++ b/src/OpenTelemetry.Exporter.Instana/Implementation/Transport.cs @@ -15,7 +15,7 @@ internal static class Transport { private const int MultiSpanBufferSize = 4096000; private const int MultiSpanBufferLimit = 4070000; - private static readonly MediaTypeHeaderValue MEDIAHEADER = new MediaTypeHeaderValue("application/json"); + private static readonly MediaTypeHeaderValue MEDIAHEADER = new("application/json"); private static readonly byte[] TracesBuffer = new byte[MultiSpanBufferSize]; private static bool isConfigured; private static int backendTimeout; @@ -28,10 +28,7 @@ static Transport() Configure(); } - internal static bool IsAvailable - { - get { return isConfigured && Client != null; } - } + internal static bool IsAvailable => isConfigured && Client != null; internal static InstanaHttpClient? Client { get; set; } @@ -39,56 +36,50 @@ internal static async Task SendSpansAsync(ConcurrentQueue spanQueue { try { - using (MemoryStream sendBuffer = new MemoryStream(TracesBuffer)) + using var sendBuffer = new MemoryStream(TracesBuffer); + using var writer = new StreamWriter(sendBuffer); + await writer.WriteAsync("{\"spans\":[").ConfigureAwait(false); + var first = true; + + // peek instead of dequeue, because we don't yet know whether the next span + // fits within our MULTI_SPAN_BUFFER_LIMIT + while (spanQueue.TryPeek(out var span) && sendBuffer.Position < MultiSpanBufferLimit) { - using (StreamWriter writer = new StreamWriter(sendBuffer)) + if (!first) { - await writer.WriteAsync("{\"spans\":[").ConfigureAwait(false); - bool first = true; - - // peek instead of dequeue, because we don't yet know whether the next span - // fits within our MULTI_SPAN_BUFFER_LIMIT - while (spanQueue.TryPeek(out InstanaSpan span) && sendBuffer.Position < MultiSpanBufferLimit) - { - if (!first) - { - await writer.WriteAsync(",").ConfigureAwait(false); - } - - await InstanaSpanSerializer.SerializeToStreamWriterAsync(span, writer).ConfigureAwait(false); - await writer.FlushAsync().ConfigureAwait(false); - - first = false; - - // Now we can dequeue. Note, this means we'll be giving up/losing - // this span if we fail to send for any reason. - spanQueue.TryDequeue(out _); - } - - await writer.WriteAsync("]}").ConfigureAwait(false); - await writer.FlushAsync().ConfigureAwait(false); - - long length = sendBuffer.Position; - sendBuffer.Position = 0; - sendBuffer.SetLength(length); - - HttpContent content = new StreamContent(sendBuffer, (int)length); - content.Headers.ContentType = MEDIAHEADER; - content.Headers.Add("X-INSTANA-TIME", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture)); - - using (var httpMsg = new HttpRequestMessage() - { - Method = HttpMethod.Post, - RequestUri = new Uri(bundleUrl), - }) - { - httpMsg.Content = content; - if (Client != null) - { - await Client.SendAsync(httpMsg).ConfigureAwait(false); - } - } + await writer.WriteAsync(",").ConfigureAwait(false); } + + await InstanaSpanSerializer.SerializeToStreamWriterAsync(span, writer).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + + first = false; + + // Now we can dequeue. Note, this means we'll be giving up/losing + // this span if we fail to send for any reason. + spanQueue.TryDequeue(out _); + } + + await writer.WriteAsync("]}").ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + + var length = sendBuffer.Position; + sendBuffer.Position = 0; + sendBuffer.SetLength(length); + + HttpContent content = new StreamContent(sendBuffer, (int)length); + content.Headers.ContentType = MEDIAHEADER; + content.Headers.Add("X-INSTANA-TIME", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture)); + + using var httpMsg = new HttpRequestMessage() + { + Method = HttpMethod.Post, + RequestUri = new Uri(bundleUrl), + }; + httpMsg.Content = content; + if (Client != null) + { + await Client.SendAsync(httpMsg).ConfigureAwait(false); } } catch (Exception e) @@ -148,8 +139,8 @@ private static void ConfigureBackendClient() #pragma warning disable CA2000 var configuredHandler = new HttpClientHandler(); #pragma warning restore CA2000 - string proxy = Environment.GetEnvironmentVariable(InstanaExporterConstants.ENVVAR_INSTANA_ENDPOINT_PROXY); - if (Uri.TryCreate(proxy, UriKind.Absolute, out Uri proxyAddress)) + var proxy = Environment.GetEnvironmentVariable(InstanaExporterConstants.ENVVAR_INSTANA_ENDPOINT_PROXY); + if (Uri.TryCreate(proxy, UriKind.Absolute, out var proxyAddress)) { configuredHandler.Proxy = new WebProxy(proxyAddress, true); configuredHandler.UseProxy = true; diff --git a/src/OpenTelemetry.Exporter.Instana/InstanaExporter.cs b/src/OpenTelemetry.Exporter.Instana/InstanaExporter.cs index aa77513e7a..1c2fc4ad23 100644 --- a/src/OpenTelemetry.Exporter.Instana/InstanaExporter.cs +++ b/src/OpenTelemetry.Exporter.Instana/InstanaExporter.cs @@ -12,42 +12,22 @@ namespace OpenTelemetry.Exporter.Instana; internal sealed class InstanaExporter : BaseExporter { private readonly IActivityProcessor activityProcessor; - private ISpanSender spanSender = new SpanSender(); - private IInstanaExporterHelper instanaExporterHelper = new InstanaExporterHelper(); private bool shutdownCalled; public InstanaExporter(IActivityProcessor? activityProcessor = null) { - if (activityProcessor != null) + this.activityProcessor = activityProcessor ?? new DefaultActivityProcessor { - this.activityProcessor = activityProcessor; - } - else - { - this.activityProcessor = new DefaultActivityProcessor + NextProcessor = new TagsActivityProcessor { - NextProcessor = new TagsActivityProcessor - { - NextProcessor = new EventsActivityProcessor - { - NextProcessor = new ErrorActivityProcessor(), - }, - }, - }; - } + NextProcessor = new EventsActivityProcessor { NextProcessor = new ErrorActivityProcessor() }, + }, + }; } - internal ISpanSender SpanSender - { - get { return this.spanSender; } - set { this.spanSender = value; } - } + internal ISpanSender SpanSender { get; set; } = new SpanSender(); - internal IInstanaExporterHelper InstanaExporterHelper - { - get { return this.instanaExporterHelper; } - set { this.instanaExporterHelper = value; } - } + internal IInstanaExporterHelper InstanaExporterHelper { get; set; } = new InstanaExporterHelper(); public override ExportResult Export(in Batch batch) { @@ -56,13 +36,13 @@ public override ExportResult Export(in Batch batch) return ExportResult.Failure; } - From from = new From(); - if (this.instanaExporterHelper.IsWindows()) + var from = new From(); + if (this.InstanaExporterHelper.IsWindows()) { from = new From { E = Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture) }; } - string serviceName = this.ExtractServiceName(ref from); + var serviceName = this.ExtractServiceName(ref from); foreach (var activity in batch) { @@ -71,8 +51,8 @@ public override ExportResult Export(in Batch batch) continue; } - InstanaSpan span = this.ParseActivityAsync(activity, serviceName, from).Result; - this.spanSender.Enqueue(span); + var span = this.ParseActivityAsync(activity, serviceName, from).Result; + this.SpanSender.Enqueue(span); } return ExportResult.Success; @@ -98,11 +78,11 @@ protected override bool OnForceFlush(int timeoutMilliseconds) private string ExtractServiceName(ref From from) { - string serviceName = string.Empty; - string serviceId = string.Empty; - string processId = string.Empty; - string hostId = string.Empty; - var resource = this.instanaExporterHelper.GetParentProviderResource(this); + var serviceName = string.Empty; + var serviceId = string.Empty; + var processId = string.Empty; + var hostId = string.Empty; + var resource = this.InstanaExporterHelper.GetParentProviderResource(this); if (resource != Resource.Empty && resource.Attributes.Any()) { foreach (var resourceAttribute in resource.Attributes) @@ -154,7 +134,7 @@ private string ExtractServiceName(ref From from) private async Task ParseActivityAsync(Activity activity, string? serviceName = null, From? from = null) { - InstanaSpan instanaSpan = InstanaSpanFactory.CreateSpan(); + var instanaSpan = InstanaSpanFactory.CreateSpan(); await this.activityProcessor.ProcessAsync(activity, instanaSpan).ConfigureAwait(false); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaExporterTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaExporterTests.cs index e83dc8c27b..d076911310 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaExporterTests.cs @@ -32,12 +32,12 @@ public void Export() SpanSender = this.spanSender, }; - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.SetStatus(ActivityStatusCode.Error, "TestErrorDesc"); activity.TraceStateString = "TraceStateString"; - Activity[] activities = new Activity[1] { activity }; - Batch batch = new Batch(activities, activities.Length); + Activity[] activities = [activity]; + var batch = new Batch(activities, activities.Length); var result = this.instanaExporter.Export(in batch); Assert.Equal(ExportResult.Success, result); @@ -65,11 +65,11 @@ public void Export_ProcessPidDoesNotExistButServiceIdExists() SpanSender = this.spanSender, }; - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.SetStatus(ActivityStatusCode.Error, "TestErrorDesc"); - Activity[] activities = new Activity[1] { activity }; - Batch batch = new Batch(activities, activities.Length); + Activity[] activities = [activity]; + var batch = new Batch(activities, activities.Length); var result = this.instanaExporter.Export(in batch); Assert.Equal(ExportResult.Success, result); @@ -89,13 +89,13 @@ public void Export_ExporterIsShotDown() SpanSender = this.spanSender, }; - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.SetStatus(ActivityStatusCode.Error, "TestErrorDesc"); this.instanaExporter.Shutdown(); - Activity[] activities = new Activity[1] { activity }; - Batch batch = new Batch(activities, activities.Length); + Activity[] activities = [activity]; + var batch = new Batch(activities, activities.Length); var result = this.instanaExporter.Export(in batch); Assert.Equal(ExportResult.Failure, result); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanFactoryTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanFactoryTests.cs index 3e1e14f773..f53310e25c 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanFactoryTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanFactoryTests.cs @@ -12,7 +12,7 @@ public static class InstanaSpanFactoryTests public static void CreateSpan() { _ = new InstanaSpanFactory(); - InstanaSpan instanaSpan = InstanaSpanFactory.CreateSpan(); + var instanaSpan = InstanaSpanFactory.CreateSpan(); Assert.NotNull(instanaSpan); Assert.NotNull(instanaSpan.TransformInfo); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanSerializerTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanSerializerTests.cs index 389acfdf74..6063f4befc 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanSerializerTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanSerializerTests.cs @@ -13,7 +13,7 @@ public static class InstanaSpanSerializerTests [Fact] public static async Task SerializeToStreamWriterAsync() { - InstanaSpan instanaOtelSpan = InstanaSpanFactory.CreateSpan(); + var instanaOtelSpan = InstanaSpanFactory.CreateSpan(); instanaOtelSpan.F = new Implementation.From { E = "12345", H = "localhost" }; instanaOtelSpan.N = "otel"; instanaOtelSpan.T = "hexNumberT1234"; @@ -23,45 +23,43 @@ public static async Task SerializeToStreamWriterAsync() instanaOtelSpan.D = 123456; instanaOtelSpan.Lt = "hexNumberLT1234567890123"; instanaOtelSpan.Tp = true; - instanaOtelSpan.Data.Tags = new Dictionary(); - instanaOtelSpan.Data.Tags["tag1Key"] = "tag1Vale"; - instanaOtelSpan.Data.Tags["tag2Key"] = "tag2Vale"; - instanaOtelSpan.Data.data = new Dictionary(); - instanaOtelSpan.Data.data["data1Key"] = "data1Vale"; - instanaOtelSpan.Data.data["data2Key"] = "data2Vale"; - instanaOtelSpan.Data.Events = new List - { + instanaOtelSpan.Data.Tags = new Dictionary { ["tag1Key"] = "tag1Vale", ["tag2Key"] = "tag2Vale" }; + instanaOtelSpan.Data.data = new Dictionary { ["data1Key"] = "data1Vale", ["data2Key"] = "data2Vale" }; + instanaOtelSpan.Data.Events = + [ new() { - Name = "testEvent", Ts = 111111, + Name = "testEvent", + Ts = 111111, Tags = new Dictionary { { "eventTagKey", "eventTagValue" } }, }, + new() { - Name = "testEvent2", Ts = 222222, + Name = "testEvent2", + Ts = 222222, Tags = new Dictionary { { "eventTag2Key", "eventTag2Value" } }, - }, - }; + } + + ]; InstanaSpanTest? span; - using (MemoryStream sendBuffer = new MemoryStream(new byte[4096000])) + using (var sendBuffer = new MemoryStream(new byte[4096000])) { - using (StreamWriter writer = new StreamWriter(sendBuffer)) - { - await InstanaSpanSerializer.SerializeToStreamWriterAsync(instanaOtelSpan, writer); - await writer.FlushAsync(); - long length = sendBuffer.Position; - sendBuffer.Position = 0; - sendBuffer.SetLength(length); + using var writer = new StreamWriter(sendBuffer); + await InstanaSpanSerializer.SerializeToStreamWriterAsync(instanaOtelSpan, writer); + await writer.FlushAsync(); + var length = sendBuffer.Position; + sendBuffer.Position = 0; + sendBuffer.SetLength(length); - JsonSerializer serializer = new JsonSerializer(); - serializer.Converters.Add(new JavaScriptDateTimeConverter()); - serializer.NullValueHandling = NullValueHandling.Ignore; + var serializer = new JsonSerializer(); + serializer.Converters.Add(new JavaScriptDateTimeConverter()); + serializer.NullValueHandling = NullValueHandling.Ignore; - TextReader textReader = new StreamReader(sendBuffer); - JsonReader reader = new JsonTextReader(textReader); - span = serializer.Deserialize(reader); - } + TextReader textReader = new StreamReader(sendBuffer); + JsonReader reader = new JsonTextReader(textReader); + span = serializer.Deserialize(reader); } Assert.NotNull(span); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanTest.cs b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanTest.cs index 201b0f3918..32bfef6851 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanTest.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/InstanaSpanTest.cs @@ -145,23 +145,19 @@ public override bool CanConvert(Type objectType) } else { - JObject obj = JObject.Load(reader); + var obj = JObject.Load(reader); var data = obj.Root; if (data != null) { var newData = new Data(); foreach (var field in data) { - if (((JProperty)field).Name == "tags" || - ((JProperty)field).Name == "events") + if (((JProperty)field).Name is "tags" or "events") { continue; } - if (newData.data == null) - { - newData.data = new Dictionary(); - } + newData.data ??= []; newData.data[((JProperty)field).Name] = ((JProperty)field).Value.ToString(); } diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/DefaultActivityProcessorTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/DefaultActivityProcessorTests.cs index 85ae5c3577..bdf6907982 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/DefaultActivityProcessorTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/DefaultActivityProcessorTests.cs @@ -10,16 +10,16 @@ namespace OpenTelemetry.Exporter.Instana.Tests.Processors; public class DefaultActivityProcessorTests { - private DefaultActivityProcessor defaultActivityProcessor = new DefaultActivityProcessor(); + private readonly DefaultActivityProcessor defaultActivityProcessor = new(); [Fact] public async Task ProcessAsync() { - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.Start(); await Task.Delay(200); activity.Stop(); - InstanaSpan instanaSpan = new InstanaSpan(); + var instanaSpan = new InstanaSpan(); await this.defaultActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.False(string.IsNullOrEmpty(instanaSpan.S)); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/ErrorActivityProcessorTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/ErrorActivityProcessorTests.cs index 18c37f236a..216eae523c 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/ErrorActivityProcessorTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/ErrorActivityProcessorTests.cs @@ -10,14 +10,14 @@ namespace OpenTelemetry.Exporter.Instana.Tests.Processors; public class ErrorActivityProcessorTests { - private ErrorActivityProcessor errorActivityProcessor = new ErrorActivityProcessor(); + private readonly ErrorActivityProcessor errorActivityProcessor = new(); [Fact] public async Task Process_ErrorStatusCodeIsSet() { - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.SetStatus(ActivityStatusCode.Error, "TestErrorDesc"); - InstanaSpan instanaSpan = new InstanaSpan(); + var instanaSpan = new InstanaSpan(); await this.errorActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.True(instanaSpan.Ec == 1); @@ -30,8 +30,8 @@ public async Task Process_ErrorStatusCodeIsSet() [Fact] public async Task Process_ExistsExceptionEvent() { - Activity activity = new Activity("testOperationName"); - InstanaSpan instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() { HasExceptionEvent = true } }; + var activity = new Activity("testOperationName"); + var instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() { HasExceptionEvent = true } }; await this.errorActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.True(instanaSpan.Ec == 1); @@ -40,8 +40,8 @@ public async Task Process_ExistsExceptionEvent() [Fact] public async Task Process_NoError() { - Activity activity = new Activity("testOperationName"); - InstanaSpan instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() }; + var activity = new Activity("testOperationName"); + var instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() }; await this.errorActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.True(instanaSpan.Ec == 0); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs index ce3b79dc8e..35452ace15 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs @@ -12,29 +12,27 @@ namespace OpenTelemetry.Exporter.Instana.Tests.Processors; public class EventsActivityProcessorTests { - private EventsActivityProcessor eventsActivityProcessor = new EventsActivityProcessor(); + private readonly EventsActivityProcessor eventsActivityProcessor = new(); [Fact] public async Task ProcessAsync() { - var activityTagsCollection = new ActivityTagsCollection(); - activityTagsCollection.Add(new KeyValuePair("eventTagKey", "eventTagValue")); + var activityTagsCollection = new ActivityTagsCollection { new KeyValuePair("eventTagKey", "eventTagValue") }; var activityEvent = new ActivityEvent( "testActivityEvent", DateTimeOffset.MinValue, activityTagsCollection); - var activityTagsCollection2 = new ActivityTagsCollection(); - activityTagsCollection2.Add(new KeyValuePair("eventTagKey2", "eventTagValue2")); + var activityTagsCollection2 = new ActivityTagsCollection { new KeyValuePair("eventTagKey2", "eventTagValue2") }; var activityEvent2 = new ActivityEvent( "testActivityEvent2", DateTimeOffset.MaxValue, activityTagsCollection2); - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.AddEvent(activityEvent); activity.AddEvent(activityEvent2); - InstanaSpan instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() }; + var instanaSpan = new InstanaSpan() { TransformInfo = new Implementation.InstanaSpanTransformInfo() }; if (this.eventsActivityProcessor != null) { await this.eventsActivityProcessor.ProcessAsync(activity, instanaSpan); @@ -46,7 +44,7 @@ public async Task ProcessAsync() Assert.True(instanaSpan.Data.Events[0].Name == "testActivityEvent"); Assert.True(instanaSpan.Data.Events[0].Ts > 0); Assert.NotNull(instanaSpan.Data?.Events[0]?.Tags); - string? eventTagValue = string.Empty; + var eventTagValue = string.Empty; _ = instanaSpan.Data.Events[0].Tags?.TryGetValue("eventTagKey", out eventTagValue); Assert.True(eventTagValue == "eventTagValue"); Assert.True(instanaSpan.Data.Events[1].Name == "testActivityEvent2"); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/TagsActivityProcessorTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/TagsActivityProcessorTests.cs index b70bc79bf6..fb2a4d05a2 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/TagsActivityProcessorTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/TagsActivityProcessorTests.cs @@ -10,17 +10,17 @@ namespace OpenTelemetry.Exporter.Instana.Tests.Processors; public class TagsActivityProcessorTests { - private TagsActivityProcessor tagsActivityProcessor = new TagsActivityProcessor(); + private readonly TagsActivityProcessor tagsActivityProcessor = new(); [Fact] public async Task ProcessAsync_StatusTagsExist() { - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.AddTag("otel.status_code", "testStatusCode"); activity.AddTag("otel.status_description", "testStatusDescription"); activity.AddTag("otel.testTag", "testTag"); - InstanaSpan instanaSpan = new InstanaSpan(); + var instanaSpan = new InstanaSpan(); await this.tagsActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.NotNull(instanaSpan.Data); @@ -33,10 +33,10 @@ public async Task ProcessAsync_StatusTagsExist() [Fact] public async Task ProcessAsync_StatusTagsDoNotExist() { - Activity activity = new Activity("testOperationName"); + var activity = new Activity("testOperationName"); activity.AddTag("otel.testTag", "testTag"); - InstanaSpan instanaSpan = new InstanaSpan(); + var instanaSpan = new InstanaSpan(); await this.tagsActivityProcessor.ProcessAsync(activity, instanaSpan); Assert.NotNull(instanaSpan.Data); diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/TestInstanaExporterHelper.cs b/test/OpenTelemetry.Exporter.Instana.Tests/TestInstanaExporterHelper.cs index bf48310c1f..7a88315de0 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/TestInstanaExporterHelper.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/TestInstanaExporterHelper.cs @@ -8,7 +8,7 @@ namespace OpenTelemetry.Exporter.Instana.Tests; internal class TestInstanaExporterHelper : IInstanaExporterHelper { - public Dictionary Attributes { get; } = new(); + public Dictionary Attributes { get; } = []; public Resource GetParentProviderResource(BaseExporter otelExporter) {