diff --git a/build/scripts/Targets.fs b/build/scripts/Targets.fs index 5cfc8f0..15ef531 100644 --- a/build/scripts/Targets.fs +++ b/build/scripts/Targets.fs @@ -36,9 +36,14 @@ let private generatePackages _ = exec { run "dotnet" "pack" } let private pristineCheck (arguments:ParseResults) = let skipCheck = arguments.TryGetResult Skip_Dirty_Check |> Option.isSome match skipCheck, Information.isCleanWorkingCopy "." with - | true, _ -> printfn "Checkout is dirty but -c was specified to ignore this" + | true, _ -> printfn "Skip checking for clean working copy since -c is specified" | _, true -> printfn "The checkout folder does not have pending changes, proceeding" | _ -> failwithf "The checkout folder has pending changes, aborting. Specify -c to ./build.sh to skip this check" + + match skipCheck, (exec { exit_code_of "dotnet" "format" "--verify-no-changes" }) with + | true, _ -> printfn "Skip formatting checks since -c is specified" + | _, 0 -> printfn "There are no dotnet formatting violations, continuing the build." + | _ -> failwithf "There are dotnet formatting violations. Call `dotnet format` to fix or specify -c to ./build.sh to skip this check" let private runTests suite _ = let logger = diff --git a/examples/Example.Elastic.OpenTelemetry.AspNetCore/Program.cs b/examples/Example.Elastic.OpenTelemetry.AspNetCore/Program.cs index f222564..5de5fca 100644 --- a/examples/Example.Elastic.OpenTelemetry.AspNetCore/Program.cs +++ b/examples/Example.Elastic.OpenTelemetry.AspNetCore/Program.cs @@ -11,7 +11,7 @@ builder.Services .AddHttpClient() .AddOpenTelemetry() - .WithTracing(t=>t.AddAspNetCoreInstrumentation()); + .WithTracing(t => t.AddAspNetCoreInstrumentation()); builder.Services .AddControllersWithViews(); diff --git a/examples/Example.Elastic.OpenTelemetry.Worker/Worker.cs b/examples/Example.Elastic.OpenTelemetry.Worker/Worker.cs index 9f65359..a587058 100644 --- a/examples/Example.Elastic.OpenTelemetry.Worker/Worker.cs +++ b/examples/Example.Elastic.OpenTelemetry.Worker/Worker.cs @@ -24,7 +24,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) using (var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal)) { activity?.SetTag("CustomTag", "TagValue"); - + if (Counter.Enabled) Counter.Add(1); @@ -42,4 +42,4 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) await Task.Delay(5000, stoppingToken); } -} \ No newline at end of file +} diff --git a/examples/Example.Elastic.OpenTelemetry/Usage.cs b/examples/Example.Elastic.OpenTelemetry/Usage.cs index c86d187..e8b7026 100644 --- a/examples/Example.Elastic.OpenTelemetry/Usage.cs +++ b/examples/Example.Elastic.OpenTelemetry/Usage.cs @@ -12,12 +12,12 @@ namespace Example.Elastic.OpenTelemetry; internal static class Usage { - private const string ActivitySourceName = "CustomActivitySource"; - private static readonly ActivitySource ActivitySource = new(ActivitySourceName, "1.0.0"); - private static readonly HttpClient HttpClient = new(); + private const string ActivitySourceName = "CustomActivitySource"; + private static readonly ActivitySource ActivitySource = new(ActivitySourceName, "1.0.0"); + private static readonly HttpClient HttpClient = new(); - public static async Task BasicBuilderUsageAsync() - { + public static async Task BasicBuilderUsageAsync() + { // NOTE: This sample assumes ENV VARs have been set to configure the Endpoint and Authorization header. // Build an agent by creating and using an agent builder, adding a single source (for traces and metrics) defined in this sample application. @@ -56,63 +56,63 @@ public static async Task BasicBuilderUsageAsync() await DoStuffAsync(); - static async Task DoStuffAsync() - { - using var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal); - activity?.SetTag("CustomTag", "TagValue"); - - await Task.Delay(100); - var response = await HttpClient.GetAsync("http://elastic.co"); - await Task.Delay(50); - - if (response.StatusCode == System.Net.HttpStatusCode.OK) - activity?.SetStatus(ActivityStatusCode.Ok); - else - activity?.SetStatus(ActivityStatusCode.Error); - } - } - - //public static async Task ComplexUsageAsync() - //{ - // using var agent = Agent.Build( - // traceConfiguration: trace => trace.AddConsoleExporter(), - // metricConfiguration: metric => metric.AddConsoleExporter() - // ); - // //agent && Agent.Current now pointing to the same instance; - // var activitySource = Agent.Current.ActivitySource; - - // for (var i = 0; i < 2; i++) - // { - // using var parent = activitySource.StartActivity("Parent"); - // await Task.Delay(TimeSpan.FromSeconds(0.25)); - // await StartChildSpansForCompressionAsync(); - // await Task.Delay(TimeSpan.FromSeconds(0.25)); - // await StartChildSpansAsync(); - // await Task.Delay(TimeSpan.FromSeconds(0.25)); - // using var _ = activitySource.StartActivity("ChildTwo"); - // await Task.Delay(TimeSpan.FromSeconds(0.25)); - // } - - // Console.WriteLine("DONE"); - - // async Task StartChildSpansForCompressionAsync() - // { - // for (var i = 0; i < 10; i++) - // { - // using var child = activitySource.StartActivity("ChildSpanCompression"); - // await Task.Delay(TimeSpan.FromSeconds(0.25)); - // } - // } - - // async Task StartChildSpansAsync() - // { - // using var child = activitySource.StartActivity("Child"); - // await Task.Delay(TimeSpan.FromMilliseconds(10)); - - // // These have effectively ActivitySource = "", there is no way to include this without enabling ALL - // // activities on TracerBuilderProvider.AddSource("*") - // using var a = new Activity("Child2").Start(); - // await Task.Delay(TimeSpan.FromMilliseconds(10)); - // } - //} + static async Task DoStuffAsync() + { + using var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal); + activity?.SetTag("CustomTag", "TagValue"); + + await Task.Delay(100); + var response = await HttpClient.GetAsync("http://elastic.co"); + await Task.Delay(50); + + if (response.StatusCode == System.Net.HttpStatusCode.OK) + activity?.SetStatus(ActivityStatusCode.Ok); + else + activity?.SetStatus(ActivityStatusCode.Error); + } + } + + //public static async Task ComplexUsageAsync() + //{ + // using var agent = Agent.Build( + // traceConfiguration: trace => trace.AddConsoleExporter(), + // metricConfiguration: metric => metric.AddConsoleExporter() + // ); + // //agent && Agent.Current now pointing to the same instance; + // var activitySource = Agent.Current.ActivitySource; + + // for (var i = 0; i < 2; i++) + // { + // using var parent = activitySource.StartActivity("Parent"); + // await Task.Delay(TimeSpan.FromSeconds(0.25)); + // await StartChildSpansForCompressionAsync(); + // await Task.Delay(TimeSpan.FromSeconds(0.25)); + // await StartChildSpansAsync(); + // await Task.Delay(TimeSpan.FromSeconds(0.25)); + // using var _ = activitySource.StartActivity("ChildTwo"); + // await Task.Delay(TimeSpan.FromSeconds(0.25)); + // } + + // Console.WriteLine("DONE"); + + // async Task StartChildSpansForCompressionAsync() + // { + // for (var i = 0; i < 10; i++) + // { + // using var child = activitySource.StartActivity("ChildSpanCompression"); + // await Task.Delay(TimeSpan.FromSeconds(0.25)); + // } + // } + + // async Task StartChildSpansAsync() + // { + // using var child = activitySource.StartActivity("Child"); + // await Task.Delay(TimeSpan.FromMilliseconds(10)); + + // // These have effectively ActivitySource = "", there is no way to include this without enabling ALL + // // activities on TracerBuilderProvider.AddSource("*") + // using var a = new Activity("Child2").Start(); + // await Task.Delay(TimeSpan.FromMilliseconds(10)); + // } + //} } diff --git a/src/Elastic.OpenTelemetry/AgentBuilder.Build.cs b/src/Elastic.OpenTelemetry/AgentBuilder.Build.cs index aef13c8..73f2810 100644 --- a/src/Elastic.OpenTelemetry/AgentBuilder.Build.cs +++ b/src/Elastic.OpenTelemetry/AgentBuilder.Build.cs @@ -18,7 +18,8 @@ public static class OpenTelemetryBuilderExtensions /// TODO public static IOpenTelemetryBuilder WithLogger(this IOpenTelemetryBuilder builder, ILogger logger) { - if (builder is not AgentBuilder agentBuilder) return builder; + if (builder is not AgentBuilder agentBuilder) + return builder; agentBuilder.Logger.SetAdditionalLogger(logger); return agentBuilder; diff --git a/src/Elastic.OpenTelemetry/AgentBuilder.cs b/src/Elastic.OpenTelemetry/AgentBuilder.cs index 4bfec04..b78143f 100644 --- a/src/Elastic.OpenTelemetry/AgentBuilder.cs +++ b/src/Elastic.OpenTelemetry/AgentBuilder.cs @@ -48,7 +48,7 @@ public record AgentBuilderOptions public bool SkipOtlpExporter { get; init; } /// - /// Optional name which is used when retrieving OTLP options. + /// Optional name which is used when retrieving OTLP options. /// public string? OtlpExporterName { get; init; } } @@ -68,7 +68,8 @@ public class AgentBuilder : IOpenTelemetryBuilder public AgentBuilder(params string[] activitySourceNames) : this(new AgentBuilderOptions { ActivitySources = activitySourceNames - }) { } + }) + { } /// TODO public AgentBuilder(AgentBuilderOptions options) diff --git a/src/Elastic.OpenTelemetry/DependencyInjection/ServiceCollectionExtensions.cs b/src/Elastic.OpenTelemetry/DependencyInjection/ServiceCollectionExtensions.cs index c79b684..4728232 100644 --- a/src/Elastic.OpenTelemetry/DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Elastic.OpenTelemetry/DependencyInjection/ServiceCollectionExtensions.cs @@ -40,8 +40,8 @@ public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollect /// public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection, AgentBuilderOptions options) { - if (serviceCollection.Any(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ElasticOtelDistroService))) - { + if (serviceCollection.Any(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ElasticOtelDistroService))) + { var sp = serviceCollection.BuildServiceProvider(); return sp.GetService()!; //already registered as singleton } diff --git a/src/Elastic.OpenTelemetry/Diagnostics/Logging/AgentCompositeLogger.cs b/src/Elastic.OpenTelemetry/Diagnostics/Logging/AgentCompositeLogger.cs index 79fe29b..1675acf 100644 --- a/src/Elastic.OpenTelemetry/Diagnostics/Logging/AgentCompositeLogger.cs +++ b/src/Elastic.OpenTelemetry/Diagnostics/Logging/AgentCompositeLogger.cs @@ -30,12 +30,14 @@ public ValueTask DisposeAsync() /// TODO public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { - if (_isDisposed) return; + if (_isDisposed) + return; if (FileLogger.IsEnabled(logLevel)) FileLogger.Log(logLevel, eventId, state, exception, formatter); - if (additionalLogger == null) return; + if (additionalLogger == null) + return; if (additionalLogger.IsEnabled(logLevel)) additionalLogger.Log(logLevel, eventId, state, exception, formatter); @@ -58,7 +60,7 @@ private class CompositeDisposable(params IDisposable?[] disposables) : IDisposab { public void Dispose() { - foreach(var disposable in disposables) + foreach (var disposable in disposables) disposable?.Dispose(); } } diff --git a/src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs b/src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs index ed14993..ed671ee 100644 --- a/src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs +++ b/src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs @@ -34,7 +34,8 @@ public FileLogger() _scopeProvider = new LoggerExternalScopeProvider(); var process = Process.GetCurrentProcess(); - if (!FileLoggingEnabled) return; + if (!FileLoggingEnabled) + return; var configuredPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ElasticOtelLogDirectoryEnvironmentVariable); @@ -56,8 +57,8 @@ public FileLogger() WritingTask = Task.Run(async () => { while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false) && !_disposing) - while (_channel.Reader.TryRead(out var logLine) && !_disposing) - await _streamWriter.WriteLineAsync(logLine).ConfigureAwait(false); + while (_channel.Reader.TryRead(out var logLine) && !_disposing) + await _streamWriter.WriteLineAsync(logLine).ConfigureAwait(false); _syncDisposeWaitHandle.Set(); }); @@ -114,14 +115,7 @@ public async ValueTask DisposeAsync() if (WritingTask != null) await WritingTask.ConfigureAwait(false); - if (_streamWriter != null) - { -#if NETSTANDARD2_0 || NETFRAMEWORK - _streamWriter.Dispose(); -#else - await _streamWriter.DisposeAsync().ConfigureAwait(false); -#endif - } + _streamWriter?.Dispose(); } } diff --git a/src/Elastic.OpenTelemetry/Diagnostics/Logging/ScopedCompositeLogger.cs b/src/Elastic.OpenTelemetry/Diagnostics/Logging/ScopedCompositeLogger.cs index 77eddd9..d5f618d 100644 --- a/src/Elastic.OpenTelemetry/Diagnostics/Logging/ScopedCompositeLogger.cs +++ b/src/Elastic.OpenTelemetry/Diagnostics/Logging/ScopedCompositeLogger.cs @@ -28,7 +28,8 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except if (fileLogger.IsEnabled(logLevel)) fileLogger.Log(logLevel, eventId, state, exception, formatter); - if (additionalLogger == null) return; + if (additionalLogger == null) + return; if (additionalLogger.IsEnabled(logLevel)) additionalLogger.Log(logLevel, eventId, state, exception, formatter); @@ -45,7 +46,7 @@ private class CompositeDisposable(params IDisposable?[] disposables) : IDisposab { public void Dispose() { - foreach(var disposable in disposables) + foreach (var disposable in disposables) disposable?.Dispose(); } } diff --git a/src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs b/src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs index 4dbecba..dce5f5c 100644 --- a/src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs +++ b/src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs @@ -26,7 +26,7 @@ class LoggingEventListener : EventListener, IAsyncDisposable private static partial Regex TraceParentRegex(); #else - private static Regex _traceParentRegex = new Regex(TraceParentRegularExpressionString); + private static readonly Regex _traceParentRegex = new Regex(TraceParentRegularExpressionString); private static Regex TraceParentRegex() => _traceParentRegex; #endif diff --git a/src/Elastic.OpenTelemetry/Exporters/BatchExporter.cs b/src/Elastic.OpenTelemetry/Exporters/BatchExporter.cs index d49d188..8013884 100644 --- a/src/Elastic.OpenTelemetry/Exporters/BatchExporter.cs +++ b/src/Elastic.OpenTelemetry/Exporters/BatchExporter.cs @@ -1,18 +1,17 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using OpenTelemetry; - using System.Diagnostics; +using OpenTelemetry; namespace Elastic.OpenTelemetry.Exporters; internal class BatchExporter : BaseExporter { - public override ExportResult Export(in Batch batch) - { - using var scope = SuppressInstrumentationScope.Begin(); - Console.WriteLine($"Exporting: {batch.Count:N0} items"); - return ExportResult.Success; - } + public override ExportResult Export(in Batch batch) + { + using var scope = SuppressInstrumentationScope.Begin(); + Console.WriteLine($"Exporting: {batch.Count:N0} items"); + return ExportResult.Success; + } } diff --git a/src/Elastic.OpenTelemetry/Extensions/ActivityExtensions.cs b/src/Elastic.OpenTelemetry/Extensions/ActivityExtensions.cs index dbfe9d5..1053ec9 100644 --- a/src/Elastic.OpenTelemetry/Extensions/ActivityExtensions.cs +++ b/src/Elastic.OpenTelemetry/Extensions/ActivityExtensions.cs @@ -9,84 +9,84 @@ namespace Elastic.OpenTelemetry.Extensions; internal static class ActivityExtensions { - public static bool TryCompress(this Activity buffered, Activity sibling) - { - Composite? composite = null; - - var property = buffered.GetCustomProperty("Composite"); - - if (property is Composite c) - composite = c; - - var isAlreadyComposite = composite is not null; - - var canBeCompressed = isAlreadyComposite - ? buffered.TryToCompressComposite(sibling, composite!) - : buffered.TryToCompressRegular(sibling, ref composite); - - if (!canBeCompressed) - return false; - - if (!isAlreadyComposite) - { - composite ??= new Composite(); - composite.Count = 1; - composite.DurationSum = buffered.Duration.Milliseconds; - } - - composite!.Count++; - composite.DurationSum += sibling.Duration.Milliseconds; - - buffered.SetCustomProperty("Composite", composite); - - var endTime = sibling.StartTimeUtc.Add(sibling.Duration); - buffered.SetEndTime(endTime); - - sibling.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; - - return true; - } - - private static bool TryToCompressRegular(this Activity buffered, Activity sibling, ref Composite? composite) - { - if (!buffered.IsSameKind(sibling)) - return false; - - if (buffered.OperationName == sibling.OperationName) - { - // TODO - Duration configuration check - - composite ??= new Composite(); - composite.CompressionStrategy = "exact_match"; - return true; - } - - // TODO - Duration configuration check - composite ??= new Composite(); - composite.CompressionStrategy = "same_kind"; - // TODO - Set name - return true; - } - - private static bool TryToCompressComposite(this Activity buffered, Activity sibling, Composite composite) - { - switch (composite.CompressionStrategy) - { - case "exact_match": - return buffered.IsSameKind(sibling) && buffered.OperationName == sibling.OperationName; // && sibling.Duration <= Configuration.SpanCompressionExactMatchMaxDuration; - - case "same_kind": - return buffered.IsSameKind(sibling); // && sibling.Duration <= Configuration.SpanCompressionSameKindMaxDuration; - } - - return false; - } - - // TODO - Further implementation if possible - private static bool IsSameKind(this Activity current, Activity other) => - current.Kind == other.Kind; - // We don't have a direct way to establish which attribute(s) to use to assess these - //&& Subtype == other.Subtype - //&& _context.IsValueCreated && other._context.IsValueCreated - //&& Context?.Service?.Target == other.Context?.Service?.Target; + public static bool TryCompress(this Activity buffered, Activity sibling) + { + Composite? composite = null; + + var property = buffered.GetCustomProperty("Composite"); + + if (property is Composite c) + composite = c; + + var isAlreadyComposite = composite is not null; + + var canBeCompressed = isAlreadyComposite + ? buffered.TryToCompressComposite(sibling, composite!) + : buffered.TryToCompressRegular(sibling, ref composite); + + if (!canBeCompressed) + return false; + + if (!isAlreadyComposite) + { + composite ??= new Composite(); + composite.Count = 1; + composite.DurationSum = buffered.Duration.Milliseconds; + } + + composite!.Count++; + composite.DurationSum += sibling.Duration.Milliseconds; + + buffered.SetCustomProperty("Composite", composite); + + var endTime = sibling.StartTimeUtc.Add(sibling.Duration); + buffered.SetEndTime(endTime); + + sibling.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; + + return true; + } + + private static bool TryToCompressRegular(this Activity buffered, Activity sibling, ref Composite? composite) + { + if (!buffered.IsSameKind(sibling)) + return false; + + if (buffered.OperationName == sibling.OperationName) + { + // TODO - Duration configuration check + + composite ??= new Composite(); + composite.CompressionStrategy = "exact_match"; + return true; + } + + // TODO - Duration configuration check + composite ??= new Composite(); + composite.CompressionStrategy = "same_kind"; + // TODO - Set name + return true; + } + + private static bool TryToCompressComposite(this Activity buffered, Activity sibling, Composite composite) + { + switch (composite.CompressionStrategy) + { + case "exact_match": + return buffered.IsSameKind(sibling) && buffered.OperationName == sibling.OperationName; // && sibling.Duration <= Configuration.SpanCompressionExactMatchMaxDuration; + + case "same_kind": + return buffered.IsSameKind(sibling); // && sibling.Duration <= Configuration.SpanCompressionSameKindMaxDuration; + } + + return false; + } + + // TODO - Further implementation if possible + private static bool IsSameKind(this Activity current, Activity other) => + current.Kind == other.Kind; + // We don't have a direct way to establish which attribute(s) to use to assess these + //&& Subtype == other.Subtype + //&& _context.IsValueCreated && other._context.IsValueCreated + //&& Context?.Service?.Target == other.Context?.Service?.Target; } diff --git a/src/Elastic.OpenTelemetry/Extensions/ResourceBuilderExtensions.cs b/src/Elastic.OpenTelemetry/Extensions/ResourceBuilderExtensions.cs index 5d1abf5..7254aeb 100644 --- a/src/Elastic.OpenTelemetry/Extensions/ResourceBuilderExtensions.cs +++ b/src/Elastic.OpenTelemetry/Extensions/ResourceBuilderExtensions.cs @@ -9,10 +9,10 @@ namespace Elastic.OpenTelemetry.Extensions; internal static class ResourceBuilderExtensions { - internal static ResourceBuilder AddDistroAttributes(this ResourceBuilder builder) => - builder.AddAttributes(new Dictionary - { - { ResourceSemanticConventions.AttributeTelemetryDistroName, "elastic-dotnet" }, - { ResourceSemanticConventions.AttributeTelemetryDistroVersion, Agent.InformationalVersion } - }); + internal static ResourceBuilder AddDistroAttributes(this ResourceBuilder builder) => + builder.AddAttributes(new Dictionary + { + { ResourceSemanticConventions.AttributeTelemetryDistroName, "elastic-dotnet" }, + { ResourceSemanticConventions.AttributeTelemetryDistroVersion, Agent.InformationalVersion } + }); } diff --git a/src/Elastic.OpenTelemetry/Extensions/TracerProviderBuilderExtensions.cs b/src/Elastic.OpenTelemetry/Extensions/TracerProviderBuilderExtensions.cs index 1f1e994..69e9ac4 100644 --- a/src/Elastic.OpenTelemetry/Extensions/TracerProviderBuilderExtensions.cs +++ b/src/Elastic.OpenTelemetry/Extensions/TracerProviderBuilderExtensions.cs @@ -1,13 +1,13 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using Elastic.OpenTelemetry.Processors; -using OpenTelemetry.Trace; -using OpenTelemetry; using System.Diagnostics; using Elastic.OpenTelemetry.Diagnostics; +using Elastic.OpenTelemetry.Processors; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using OpenTelemetry; +using OpenTelemetry.Trace; namespace Elastic.OpenTelemetry.Extensions; diff --git a/src/Elastic.OpenTelemetry/IOpenTelemetryBuilder.cs b/src/Elastic.OpenTelemetry/IOpenTelemetryBuilder.cs index 528e4ba..bcb1ef1 100644 --- a/src/Elastic.OpenTelemetry/IOpenTelemetryBuilder.cs +++ b/src/Elastic.OpenTelemetry/IOpenTelemetryBuilder.cs @@ -36,64 +36,64 @@ public interface IOpenTelemetryBuilder /// public static class OpenTelemetryBuilderSdkExtensions { - /// - /// Registers an action to configure the s used - /// by tracing, metrics, and logging. - /// - /// . - /// - /// Note: This is safe to be called multiple times and by library authors. - /// Each registered configuration action will be applied sequentially. - /// - /// configuration - /// action. - /// The supplied for chaining - /// calls. - public static IOpenTelemetryBuilder ConfigureResource( - this IOpenTelemetryBuilder builder, - Action configure) - { - builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.ConfigureResource(configure)); - - builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.ConfigureResource(configure)); - - //builder.Services.ConfigureOpenTelemetryLoggerProvider(builder => builder.ConfigureResource(configure)); + /// + /// Registers an action to configure the s used + /// by tracing, metrics, and logging. + /// + /// . + /// + /// Note: This is safe to be called multiple times and by library authors. + /// Each registered configuration action will be applied sequentially. + /// + /// configuration + /// action. + /// The supplied for chaining + /// calls. + public static IOpenTelemetryBuilder ConfigureResource( + this IOpenTelemetryBuilder builder, + Action configure) + { + builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.ConfigureResource(configure)); - return builder; - } - - /// - /// Adds metric services into the builder. - /// - /// . - /// - /// Notes: - /// - /// This is safe to be called multiple times and by library authors. - /// Only a single will be created for a given - /// . - /// This method automatically registers an named 'OpenTelemetry' into the . - /// - /// - /// The supplied for chaining - /// calls. - public static IOpenTelemetryBuilder WithMetrics(this IOpenTelemetryBuilder builder) - => WithMetrics(builder, _ => { }); - - /// - /// Adds metric services into the builder. - /// - /// - /// . - /// - /// configuration callback. - /// The supplied for chaining - /// calls. - public static IOpenTelemetryBuilder WithMetrics( - this IOpenTelemetryBuilder builder, - Action configure) + builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.ConfigureResource(configure)); + + //builder.Services.ConfigureOpenTelemetryLoggerProvider(builder => builder.ConfigureResource(configure)); + + return builder; + } + + /// + /// Adds metric services into the builder. + /// + /// . + /// + /// Notes: + /// + /// This is safe to be called multiple times and by library authors. + /// Only a single will be created for a given + /// . + /// This method automatically registers an named 'OpenTelemetry' into the . + /// + /// + /// The supplied for chaining + /// calls. + public static IOpenTelemetryBuilder WithMetrics(this IOpenTelemetryBuilder builder) + => WithMetrics(builder, _ => { }); + + /// + /// Adds metric services into the builder. + /// + /// + /// . + /// + /// configuration callback. + /// The supplied for chaining + /// calls. + public static IOpenTelemetryBuilder WithMetrics( + this IOpenTelemetryBuilder builder, + Action configure) { //internal temporary hack while we wait for IOpenTelemetryBuilder to ship //TODO cache @@ -110,34 +110,34 @@ public static IOpenTelemetryBuilder WithMetrics( return builder; */ - } - - /// - /// Adds tracing services into the builder. - /// - /// . - /// - /// Note: This is safe to be called multiple times and by library authors. - /// Only a single will be created for a given - /// . - /// - /// The supplied for chaining - /// calls. - public static IOpenTelemetryBuilder WithTracing(this IOpenTelemetryBuilder builder) - => WithTracing(builder, _ => { }); - - /// - /// Adds tracing services into the builder. - /// - /// - /// . - /// - /// configuration callback. - /// The supplied for chaining - /// calls. - public static IOpenTelemetryBuilder WithTracing( - this IOpenTelemetryBuilder builder, - Action configure) + } + + /// + /// Adds tracing services into the builder. + /// + /// . + /// + /// Note: This is safe to be called multiple times and by library authors. + /// Only a single will be created for a given + /// . + /// + /// The supplied for chaining + /// calls. + public static IOpenTelemetryBuilder WithTracing(this IOpenTelemetryBuilder builder) + => WithTracing(builder, _ => { }); + + /// + /// Adds tracing services into the builder. + /// + /// + /// . + /// + /// configuration callback. + /// The supplied for chaining + /// calls. + public static IOpenTelemetryBuilder WithTracing( + this IOpenTelemetryBuilder builder, + Action configure) { //internal temporary hack while we wait for IOpenTelemetryBuilder to ship @@ -149,11 +149,11 @@ public static IOpenTelemetryBuilder WithTracing( var lambda = Expression.Lambda>(body, value); var tracerProviderBuilder = lambda.Compile()(builder.Services); - //var tracerProviderBuilder = new TracerProviderBuilderBase(builder.Services); + //var tracerProviderBuilder = new TracerProviderBuilderBase(builder.Services); - configure(tracerProviderBuilder); + configure(tracerProviderBuilder); - return builder; - } + return builder; + } } diff --git a/src/Elastic.OpenTelemetry/Processors/Composite.cs b/src/Elastic.OpenTelemetry/Processors/Composite.cs index a388e02..223c2d7 100644 --- a/src/Elastic.OpenTelemetry/Processors/Composite.cs +++ b/src/Elastic.OpenTelemetry/Processors/Composite.cs @@ -6,18 +6,18 @@ namespace Elastic.OpenTelemetry.Processors; // TODO - Consider a struct, but consider if this would get copied too much internal class Composite { - /// - /// A string value indicating which compression strategy was used. The valid values are `exact_match` and `same_kind` - /// - public string CompressionStrategy { get; set; } = "exact_match"; + /// + /// A string value indicating which compression strategy was used. The valid values are `exact_match` and `same_kind` + /// + public string CompressionStrategy { get; set; } = "exact_match"; - /// - /// Count is the number of compressed spans the composite span represents. The minimum count is 2, as a composite span represents at least two spans. - /// - public int Count { get; set; } + /// + /// Count is the number of compressed spans the composite span represents. The minimum count is 2, as a composite span represents at least two spans. + /// + public int Count { get; set; } - /// - /// Sum of the durations of all compressed spans this composite span represents in milliseconds. - /// - public double DurationSum { get; set; } + /// + /// Sum of the durations of all compressed spans this composite span represents in milliseconds. + /// + public double DurationSum { get; set; } } diff --git a/src/Elastic.OpenTelemetry/Processors/SpanCompressionProcessor.cs b/src/Elastic.OpenTelemetry/Processors/SpanCompressionProcessor.cs index 0353926..6c5b508 100644 --- a/src/Elastic.OpenTelemetry/Processors/SpanCompressionProcessor.cs +++ b/src/Elastic.OpenTelemetry/Processors/SpanCompressionProcessor.cs @@ -1,70 +1,69 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using Elastic.OpenTelemetry.Extensions; - -using OpenTelemetry; - using System.Diagnostics; using System.Runtime.CompilerServices; +using Elastic.OpenTelemetry.Extensions; +using OpenTelemetry; namespace Elastic.OpenTelemetry.Processors; /// A processor that can mark spans as compressed/composite public class SpanCompressionProcessor : BaseProcessor { - private readonly ConditionalWeakTable _compressionBuffer = new(); + private readonly ConditionalWeakTable _compressionBuffer = new(); /// - public override void OnStart(Activity data) - { - if (data.DisplayName == "ChildSpanCompression") - data.SetCustomProperty("IsExitSpan", true); // Later, we'll have to infer this from the Activity Source and Name (if practical) + public override void OnStart(Activity data) + { + if (data.DisplayName == "ChildSpanCompression") + data.SetCustomProperty("IsExitSpan", true); // Later, we'll have to infer this from the Activity Source and Name (if practical) - base.OnStart(data); - } + base.OnStart(data); + } /// - public override void OnEnd(Activity data) - { - if (data.Parent is null) - { - base.OnEnd(data); - return; - } + public override void OnEnd(Activity data) + { + if (data.Parent is null) + { + base.OnEnd(data); + return; + } - var property = data.GetCustomProperty("IsExitSpan"); + var property = data.GetCustomProperty("IsExitSpan"); - if (!IsCompressionEligible(data, property) || data.Parent!.IsStopped) - { - FlushBuffer(data.Parent!); - base.OnEnd(data); - return; - } + if (!IsCompressionEligible(data, property) || data.Parent!.IsStopped) + { + FlushBuffer(data.Parent!); + base.OnEnd(data); + return; + } - if (_compressionBuffer.TryGetValue(data.Parent!, out var compressionBuffer)) - { - if (!compressionBuffer.TryCompress(data)) - { - FlushBuffer(data.Parent!); - _compressionBuffer.Add(data.Parent!, data); - } - } - else - { - _compressionBuffer.Add(data.Parent!, data); - data.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; - } + if (_compressionBuffer.TryGetValue(data.Parent!, out var compressionBuffer)) + { + if (!compressionBuffer.TryCompress(data)) + { + FlushBuffer(data.Parent!); + _compressionBuffer.Add(data.Parent!, data); + } + } + else + { + _compressionBuffer.Add(data.Parent!, data); + data.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; + } - base.OnEnd(data); + base.OnEnd(data); - static bool IsCompressionEligible(Activity data, object? property) => - property is true && data.Status is ActivityStatusCode.Ok or ActivityStatusCode.Unset; + static bool IsCompressionEligible(Activity data, object? property) => + property is true && data.Status is ActivityStatusCode.Ok or ActivityStatusCode.Unset; } private void FlushBuffer(Activity data) { - if (!_compressionBuffer.TryGetValue(data, out var compressionBuffer)) return; + if (!_compressionBuffer.TryGetValue(data, out var compressionBuffer)) + return; // This recreates the initial activity now we know it's final end time and can record it. using var activity = compressionBuffer.Source.StartActivity(compressionBuffer.DisplayName, compressionBuffer.Kind, compressionBuffer.Parent!.Context, diff --git a/src/Elastic.OpenTelemetry/Processors/SpanCounterProcessor.cs b/src/Elastic.OpenTelemetry/Processors/SpanCounterProcessor.cs index 0b602d3..03b1d59 100644 --- a/src/Elastic.OpenTelemetry/Processors/SpanCounterProcessor.cs +++ b/src/Elastic.OpenTelemetry/Processors/SpanCounterProcessor.cs @@ -1,23 +1,22 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using OpenTelemetry; - using System.Diagnostics; using System.Diagnostics.Metrics; +using OpenTelemetry; namespace Elastic.OpenTelemetry.Processors; /// An example processor that emits the number of spans as a metric public class SpanCounterProcessor : BaseProcessor { - private static readonly Meter Meter = new("Elastic.OpenTelemetry", "1.0.0"); - private static readonly Counter Counter = Meter.CreateCounter("span-export-count"); + private static readonly Meter Meter = new("Elastic.OpenTelemetry", "1.0.0"); + private static readonly Counter Counter = Meter.CreateCounter("span-export-count"); /// - public override void OnEnd(Activity data) - { - Counter.Add(1); - base.OnEnd(data); - } + public override void OnEnd(Activity data) + { + Counter.Add(1); + base.OnEnd(data); + } } diff --git a/src/Elastic.OpenTelemetry/Processors/StackTraceProcessor.cs b/src/Elastic.OpenTelemetry/Processors/StackTraceProcessor.cs index f14fd17..273d72c 100644 --- a/src/Elastic.OpenTelemetry/Processors/StackTraceProcessor.cs +++ b/src/Elastic.OpenTelemetry/Processors/StackTraceProcessor.cs @@ -1,8 +1,8 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using OpenTelemetry; using System.Diagnostics; +using OpenTelemetry; namespace Elastic.OpenTelemetry.Processors; @@ -10,21 +10,23 @@ namespace Elastic.OpenTelemetry.Processors; public class StackTraceProcessor : BaseProcessor { /// - public override void OnStart(Activity data) - { - //for now always capture stack trace on start - var stackTrace = new StackTrace(true); - data.SetCustomProperty("_stack_trace", stackTrace); - base.OnStart(data); - } + public override void OnStart(Activity data) + { + //for now always capture stack trace on start + var stackTrace = new StackTrace(true); + data.SetCustomProperty("_stack_trace", stackTrace); + base.OnStart(data); + } /// - public override void OnEnd(Activity data) - { - if (data.GetCustomProperty("_stack_trace") is not StackTrace stackTrace) return; - if (data.Duration < TimeSpan.FromMilliseconds(2)) return; + public override void OnEnd(Activity data) + { + if (data.GetCustomProperty("_stack_trace") is not StackTrace stackTrace) + return; + if (data.Duration < TimeSpan.FromMilliseconds(2)) + return; - data.SetTag("code.stacktrace", stackTrace); - base.OnEnd(data); - } + data.SetTag("code.stacktrace", stackTrace); + base.OnEnd(data); + } } diff --git a/src/Elastic.OpenTelemetry/Processors/TransactionIdProcessor.cs b/src/Elastic.OpenTelemetry/Processors/TransactionIdProcessor.cs index 958b76d..201eab1 100644 --- a/src/Elastic.OpenTelemetry/Processors/TransactionIdProcessor.cs +++ b/src/Elastic.OpenTelemetry/Processors/TransactionIdProcessor.cs @@ -26,7 +26,8 @@ public override void OnStart(Activity activity) if (activity.Parent == null) _currentTransactionId.Value = activity.SpanId; - if (!_currentTransactionId.Value.HasValue) return; + if (!_currentTransactionId.Value.HasValue) + return; activity.SetTag(TransactionIdTagName, _currentTransactionId.Value.Value.ToString()); logger.TransactionIdProcessorTagAdded(); diff --git a/src/Elastic.OpenTelemetry/Resources/DefaultServiceDetector.cs b/src/Elastic.OpenTelemetry/Resources/DefaultServiceDetector.cs index 5359017..4bc9522 100644 --- a/src/Elastic.OpenTelemetry/Resources/DefaultServiceDetector.cs +++ b/src/Elastic.OpenTelemetry/Resources/DefaultServiceDetector.cs @@ -9,31 +9,31 @@ namespace Elastic.OpenTelemetry.Resources; internal class DefaultServiceDetector : IResourceDetector { - private static readonly Resource DefaultResource; + private static readonly Resource DefaultResource; - static DefaultServiceDetector() - { - // This is replicated from https://github.com/open-telemetry/opentelemetry-dotnet/blob/00750ddcca5c2819238d5b8bda10753f58ba4a7a/src/OpenTelemetry/Resources/ResourceBuilder.cs - // as the default resource is not public. + static DefaultServiceDetector() + { + // This is replicated from https://github.com/open-telemetry/opentelemetry-dotnet/blob/00750ddcca5c2819238d5b8bda10753f58ba4a7a/src/OpenTelemetry/Resources/ResourceBuilder.cs + // as the default resource is not public. - var defaultServiceName = "unknown_service"; + var defaultServiceName = "unknown_service"; - try - { - var processName = Process.GetCurrentProcess().ProcessName; - if (!string.IsNullOrWhiteSpace(processName)) - defaultServiceName = $"{defaultServiceName}:{processName}"; - } - catch - { - // GetCurrentProcess can throw PlatformNotSupportedException - } + try + { + var processName = Process.GetCurrentProcess().ProcessName; + if (!string.IsNullOrWhiteSpace(processName)) + defaultServiceName = $"{defaultServiceName}:{processName}"; + } + catch + { + // GetCurrentProcess can throw PlatformNotSupportedException + } - DefaultResource = new Resource(new Dictionary - { - [ResourceSemanticConventions.AttributeServiceName] = defaultServiceName, - }); - } + DefaultResource = new Resource(new Dictionary + { + [ResourceSemanticConventions.AttributeServiceName] = defaultServiceName, + }); + } - public Resource Detect() => DefaultResource; + public Resource Detect() => DefaultResource; } diff --git a/src/Elastic.OpenTelemetry/SemanticConventions/ResourceSemanticConventions.cs b/src/Elastic.OpenTelemetry/SemanticConventions/ResourceSemanticConventions.cs index 436aae4..3a4305f 100644 --- a/src/Elastic.OpenTelemetry/SemanticConventions/ResourceSemanticConventions.cs +++ b/src/Elastic.OpenTelemetry/SemanticConventions/ResourceSemanticConventions.cs @@ -5,11 +5,11 @@ namespace Elastic.OpenTelemetry.SemanticConventions; internal static class ResourceSemanticConventions { - public const string AttributeDeploymentEnvironment = "deployment.environment"; + public const string AttributeDeploymentEnvironment = "deployment.environment"; - public const string AttributeServiceName = "service.name"; - public const string AttributeServiceVersion = "service.version"; + public const string AttributeServiceName = "service.name"; + public const string AttributeServiceVersion = "service.version"; - public const string AttributeTelemetryDistroName = "telemetry.distro.name"; - public const string AttributeTelemetryDistroVersion = "telemetry.distro.version"; + public const string AttributeTelemetryDistroName = "telemetry.distro.name"; + public const string AttributeTelemetryDistroVersion = "telemetry.distro.version"; } diff --git a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/ApmUIBrowserContext.cs b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/ApmUIBrowserContext.cs index 57c1ebb..9db31d3 100644 --- a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/ApmUIBrowserContext.cs +++ b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/ApmUIBrowserContext.cs @@ -39,8 +39,8 @@ public async Task InitializeAsync() var page = await OpenApmLandingPage("test_bootstrap"); try { - await page.GetByRole(AriaRole.Textbox, new () { Name = "email" }).FillAsync(username); - await page.GetByRole(AriaRole.Textbox, new () { Name = "password" }).FillAsync(password); + await page.GetByRole(AriaRole.Textbox, new() { Name = "email" }).FillAsync(username); + await page.GetByRole(AriaRole.Textbox, new() { Name = "password" }).FillAsync(password); await page.GetByRole(AriaRole.Button, new() { Name = "Log in" }).ClickAsync(); await WaitForServiceOnOverview(page); @@ -62,7 +62,7 @@ public async Task InitializeAsync() public async Task NewProfiledPage(string testName) { - var page = await Browser.NewPageAsync(new () { StorageState = StorageState }); + var page = await Browser.NewPageAsync(new() { StorageState = StorageState }); await page.Context.Tracing.StartAsync(new() { Title = testName, @@ -87,12 +87,12 @@ public async Task WaitForServiceOnOverview(IPage page) page.SetDefaultTimeout((float)TimeSpan.FromSeconds(30).TotalMilliseconds); var servicesHeader = page.GetByRole(AriaRole.Heading, new() { Name = "Services" }); - await servicesHeader.WaitForAsync(new () { State = WaitForSelectorState.Visible }); + await servicesHeader.WaitForAsync(new() { State = WaitForSelectorState.Visible }); page.SetDefaultTimeout((float)TimeSpan.FromSeconds(10).TotalMilliseconds); Exception? observed = null; - for (var i = 0; i < 10;i++) + for (var i = 0; i < 10; i++) { try { @@ -120,7 +120,7 @@ public async Task StopTrace(IPage page, string? testName = null) { if (string.IsNullOrWhiteSpace(testName)) - await page.Context.Tracing.StopAsync(new ()); + await page.Context.Tracing.StopAsync(new()); else { var root = DotNetRunApplication.GetSolutionRoot(); diff --git a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DistributedApplicationFixture.cs b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DistributedApplicationFixture.cs index 64297b3..c17af1b 100644 --- a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DistributedApplicationFixture.cs +++ b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DistributedApplicationFixture.cs @@ -12,7 +12,7 @@ namespace Elastic.OpenTelemetry.EndToEndTests.DistributedFixture; public class DistributedApplicationFixture : IPartitionLifetime { - private readonly ITrafficSimulator[] _trafficSimulators = [ new DefaultTrafficSimulator() ]; + private readonly ITrafficSimulator[] _trafficSimulators = [new DefaultTrafficSimulator()]; public string ServiceName { get; } = $"dotnet-e2e-{ShaForCurrentTicks()}"; diff --git a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DotNetRunApplication.cs b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DotNetRunApplication.cs index 5793840..cfd7a89 100644 --- a/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DotNetRunApplication.cs +++ b/tests/Elastic.OpenTelemetry.EndToEndTests/DistributedFixture/DotNetRunApplication.cs @@ -54,7 +54,7 @@ private LongRunningArguments CreateStartArgs() var arguments = new[] { "run", "--project", project }; var applicationArguments = GetArguments(); if (applicationArguments.Length > 0) - arguments = [..arguments, "--", ..applicationArguments]; + arguments = [.. arguments, "--", .. applicationArguments]; return new("dotnet", arguments) { @@ -71,7 +71,8 @@ private LongRunningArguments CreateStartArgs() StartedConfirmationHandler = l => { //Grab actual process id to send SIGINT to. - if (l.Line == null) return false; + if (l.Line == null) + return false; var processIdMatch = ProcessIdMatch.Match(l.Line); if (processIdMatch.Success) ProcessId = int.Parse(processIdMatch.Groups["processid"].Value); diff --git a/tests/Elastic.OpenTelemetry.EndToEndTests/ServiceTests.cs b/tests/Elastic.OpenTelemetry.EndToEndTests/ServiceTests.cs index 2e0b432..195ad63 100644 --- a/tests/Elastic.OpenTelemetry.EndToEndTests/ServiceTests.cs +++ b/tests/Elastic.OpenTelemetry.EndToEndTests/ServiceTests.cs @@ -16,7 +16,7 @@ public class EndToEndTests(ITestOutputHelper output, DistributedApplicationFixtu : IPartitionFixture, IAsyncLifetime { public ITestOutputHelper Output { get; } = output; - private string _testName = string.Empty; + private readonly string _testName = string.Empty; private IPage _page = null!; [Fact] diff --git a/tests/Elastic.OpenTelemetry.Tests/GlobalUsings.cs b/tests/Elastic.OpenTelemetry.Tests/GlobalUsings.cs index febe4db..dd6e8f8 100644 --- a/tests/Elastic.OpenTelemetry.Tests/GlobalUsings.cs +++ b/tests/Elastic.OpenTelemetry.Tests/GlobalUsings.cs @@ -1,9 +1,9 @@ // Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -global using Xunit; global using System.Diagnostics; global using Elastic.OpenTelemetry.Processors; global using FluentAssertions; global using OpenTelemetry.Resources; global using OpenTelemetry.Trace; +global using Xunit; diff --git a/tests/Elastic.OpenTelemetry.Tests/LoggingTests.cs b/tests/Elastic.OpenTelemetry.Tests/LoggingTests.cs index 8c6cfb5..e3748a0 100644 --- a/tests/Elastic.OpenTelemetry.Tests/LoggingTests.cs +++ b/tests/Elastic.OpenTelemetry.Tests/LoggingTests.cs @@ -2,7 +2,7 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information -using System.Net.Sockets; +using System.Diagnostics; using OpenTelemetry; using Xunit.Abstractions; diff --git a/tests/Elastic.OpenTelemetry.Tests/ServiceCollectionTests.cs b/tests/Elastic.OpenTelemetry.Tests/ServiceCollectionTests.cs index fd8dddc..d7d2666 100644 --- a/tests/Elastic.OpenTelemetry.Tests/ServiceCollectionTests.cs +++ b/tests/Elastic.OpenTelemetry.Tests/ServiceCollectionTests.cs @@ -10,15 +10,15 @@ namespace Elastic.OpenTelemetry.Tests; public class ServiceCollectionTests(ITestOutputHelper output) { - [Fact] - public async Task ServiceCollectionAddIsSafeToCallMultipleTimes() + [Fact] + public async Task ServiceCollectionAddIsSafeToCallMultipleTimes() { var options = new AgentBuilderOptions { Logger = new TestLogger(output), SkipOtlpExporter = true }; - const string activitySourceName = nameof(ServiceCollectionAddIsSafeToCallMultipleTimes); - var activitySource = new ActivitySource(activitySourceName, "1.0.0"); + const string activitySourceName = nameof(ServiceCollectionAddIsSafeToCallMultipleTimes); + var activitySource = new ActivitySource(activitySourceName, "1.0.0"); - var exportedItems = new List(); + var exportedItems = new List(); var host = Host.CreateDefaultBuilder(); host.ConfigureServices(s => @@ -44,6 +44,6 @@ public async Task ServiceCollectionAddIsSafeToCallMultipleTimes() } - exportedItems.Should().HaveCount(1); - } + exportedItems.Should().HaveCount(1); + } } diff --git a/tests/Elastic.OpenTelemetry.Tests/TransactionIdProcessorTests.cs b/tests/Elastic.OpenTelemetry.Tests/TransactionIdProcessorTests.cs index f21b79e..a2173e8 100644 --- a/tests/Elastic.OpenTelemetry.Tests/TransactionIdProcessorTests.cs +++ b/tests/Elastic.OpenTelemetry.Tests/TransactionIdProcessorTests.cs @@ -9,35 +9,35 @@ namespace Elastic.OpenTelemetry.Tests; public class TransactionIdProcessorTests(ITestOutputHelper output) { - [Fact] - public void TransactionId_IsAddedToTags() - { + [Fact] + public void TransactionId_IsAddedToTags() + { var options = new AgentBuilderOptions { Logger = new TestLogger(output), SkipOtlpExporter = true }; - const string activitySourceName = nameof(TransactionId_IsAddedToTags); + const string activitySourceName = nameof(TransactionId_IsAddedToTags); - var activitySource = new ActivitySource(activitySourceName, "1.0.0"); + var activitySource = new ActivitySource(activitySourceName, "1.0.0"); - var exportedItems = new List(); + var exportedItems = new List(); - using var agent = new AgentBuilder(options) - .WithTracing(tpb => + using var agent = new AgentBuilder(options) + .WithTracing(tpb => { tpb .ConfigureResource(rb => rb.AddService("Test", "1.0.0")) .AddSource(activitySourceName) .AddInMemoryExporter(exportedItems); }) - .Build(); + .Build(); - using (var activity = activitySource.StartActivity(ActivityKind.Internal)) + using (var activity = activitySource.StartActivity(ActivityKind.Internal)) activity?.SetStatus(ActivityStatusCode.Ok); exportedItems.Should().HaveCount(1); - var exportedActivity = exportedItems[0]; + var exportedActivity = exportedItems[0]; - var transactionId = exportedActivity.GetTagItem(TransactionIdProcessor.TransactionIdTagName); + var transactionId = exportedActivity.GetTagItem(TransactionIdProcessor.TransactionIdTagName); - transactionId.Should().NotBeNull().And.BeAssignableTo().Which.Should().NotBeEmpty(); - } + transactionId.Should().NotBeNull().And.BeAssignableTo().Which.Should().NotBeEmpty(); + } }