diff --git a/.github/codecov.yml b/.github/codecov.yml index 3b092699d84..1abd5d69c37 100644 --- a/.github/codecov.yml +++ b/.github/codecov.yml @@ -6,6 +6,7 @@ coverage: round: down range: "70...100" status: + project: off patch: off parsers: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a8455b9c787..c993fcd9115 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -114,14 +114,6 @@ Add your fork as an origin: git remote add fork https://github.com/YOUR_GITHUB_USERNAME/opentelemetry-dotnet.git ``` -By default your work will be targeting the `main` branch. If you want to work on -the experimental metrics feature, please switch to the `metrics` feature branch: - -```sh -# only do this when you want to work on the experimental metrics feature -git checkout metrics -``` - Run tests: ```sh @@ -174,8 +166,8 @@ A PR is considered to be **ready to merge** when: * Urgent fix can take exception as long as it has been actively communicated. Any Maintainer can merge the PR once it is **ready to merge**. Note, that some -PR may not be merged immediately if repo is being in process of a major release -and the new feature doesn't fit it. +PRs may not be merged immediately if the repo is in the process of a release and +the maintainers decided to defer the PR to the next release train. If a PR has been stuck (e.g. there are lots of debates and people couldn't agree on each other), the owner should try to get people aligned by: diff --git a/examples/Console/Program.cs b/examples/Console/Program.cs index d00d11db443..2c0468c7a7e 100644 --- a/examples/Console/Program.cs +++ b/examples/Console/Program.cs @@ -117,6 +117,9 @@ internal class MetricsOptions [Option("useExporter", Default = "console", HelpText = "Options include otlp or console.", Required = false)] public string UseExporter { get; set; } + + [Option('p', "useGrpc", HelpText = "Use gRPC or HTTP when using the OTLP exporter", Required = false, Default = true)] + public bool UseGrpc { get; set; } } [Verb("grpc", HelpText = "Specify the options required to test Grpc.Net.Client")] diff --git a/examples/Console/TestMetrics.cs b/examples/Console/TestMetrics.cs index 1f41b5380f3..3e20efcc541 100644 --- a/examples/Console/TestMetrics.cs +++ b/examples/Console/TestMetrics.cs @@ -21,6 +21,7 @@ using System.Threading; using System.Threading.Tasks; using OpenTelemetry; +using OpenTelemetry.Exporter; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; @@ -66,11 +67,13 @@ internal static object Run(MetricsOptions options) AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); providerBuilder - .AddOtlpExporter(o => + .AddOtlpExporter((exporterOptions, metricReaderOptions) => { - o.MetricReaderType = MetricReaderType.Periodic; - o.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds; - o.AggregationTemporality = options.IsDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative; + exporterOptions.Protocol = options.UseGrpc ? OtlpExportProtocol.Grpc : OtlpExportProtocol.HttpProtobuf; + + metricReaderOptions.MetricReaderType = MetricReaderType.Periodic; + metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds; + metricReaderOptions.Temporality = options.IsDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative; }); } else diff --git a/examples/MicroserviceExample/Utils/Messaging/MessageReceiver.cs b/examples/MicroserviceExample/Utils/Messaging/MessageReceiver.cs index 72dfa63040d..e5e321ad14f 100644 --- a/examples/MicroserviceExample/Utils/Messaging/MessageReceiver.cs +++ b/examples/MicroserviceExample/Utils/Messaging/MessageReceiver.cs @@ -31,7 +31,7 @@ namespace Utils.Messaging public class MessageReceiver : IDisposable { private static readonly ActivitySource ActivitySource = new ActivitySource(nameof(MessageReceiver)); - private static readonly TextMapPropagator Propagator = new TraceContextPropagator(); + private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator; private readonly ILogger logger; private readonly IConnection connection; diff --git a/src/OpenTelemetry.Api/Baggage.cs b/src/OpenTelemetry.Api/Baggage.cs index b9804921964..438fe5888d7 100644 --- a/src/OpenTelemetry.Api/Baggage.cs +++ b/src/OpenTelemetry.Api/Baggage.cs @@ -239,7 +239,7 @@ public IReadOnlyDictionary GetBaggage() /// Baggage item or if nothing was found. public string GetBaggage(string name) { - Guard.ThrowIfNullOrEmpty(name, nameof(name)); + Guard.ThrowIfNullOrEmpty(name); return this.baggage != null && this.baggage.TryGetValue(name, out string value) ? value diff --git a/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs b/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs index 5523db486ac..d6b1923eac0 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs @@ -35,7 +35,7 @@ public class CompositeTextMapPropagator : TextMapPropagator /// List of wire context propagator. public CompositeTextMapPropagator(IEnumerable propagators) { - Guard.ThrowIfNull(propagators, nameof(propagators)); + Guard.ThrowIfNull(propagators); this.propagators = new List(propagators); } diff --git a/src/OpenTelemetry.Api/Context/RuntimeContext.cs b/src/OpenTelemetry.Api/Context/RuntimeContext.cs index 9f0b022f951..5da426683e5 100644 --- a/src/OpenTelemetry.Api/Context/RuntimeContext.cs +++ b/src/OpenTelemetry.Api/Context/RuntimeContext.cs @@ -41,7 +41,7 @@ public static class RuntimeContext /// The slot registered. public static RuntimeContextSlot RegisterSlot(string slotName) { - Guard.ThrowIfNullOrEmpty(slotName, nameof(slotName)); + Guard.ThrowIfNullOrEmpty(slotName); lock (Slots) { @@ -66,9 +66,9 @@ public static RuntimeContextSlot RegisterSlot(string slotName) /// The slot previously registered. public static RuntimeContextSlot GetSlot(string slotName) { - Guard.ThrowIfNullOrEmpty(slotName, nameof(slotName)); + Guard.ThrowIfNullOrEmpty(slotName); var slot = GuardNotFound(slotName); - var contextSlot = Guard.ThrowIfNotOfType>(slot, nameof(slot)); + var contextSlot = Guard.ThrowIfNotOfType>(slot); return contextSlot; } @@ -127,9 +127,9 @@ public static T GetValue(string slotName) /// The value to be set. public static void SetValue(string slotName, object value) { - Guard.ThrowIfNullOrEmpty(slotName, nameof(slotName)); + Guard.ThrowIfNullOrEmpty(slotName); var slot = GuardNotFound(slotName); - var runtimeContextSlotValueAccessor = Guard.ThrowIfNotOfType(slot, nameof(slot)); + var runtimeContextSlotValueAccessor = Guard.ThrowIfNotOfType(slot); runtimeContextSlotValueAccessor.Value = value; } @@ -140,9 +140,9 @@ public static void SetValue(string slotName, object value) /// The value retrieved from the context slot. public static object GetValue(string slotName) { - Guard.ThrowIfNullOrEmpty(slotName, nameof(slotName)); + Guard.ThrowIfNullOrEmpty(slotName); var slot = GuardNotFound(slotName); - var runtimeContextSlotValueAccessor = Guard.ThrowIfNotOfType(slot, nameof(slot)); + var runtimeContextSlotValueAccessor = Guard.ThrowIfNotOfType(slot); return runtimeContextSlotValueAccessor.Value; } diff --git a/src/OpenTelemetry.Api/Internal/Guard.cs b/src/OpenTelemetry.Api/Internal/Guard.cs index 46d57c03aa5..ea8449e4ccf 100644 --- a/src/OpenTelemetry.Api/Internal/Guard.cs +++ b/src/OpenTelemetry.Api/Internal/Guard.cs @@ -19,15 +19,45 @@ using System.Runtime.CompilerServices; using System.Threading; +#if !NETCOREAPP3_0_OR_GREATER +namespace System.Runtime.CompilerServices +{ + /// + /// Allows capturing of the expressions passed to a method. + /// + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +#pragma warning disable SA1402 // File may only contain a single type +#pragma warning disable SA1649 // File name should match first type name + internal sealed class CallerArgumentExpressionAttribute : Attribute +#pragma warning restore SA1649 // File name should match first type name +#pragma warning restore SA1402 // File may only contain a single type + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the targeted parameter. + public CallerArgumentExpressionAttribute(string parameterName) + { + this.ParameterName = parameterName; + } + + /// + /// Gets the target parameter name of the CallerArgumentExpression. + /// + public string ParameterName { get; } + } +} +#endif + +#pragma warning disable SA1403 // File may only contain a single namespace namespace OpenTelemetry.Internal +#pragma warning restore SA1403 // File may only contain a single namespace { /// /// Methods for guarding against exception throwing values. /// internal static class Guard { - private const string DefaultParamName = "N/A"; - /// /// Throw an exception if the value is null. /// @@ -35,7 +65,7 @@ internal static class Guard /// The parameter name to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfNull(object value, string paramName = DefaultParamName) + public static void ThrowIfNull(object value, [CallerArgumentExpression("value")] string paramName = null) { if (value is null) { @@ -50,7 +80,7 @@ public static void ThrowIfNull(object value, string paramName = DefaultParamName /// The parameter name to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfNullOrEmpty(string value, string paramName = DefaultParamName) + public static void ThrowIfNullOrEmpty(string value, [CallerArgumentExpression("value")] string paramName = null) { if (string.IsNullOrEmpty(value)) { @@ -65,7 +95,7 @@ public static void ThrowIfNullOrEmpty(string value, string paramName = DefaultPa /// The parameter name to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfNullOrWhitespace(string value, string paramName = DefaultParamName) + public static void ThrowIfNullOrWhitespace(string value, [CallerArgumentExpression("value")] string paramName = null) { if (string.IsNullOrWhiteSpace(value)) { @@ -81,7 +111,7 @@ public static void ThrowIfNullOrWhitespace(string value, string paramName = Defa /// The parameter name to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfZero(int value, string message = "Must not be zero", string paramName = DefaultParamName) + public static void ThrowIfZero(int value, string message = "Must not be zero", [CallerArgumentExpression("value")] string paramName = null) { if (value == 0) { @@ -96,7 +126,7 @@ public static void ThrowIfZero(int value, string message = "Must not be zero", s /// The parameter name to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfInvalidTimeout(int value, string paramName = DefaultParamName) + public static void ThrowIfInvalidTimeout(int value, [CallerArgumentExpression("value")] string paramName = null) { ThrowIfOutOfRange(value, paramName, min: Timeout.Infinite, message: $"Must be non-negative or '{nameof(Timeout)}.{nameof(Timeout.Infinite)}'"); } @@ -113,7 +143,7 @@ public static void ThrowIfInvalidTimeout(int value, string paramName = DefaultPa /// An optional custom message to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfOutOfRange(int value, string paramName = DefaultParamName, int min = int.MinValue, int max = int.MaxValue, string minName = null, string maxName = null, string message = null) + public static void ThrowIfOutOfRange(int value, [CallerArgumentExpression("value")] string paramName = null, int min = int.MinValue, int max = int.MaxValue, string minName = null, string maxName = null, string message = null) { Range(value, paramName, min, max, minName, maxName, message); } @@ -130,7 +160,7 @@ public static void ThrowIfOutOfRange(int value, string paramName = DefaultParamN /// An optional custom message to use in the thrown exception. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfOutOfRange(double value, string paramName = DefaultParamName, double min = double.MinValue, double max = double.MaxValue, string minName = null, string maxName = null, string message = null) + public static void ThrowIfOutOfRange(double value, [CallerArgumentExpression("value")] string paramName = null, double min = double.MinValue, double max = double.MaxValue, string minName = null, string maxName = null, string message = null) { Range(value, paramName, min, max, minName, maxName, message); } @@ -144,7 +174,7 @@ public static void ThrowIfOutOfRange(double value, string paramName = DefaultPar /// The value casted to the specified type. [DebuggerHidden] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T ThrowIfNotOfType(object value, string paramName = DefaultParamName) + public static T ThrowIfNotOfType(object value, [CallerArgumentExpression("value")] string paramName = null) { if (value is not T result) { diff --git a/src/OpenTelemetry.Api/Internal/SpanHelper.cs b/src/OpenTelemetry.Api/Internal/SpanHelper.cs index b48a20dbf8f..a69e3579281 100644 --- a/src/OpenTelemetry.Api/Internal/SpanHelper.cs +++ b/src/OpenTelemetry.Api/Internal/SpanHelper.cs @@ -14,6 +14,8 @@ // limitations under the License. // +using System.Diagnostics; + namespace OpenTelemetry.Trace { /// @@ -25,11 +27,13 @@ internal static class SpanHelper /// Helper method that populates span properties from http status code according /// to https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#status. /// + /// The span kind. /// Http status code. /// Resolved span for the Http status code. - public static Status ResolveSpanStatusForHttpStatusCode(int httpStatusCode) + public static Status ResolveSpanStatusForHttpStatusCode(ActivityKind kind, int httpStatusCode) { - if (httpStatusCode >= 100 && httpStatusCode <= 399) + var upperBound = kind == ActivityKind.Client ? 399 : 499; + if (httpStatusCode >= 100 && httpStatusCode <= upperBound) { return Status.Unset; } diff --git a/src/OpenTelemetry.Api/Trace/SpanAttributes.cs b/src/OpenTelemetry.Api/Trace/SpanAttributes.cs index f247d291cea..f5672c71978 100644 --- a/src/OpenTelemetry.Api/Trace/SpanAttributes.cs +++ b/src/OpenTelemetry.Api/Trace/SpanAttributes.cs @@ -41,7 +41,7 @@ public SpanAttributes() public SpanAttributes(IEnumerable> attributes) : this() { - Guard.ThrowIfNull(attributes, nameof(attributes)); + Guard.ThrowIfNull(attributes); foreach (KeyValuePair kvp in attributes) { @@ -133,7 +133,7 @@ public void Add(string key, double[] values) private void AddInternal(string key, object value) { - Guard.ThrowIfNull(key, nameof(key)); + Guard.ThrowIfNull(key); this.Attributes[key] = value; } diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleActivityExporter.cs b/src/OpenTelemetry.Exporter.Console/ConsoleActivityExporter.cs index d24317b1f16..0cfe228e6bd 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleActivityExporter.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleActivityExporter.cs @@ -32,10 +32,17 @@ public override ExportResult Export(in Batch batch) { foreach (var activity in batch) { - this.WriteLine($"Activity.Id: {activity.Id}"); - if (!string.IsNullOrEmpty(activity.ParentId)) + this.WriteLine($"Activity.TraceId: {activity.TraceId}"); + this.WriteLine($"Activity.SpanId: {activity.SpanId}"); + this.WriteLine($"Activity.TraceFlags: {activity.ActivityTraceFlags}"); + if (!string.IsNullOrEmpty(activity.TraceStateString)) { - this.WriteLine($"Activity.ParentId: {activity.ParentId}"); + this.WriteLine($"Activity.TraceState: {activity.TraceStateString}"); + } + + if (activity.ParentSpanId != default) + { + this.WriteLine($"Activity.ParentSpanId: {activity.ParentSpanId}"); } this.WriteLine($"Activity.ActivitySourceName: {activity.Source.Name}"); @@ -45,7 +52,7 @@ public override ExportResult Export(in Batch batch) this.WriteLine($"Activity.Duration: {activity.Duration}"); if (activity.TagObjects.Any()) { - this.WriteLine("Activity.TagObjects:"); + this.WriteLine("Activity.Tags:"); foreach (var tag in activity.TagObjects) { var array = tag.Value as Array; diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs index 4a0c8a6017d..56073eebb0e 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs @@ -31,7 +31,7 @@ public static class ConsoleExporterHelperExtensions [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] public static TracerProviderBuilder AddConsoleExporter(this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs b/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs index 1c9a2d9bce5..6cec91dfed2 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs @@ -23,14 +23,14 @@ namespace OpenTelemetry.Logs public static class ConsoleExporterLoggingExtensions { /// - /// Adds Console Exporter as a configuration to the OpenTelemetry ILoggingBuilder. + /// Adds Console exporter with OpenTelemetryLoggerOptions. /// /// options to use. /// Exporter configuration options. /// The instance of to chain the calls. public static OpenTelemetryLoggerOptions AddConsoleExporter(this OpenTelemetryLoggerOptions loggerOptions, Action configure = null) { - Guard.ThrowIfNull(loggerOptions, nameof(loggerOptions)); + Guard.ThrowIfNull(loggerOptions); var options = new ConsoleExporterOptions(); configure?.Invoke(options); diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs b/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs index b07ed46366d..e2cfba27fe0 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs @@ -31,7 +31,7 @@ public static class ConsoleExporterMetricsExtensions [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] public static MeterProviderBuilder AddConsoleExporter(this MeterProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var options = new ConsoleExporterOptions(); configure?.Invoke(options); diff --git a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs index 3a49d915075..db2de77d32a 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs @@ -32,8 +32,8 @@ public static class InMemoryExporterHelperExtensions [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] public static TracerProviderBuilder AddInMemoryExporter(this TracerProviderBuilder builder, ICollection exportedItems) { - Guard.ThrowIfNull(builder, nameof(builder)); - Guard.ThrowIfNull(exportedItems, nameof(exportedItems)); + Guard.ThrowIfNull(builder); + Guard.ThrowIfNull(exportedItems); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs index 4a64390f303..9cbde894ced 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs @@ -24,8 +24,8 @@ public static class InMemoryExporterLoggingExtensions { public static OpenTelemetryLoggerOptions AddInMemoryExporter(this OpenTelemetryLoggerOptions loggerOptions, ICollection exportedItems) { - Guard.ThrowIfNull(loggerOptions, nameof(loggerOptions)); - Guard.ThrowIfNull(exportedItems, nameof(exportedItems)); + Guard.ThrowIfNull(loggerOptions); + Guard.ThrowIfNull(exportedItems); return loggerOptions.AddProcessor(new SimpleLogRecordExportProcessor(new InMemoryExporter(exportedItems))); } diff --git a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs index 97d3a3eabf8..a7465262adc 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs @@ -30,8 +30,8 @@ public static class InMemoryExporterMetricsExtensions /// The instance of to chain the calls. public static MeterProviderBuilder AddInMemoryExporter(this MeterProviderBuilder builder, ICollection exportedItems) { - Guard.ThrowIfNull(builder, nameof(builder)); - Guard.ThrowIfNull(exportedItems, nameof(exportedItems)); + Guard.ThrowIfNull(builder); + Guard.ThrowIfNull(exportedItems); return builder.AddReader(new BaseExportingMetricReader(new InMemoryExporter(exportedItems))); } diff --git a/src/OpenTelemetry.Exporter.Jaeger/CHANGELOG.md b/src/OpenTelemetry.Exporter.Jaeger/CHANGELOG.md index bdda877d331..2ad0e3555a9 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.Jaeger/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +* Change supported values for `OTEL_EXPORTER_JAEGER_PROTOCOL` + Supported values: `udp/thrift.compact` and `http/thrift.binary` defined + in the [specification](https://github.com/open-telemetry/opentelemetry-specification/blob/9a0a3300c6269c2837a1d7c9c5232ec816f63222/specification/sdk-environment-variables.md?plain=1#L129). + ([#2914](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2914)) + ## 1.2.0-rc2 Released 2022-Feb-02 diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs index 3de88ba15b5..5d57747a57b 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs @@ -50,7 +50,7 @@ public JaegerExporter(JaegerExporterOptions options) internal JaegerExporter(JaegerExporterOptions options, TProtocolFactory protocolFactory = null, IJaegerClient client = null) { - Guard.ThrowIfNull(options, nameof(options)); + Guard.ThrowIfNull(options); this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0) ? JaegerExporterOptions.DefaultMaxPayloadSizeInBytes @@ -122,7 +122,7 @@ public override ExportResult Export(in Batch activityBatch) internal void SetResourceAndInitializeBatch(Resource resource) { - Guard.ThrowIfNull(resource, nameof(resource)); + Guard.ThrowIfNull(resource); var process = this.Process; diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs index 7d3e641d5be..41965dba98f 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs @@ -35,7 +35,7 @@ public static class JaegerExporterHelperExtensions /// The instance of to chain the calls. public static TracerProviderBuilder AddJaegerExporter(this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptions.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptions.cs index a0a6d61b610..9845c0e0b77 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptions.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptions.cs @@ -35,7 +35,7 @@ public class JaegerExporterOptions { internal const int DefaultMaxPayloadSizeInBytes = 4096; - internal const string OtelProtocolEnvVarKey = "OTEL_EXPORTER_JAEGER_PROTOCOL"; + internal const string OTelProtocolEnvVarKey = "OTEL_EXPORTER_JAEGER_PROTOCOL"; internal const string OTelAgentHostEnvVarKey = "OTEL_EXPORTER_JAEGER_AGENT_HOST"; internal const string OTelAgentPortEnvVarKey = "OTEL_EXPORTER_JAEGER_AGENT_PORT"; internal const string OTelEndpointEnvVarKey = "OTEL_EXPORTER_JAEGER_ENDPOINT"; @@ -45,10 +45,18 @@ public class JaegerExporterOptions public JaegerExporterOptions() { - if (EnvironmentVariableHelper.LoadString(OtelProtocolEnvVarKey, out string protocolEnvVar) - && Enum.TryParse(protocolEnvVar, ignoreCase: true, out JaegerExportProtocol protocol)) + if (EnvironmentVariableHelper.LoadString(OTelProtocolEnvVarKey, out string protocolEnvVar)) { - this.Protocol = protocol; + var protocol = protocolEnvVar.ToJaegerExportProtocol(); + + if (protocol.HasValue) + { + this.Protocol = protocol.Value; + } + else + { + throw new FormatException($"{OTelProtocolEnvVarKey} environment variable has an invalid value: '{protocolEnvVar}'"); + } } if (EnvironmentVariableHelper.LoadString(OTelAgentHostEnvVarKey, out string agentHostEnvVar)) diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptionsExtensions.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptionsExtensions.cs new file mode 100644 index 00000000000..12f225e421d --- /dev/null +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterOptionsExtensions.cs @@ -0,0 +1,28 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace OpenTelemetry.Exporter; + +internal static class JaegerExporterOptionsExtensions +{ + public static JaegerExportProtocol? ToJaegerExportProtocol(this string protocol) => + protocol?.Trim() switch + { + "udp/thrift.compact" => JaegerExportProtocol.UdpCompactThrift, + "http/thrift.binary" => JaegerExportProtocol.HttpBinaryThrift, + _ => null, + }; +} diff --git a/src/OpenTelemetry.Exporter.Jaeger/README.md b/src/OpenTelemetry.Exporter.Jaeger/README.md index 57c9ba4f476..b73455af405 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/README.md +++ b/src/OpenTelemetry.Exporter.Jaeger/README.md @@ -64,10 +64,10 @@ properties: * `Protocol`: The protocol to use. The default value is `UdpCompactThrift`. - | Protocol | Description | - |----------------|-------------------------------------------------------| - |UdpCompactThrift| Apache Thrift compact over UDP to a Jaeger Agent. | - |HttpBinaryThrift| Apache Thrift binary over HTTP to a Jaeger Collector. | + | Protocol | Description | + |------------------|-------------------------------------------------------| + |`UdpCompactThrift`| Apache Thrift compact over UDP to a Jaeger Agent. | + |`HttpBinaryThrift`| Apache Thrift binary over HTTP to a Jaeger Collector. | See the [`TestJaegerExporter.cs`](../../examples/Console/TestJaegerExporter.cs) for an example of how to use the exporter. @@ -75,14 +75,17 @@ for an example of how to use the exporter. ## Environment Variables The following environment variables can be used to override the default -values of the `JaegerExporterOptions`. - -| Environment variable | `JaegerExporterOptions` property | -| ---------------------------------- | -------------------------------- | -| `OTEL_EXPORTER_JAEGER_AGENT_HOST` | `AgentHost` | -| `OTEL_EXPORTER_JAEGER_AGENT_PORT` | `AgentPort` | -| `OTEL_EXPORTER_JAEGER_ENDPOINT` | `Endpoint` | -| `OTEL_EXPORTER_JAEGER_PROTOCOL` | `Protocol` | +values of the `JaegerExporterOptions` +(following the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md#jaeger-exporter)). + + +| Environment variable | `JaegerExporterOptions` property | +|-----------------------------------|-----------------------------------------------------------| +| `OTEL_EXPORTER_JAEGER_AGENT_HOST` | `AgentHost` | +| `OTEL_EXPORTER_JAEGER_AGENT_PORT` | `AgentPort` | +| `OTEL_EXPORTER_JAEGER_ENDPOINT` | `Endpoint` | +| `OTEL_EXPORTER_JAEGER_PROTOCOL` | `Protocol` (`udp/thrift.compact` or `http/thrift.binary`) | + `FormatException` is thrown in case of an invalid value for any of the supported environment variables. diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net461/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net461/PublicAPI.Unshipped.txt index ed28f69db50..a019b19a6ba 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net461/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net461/PublicAPI.Unshipped.txt @@ -1,6 +1,4 @@ OpenTelemetry.Exporter.OtlpExporterOptions -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.get -> OpenTelemetry.Metrics.AggregationTemporality -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.BatchExportProcessorOptions.get -> OpenTelemetry.BatchExportProcessorOptions OpenTelemetry.Exporter.OtlpExporterOptions.BatchExportProcessorOptions.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.Endpoint.get -> System.Uri @@ -9,10 +7,6 @@ OpenTelemetry.Exporter.OtlpExporterOptions.ExportProcessorType.get -> OpenTeleme OpenTelemetry.Exporter.OtlpExporterOptions.ExportProcessorType.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.Headers.get -> string OpenTelemetry.Exporter.OtlpExporterOptions.Headers.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.get -> System.Func OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.OtlpExporterOptions() -> void @@ -33,5 +27,7 @@ override OpenTelemetry.Exporter.OtlpMetricExporter.Export(in OpenTelemetry.Batch override OpenTelemetry.Exporter.OtlpMetricExporter.OnShutdown(int timeoutMilliseconds) -> bool override OpenTelemetry.Exporter.OtlpTraceExporter.Export(in OpenTelemetry.Batch activityBatch) -> OpenTelemetry.ExportResult override OpenTelemetry.Exporter.OtlpTraceExporter.OnShutdown(int timeoutMilliseconds) -> bool -static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configure = null) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporterAndMetricReader) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporter) -> OpenTelemetry.Metrics.MeterProviderBuilder static OpenTelemetry.Trace.OtlpTraceExporterHelperExtensions.AddOtlpExporter(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action configure = null) -> OpenTelemetry.Trace.TracerProviderBuilder diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net5.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net5.0/PublicAPI.Unshipped.txt index f59367caac1..4e91c691456 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net5.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/net5.0/PublicAPI.Unshipped.txt @@ -1,9 +1,3 @@ -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.get -> OpenTelemetry.Metrics.AggregationTemporality -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.get -> System.Func OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.Protocol.get -> OpenTelemetry.Exporter.OtlpExportProtocol @@ -16,4 +10,6 @@ OpenTelemetry.Exporter.OtlpMetricExporter.OtlpMetricExporter(OpenTelemetry.Expor OpenTelemetry.Metrics.OtlpMetricExporterExtensions override OpenTelemetry.Exporter.OtlpMetricExporter.Export(in OpenTelemetry.Batch metrics) -> OpenTelemetry.ExportResult override OpenTelemetry.Exporter.OtlpMetricExporter.OnShutdown(int timeoutMilliseconds) -> bool -static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configure = null) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporterAndMetricReader) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporter) -> OpenTelemetry.Metrics.MeterProviderBuilder diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt index f59367caac1..4e91c691456 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -1,9 +1,3 @@ -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.get -> OpenTelemetry.Metrics.AggregationTemporality -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.get -> System.Func OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.Protocol.get -> OpenTelemetry.Exporter.OtlpExportProtocol @@ -16,4 +10,6 @@ OpenTelemetry.Exporter.OtlpMetricExporter.OtlpMetricExporter(OpenTelemetry.Expor OpenTelemetry.Metrics.OtlpMetricExporterExtensions override OpenTelemetry.Exporter.OtlpMetricExporter.Export(in OpenTelemetry.Batch metrics) -> OpenTelemetry.ExportResult override OpenTelemetry.Exporter.OtlpMetricExporter.OnShutdown(int timeoutMilliseconds) -> bool -static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configure = null) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporterAndMetricReader) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporter) -> OpenTelemetry.Metrics.MeterProviderBuilder diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.1/PublicAPI.Unshipped.txt b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.1/PublicAPI.Unshipped.txt index f59367caac1..4e91c691456 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.1/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/.publicApi/netstandard2.1/PublicAPI.Unshipped.txt @@ -1,9 +1,3 @@ -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.get -> OpenTelemetry.Metrics.AggregationTemporality -OpenTelemetry.Exporter.OtlpExporterOptions.AggregationTemporality.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType -OpenTelemetry.Exporter.OtlpExporterOptions.MetricReaderType.set -> void -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions -OpenTelemetry.Exporter.OtlpExporterOptions.PeriodicExportingMetricReaderOptions.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.get -> System.Func OpenTelemetry.Exporter.OtlpExporterOptions.HttpClientFactory.set -> void OpenTelemetry.Exporter.OtlpExporterOptions.Protocol.get -> OpenTelemetry.Exporter.OtlpExportProtocol @@ -16,4 +10,6 @@ OpenTelemetry.Exporter.OtlpMetricExporter.OtlpMetricExporter(OpenTelemetry.Expor OpenTelemetry.Metrics.OtlpMetricExporterExtensions override OpenTelemetry.Exporter.OtlpMetricExporter.Export(in OpenTelemetry.Batch metrics) -> OpenTelemetry.ExportResult override OpenTelemetry.Exporter.OtlpMetricExporter.OnShutdown(int timeoutMilliseconds) -> bool -static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configure = null) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporterAndMetricReader) -> OpenTelemetry.Metrics.MeterProviderBuilder +static OpenTelemetry.Metrics.OtlpMetricExporterExtensions.AddOtlpExporter(this OpenTelemetry.Metrics.MeterProviderBuilder builder, System.Action configureExporter) -> OpenTelemetry.Metrics.MeterProviderBuilder diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/ApiCompatBaseline.txt b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/ApiCompatBaseline.txt new file mode 100644 index 00000000000..e7158253a98 --- /dev/null +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/ApiCompatBaseline.txt @@ -0,0 +1,4 @@ +Compat issues with assembly OpenTelemetry.Exporter.OpenTelemetryProtocol: +CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.CompilerGeneratedAttribute' exists on 'OpenTelemetry.Exporter.OtlpExporterOptions.Endpoint.get()' in the contract but not the implementation. +CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.CompilerGeneratedAttribute' exists on 'OpenTelemetry.Exporter.OtlpExporterOptions.Endpoint.set(System.Uri)' in the contract but not the implementation. +Total Issues: 2 diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/CHANGELOG.md b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/CHANGELOG.md index 1a046e0b9d4..da8dedcd2ad 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/CHANGELOG.md @@ -3,7 +3,11 @@ ## Unreleased * LogExporter bug fix to handle null EventName. - ([#2870](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2871)) + ([#2871](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2871)) + +* Fixed the default endpoint for OTLP exporter over HTTP/Protobuf. + The default value is `http://localhost:4318`. + ([#2868](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2868)) ## 1.2.0-rc2 diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs index 69c0b03e749..12af999d820 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs @@ -30,8 +30,8 @@ internal abstract class BaseOtlpGrpcExportClient : IExportClient : IExportClient>((d, k, v) => d.Add(k, v)); diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs index a5725b9ba6c..47435178ce5 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs @@ -44,14 +44,20 @@ public class OtlpExporterOptions internal readonly Func DefaultHttpClientFactory; + private const string DefaultGrpcEndpoint = "http://localhost:4317"; + private const string DefaultHttpEndpoint = "http://localhost:4318"; + private const OtlpExportProtocol DefaultOtlpExportProtocol = OtlpExportProtocol.Grpc; + + private Uri endpoint; + /// /// Initializes a new instance of the class. /// public OtlpExporterOptions() { - if (EnvironmentVariableHelper.LoadUri(EndpointEnvVarName, out Uri endpoint)) + if (EnvironmentVariableHelper.LoadUri(EndpointEnvVarName, out Uri parsedEndpoint)) { - this.Endpoint = endpoint; + this.endpoint = parsedEndpoint; } if (EnvironmentVariableHelper.LoadString(HeadersEnvVarName, out string headersEnvVar)) @@ -73,13 +79,13 @@ public OtlpExporterOptions() } else { - throw new FormatException($"{ProtocolEnvVarName} environment variable has an invalid value: '${protocolEnvVar}'"); + throw new FormatException($"{ProtocolEnvVarName} environment variable has an invalid value: '{protocolEnvVar}'"); } } this.HttpClientFactory = this.DefaultHttpClientFactory = () => { - return new HttpClient() + return new HttpClient { Timeout = TimeSpan.FromMilliseconds(this.TimeoutMilliseconds), }; @@ -89,9 +95,30 @@ public OtlpExporterOptions() /// /// Gets or sets the target to which the exporter is going to send telemetry. /// Must be a valid Uri with scheme (http or https) and host, and - /// may contain a port and path. The default value is http://localhost:4317. + /// may contain a port and path. The default value is + /// * http://localhost:4317 for + /// * http://localhost:4318 for . /// - public Uri Endpoint { get; set; } = new Uri("http://localhost:4317"); + public Uri Endpoint + { + get + { + if (this.endpoint == null) + { + this.endpoint = this.Protocol == OtlpExportProtocol.Grpc + ? new Uri(DefaultGrpcEndpoint) + : new Uri(DefaultHttpEndpoint); + } + + return this.endpoint; + } + + set + { + this.endpoint = value; + this.ProgrammaticallyModifiedEndpoint = true; + } + } /// /// Gets or sets optional headers for the connection. Refer to the @@ -107,7 +134,7 @@ public OtlpExporterOptions() /// /// Gets or sets the the OTLP transport protocol. Supported values: Grpc and HttpProtobuf. /// - public OtlpExportProtocol Protocol { get; set; } = OtlpExportProtocol.Grpc; + public OtlpExportProtocol Protocol { get; set; } = DefaultOtlpExportProtocol; /// /// Gets or sets the export processor type to be used with the OpenTelemetry Protocol Exporter. The default value is . @@ -119,22 +146,6 @@ public OtlpExporterOptions() /// public BatchExportProcessorOptions BatchExportProcessorOptions { get; set; } = new BatchExportActivityProcessorOptions(); - /// - /// Gets or sets the to use. Defaults to MetricReaderType.Periodic. - /// - public MetricReaderType MetricReaderType { get; set; } = MetricReaderType.Periodic; - - /// - /// Gets or sets the options. Ignored unless MetricReaderType is Periodic. - /// - public PeriodicExportingMetricReaderOptions PeriodicExportingMetricReaderOptions { get; set; } = new PeriodicExportingMetricReaderOptions(); - - /// - /// Gets or sets the AggregationTemporality used for Histogram - /// and Sum metrics. - /// - public AggregationTemporality AggregationTemporality { get; set; } = AggregationTemporality.Cumulative; - /// /// Gets or sets the factory function called to create the instance that will be used at runtime to @@ -167,5 +178,10 @@ public OtlpExporterOptions() /// /// public Func HttpClientFactory { get; set; } + + /// + /// Gets a value indicating whether was modified via its setter. + /// + internal bool ProgrammaticallyModifiedEndpoint { get; private set; } } } diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptionsExtensions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptionsExtensions.cs index 3760a1830de..407e9b30b40 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptionsExtensions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptionsExtensions.cs @@ -155,12 +155,12 @@ public static void TryEnableIHttpClientFactoryIntegration(this OtlpExporterOptio } } - internal static void AppendExportPath(this OtlpExporterOptions options, Uri initialEndpoint, string exportRelativePath) + internal static void AppendExportPath(this OtlpExporterOptions options, string exportRelativePath) { // The exportRelativePath is only appended when the options.Endpoint property wasn't set by the user, // the protocol is HttpProtobuf and the OTEL_EXPORTER_OTLP_ENDPOINT environment variable // is present. If the user provides a custom value for options.Endpoint that value is taken as is. - if (ReferenceEquals(initialEndpoint, options.Endpoint)) + if (!options.ProgrammaticallyModifiedEndpoint) { if (options.Protocol == OtlpExportProtocol.HttpProtobuf) { diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporter.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporter.cs index c033436b392..22fdd978d4d 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporter.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpLogExporter.cs @@ -70,10 +70,10 @@ public override ExportResult Export(in Batch logRecordBatch) var request = new OtlpCollector.ExportLogsServiceRequest(); - request.AddBatch(this.ProcessResource, logRecordBatch); - try { + request.AddBatch(this.ProcessResource, logRecordBatch); + if (!this.exportClient.SendExportRequest(request)) { return ExportResult.Failure; diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporter.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporter.cs index 2cb2aae876d..7983c3da069 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporter.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporter.cs @@ -69,10 +69,10 @@ public override ExportResult Export(in Batch metrics) var request = new OtlpCollector.ExportMetricsServiceRequest(); - request.AddMetrics(this.ProcessResource, metrics); - try { + request.AddMetrics(this.ProcessResource, metrics); + if (!this.exportClient.SendExportRequest(request)) { return ExportResult.Failure; diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs index fc0956d0ad5..118c1e89808 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs @@ -25,13 +25,46 @@ namespace OpenTelemetry.Metrics /// public static class OtlpMetricExporterExtensions { + /// + /// Adds to the using default options. + /// + /// builder to use. + /// The instance of to chain the calls. + public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder) + { + return AddOtlpExporter(builder, options => { }); + } + /// /// Adds to the . /// /// builder to use. - /// Exporter configuration options. + /// Exporter configuration options. /// The instance of to chain the calls. - public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder, Action configure = null) + public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder, Action configureExporter) + { + Guard.ThrowIfNull(builder); + + if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) + { + return deferredMeterProviderBuilder.Configure((sp, builder) => + { + AddOtlpExporter(builder, sp.GetOptions(), sp.GetOptions(), configureExporter, null, sp); + }); + } + + return AddOtlpExporter(builder, new OtlpExporterOptions(), new MetricReaderOptions(), configureExporter, null, serviceProvider: null); + } + + /// + /// Adds to the . + /// + /// builder to use. + /// Exporter and configuration options. + /// The instance of to chain the calls. + public static MeterProviderBuilder AddOtlpExporter( + this MeterProviderBuilder builder, + Action configureExporterAndMetricReader) { Guard.ThrowIfNull(builder, nameof(builder)); @@ -39,34 +72,46 @@ public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder bui { return deferredMeterProviderBuilder.Configure((sp, builder) => { - AddOtlpExporter(builder, sp.GetOptions(), configure, sp); + AddOtlpExporter(builder, sp.GetOptions(), sp.GetOptions(), null, configureExporterAndMetricReader, sp); }); } - return AddOtlpExporter(builder, new OtlpExporterOptions(), configure, serviceProvider: null); + return AddOtlpExporter(builder, new OtlpExporterOptions(), new MetricReaderOptions(), null, configureExporterAndMetricReader, serviceProvider: null); } private static MeterProviderBuilder AddOtlpExporter( MeterProviderBuilder builder, - OtlpExporterOptions options, - Action configure, + OtlpExporterOptions exporterOptions, + MetricReaderOptions metricReaderOptions, + Action configureExporter, + Action configureExporterAndMetricReader, IServiceProvider serviceProvider) { - var initialEndpoint = options.Endpoint; + if (configureExporterAndMetricReader != null) + { + configureExporterAndMetricReader.Invoke(exporterOptions, metricReaderOptions); + } + else + { + configureExporter?.Invoke(exporterOptions); + } - configure?.Invoke(options); + exporterOptions.TryEnableIHttpClientFactoryIntegration(serviceProvider, "OtlpMetricExporter"); - options.TryEnableIHttpClientFactoryIntegration(serviceProvider, "OtlpMetricExporter"); + exporterOptions.AppendExportPath(OtlpExporterOptions.MetricsExportPath); - options.AppendExportPath(initialEndpoint, OtlpExporterOptions.MetricsExportPath); + var metricExporter = new OtlpMetricExporter(exporterOptions); - var metricExporter = new OtlpMetricExporter(options); + if (metricReaderOptions.MetricReaderType == (MetricReaderType)(-1)) + { + metricReaderOptions.MetricReaderType = MetricReaderType.Periodic; + } - var metricReader = options.MetricReaderType == MetricReaderType.Manual + var metricReader = metricReaderOptions.MetricReaderType == MetricReaderType.Manual ? new BaseExportingMetricReader(metricExporter) - : new PeriodicExportingMetricReader(metricExporter, options.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds); + : new PeriodicExportingMetricReader(metricExporter, metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds); - metricReader.Temporality = options.AggregationTemporality; + metricReader.Temporality = metricReaderOptions.Temporality; return builder.AddReader(metricReader); } } diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporter.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporter.cs index 1a846dd6575..71f19db313a 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporter.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporter.cs @@ -69,10 +69,10 @@ public override ExportResult Export(in Batch activityBatch) var request = new OtlpCollector.ExportTraceServiceRequest(); - request.AddBatch(this.ProcessResource, activityBatch); - try { + request.AddBatch(this.ProcessResource, activityBatch); + if (!this.exportClient.SendExportRequest(request)) { return ExportResult.Failure; @@ -81,7 +81,6 @@ public override ExportResult Export(in Batch activityBatch) catch (Exception ex) { OpenTelemetryProtocolExporterEventSource.Log.ExportMethodException(ex); - return ExportResult.Failure; } finally diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs index d9e66316919..1fbce2de2c5 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs @@ -33,7 +33,7 @@ public static class OtlpTraceExporterHelperExtensions /// The instance of to chain the calls. public static TracerProviderBuilder AddOtlpExporter(this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { @@ -52,13 +52,11 @@ private static TracerProviderBuilder AddOtlpExporter( Action configure, IServiceProvider serviceProvider) { - var originalEndpoint = exporterOptions.Endpoint; - configure?.Invoke(exporterOptions); exporterOptions.TryEnableIHttpClientFactoryIntegration(serviceProvider, "OtlpTraceExporter"); - exporterOptions.AppendExportPath(originalEndpoint, OtlpExporterOptions.TracesExportPath); + exporterOptions.AppendExportPath(OtlpExporterOptions.TracesExportPath); var otlpExporter = new OtlpTraceExporter(exporterOptions); diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md index af7a3d694b4..abc7add6d94 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md @@ -56,12 +56,12 @@ The following environment variables can be used to override the default values of the `OtlpExporterOptions` (following the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md)). -| Environment variable | `OtlpExporterOptions` property | -| ------------------------------| ----------------------------------| -| `OTEL_EXPORTER_OTLP_ENDPOINT` | `Endpoint` | -| `OTEL_EXPORTER_OTLP_HEADERS` | `Headers` | -| `OTEL_EXPORTER_OTLP_TIMEOUT` | `TimeoutMilliseconds` | -| `OTEL_EXPORTER_OTLP_PROTOCOL` | `Protocol` (grpc or http/protobuf)| +| Environment variable | `OtlpExporterOptions` property | +| ------------------------------| --------------------------------------| +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `Endpoint` | +| `OTEL_EXPORTER_OTLP_HEADERS` | `Headers` | +| `OTEL_EXPORTER_OTLP_TIMEOUT` | `TimeoutMilliseconds` | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | `Protocol` (`grpc` or `http/protobuf`)| `FormatException` is thrown in case of an invalid value for any of the supported environment variables. diff --git a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterHttpServer.cs b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterHttpServer.cs index eada5dc0164..176e968a187 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterHttpServer.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterHttpServer.cs @@ -40,7 +40,7 @@ internal sealed class PrometheusExporterHttpServer : IDisposable /// The instance. public PrometheusExporterHttpServer(PrometheusExporter exporter) { - Guard.ThrowIfNull(exporter, nameof(exporter)); + Guard.ThrowIfNull(exporter); this.exporter = exporter; if ((exporter.Options.HttpListenerPrefixes?.Count ?? 0) <= 0) diff --git a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMiddleware.cs b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMiddleware.cs index b76342ca501..b29fe33a33b 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMiddleware.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMiddleware.cs @@ -38,7 +38,7 @@ internal sealed class PrometheusExporterMiddleware /// . public PrometheusExporterMiddleware(MeterProvider meterProvider, RequestDelegate next) { - Guard.ThrowIfNull(meterProvider, nameof(meterProvider)); + Guard.ThrowIfNull(meterProvider); if (!meterProvider.TryFindExporter(out PrometheusExporter exporter)) { diff --git a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporter.cs b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporter.cs index 9470b31e67a..e49c5d16831 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporter.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporter.cs @@ -29,7 +29,6 @@ public class PrometheusExporter : BaseExporter, IPullMetricExporter { internal const string HttpListenerStartFailureExceptionMessage = "PrometheusExporter http listener could not be started."; internal readonly PrometheusExporterOptions Options; - internal Batch Metrics; // TODO: this is no longer needed, we can remove it later private readonly PrometheusExporterHttpServer metricsHttpServer; private Func funcCollect; private Func, ExportResult> funcExport; diff --git a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs index a7d5da46285..6d42926589a 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs @@ -30,7 +30,7 @@ public static class PrometheusExporterMeterProviderBuilderExtensions /// The instance of to chain the calls. public static MeterProviderBuilder AddPrometheusExporter(this MeterProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterOptions.cs b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterOptions.cs index 758c22f5106..4039e5863e4 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterOptions.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterOptions.cs @@ -54,7 +54,7 @@ public IReadOnlyCollection HttpListenerPrefixes get => this.httpListenerPrefixes; set { - Guard.ThrowIfNull(value, nameof(this.httpListenerPrefixes)); + Guard.ThrowIfNull(value); foreach (string inputUri in value) { @@ -87,7 +87,7 @@ public int ScrapeResponseCacheDurationMilliseconds get => this.scrapeResponseCacheDurationMilliseconds; set { - Guard.ThrowIfOutOfRange(value, nameof(value), min: 0); + Guard.ThrowIfOutOfRange(value, min: 0); this.scrapeResponseCacheDurationMilliseconds = value; } diff --git a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs index c02e5905731..973e966b8ec 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs @@ -37,7 +37,7 @@ public class ZPagesExporter : BaseExporter /// Options for the exporter. public ZPagesExporter(ZPagesExporterOptions options) { - Guard.ThrowIfNull(options?.RetentionTime, $"{nameof(options)}?.{nameof(options.RetentionTime)}"); + Guard.ThrowIfNull(options?.RetentionTime); ZPagesActivityTracker.RetentionTime = options.RetentionTime; diff --git a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs index 7dd316a5c4c..26eba5968ee 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs @@ -37,7 +37,7 @@ public static TracerProviderBuilder AddZPagesExporter( this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var exporterOptions = new ZPagesExporterOptions(); configure?.Invoke(exporterOptions); diff --git a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs index 906d81674c2..cce9aa58ea3 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs @@ -42,7 +42,7 @@ public class ZPagesExporterStatsHttpServer : IDisposable /// The instance. public ZPagesExporterStatsHttpServer(ZPagesExporter exporter) { - Guard.ThrowIfNull(exporter?.Options?.Url, $"{nameof(exporter)}?.{nameof(exporter.Options)}?.{nameof(exporter.Options.Url)}"); + Guard.ThrowIfNull(exporter?.Options?.Url); this.httpListener.Prefixes.Add(exporter.Options.Url); } diff --git a/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs b/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs index a555a90587e..1ee3b7cf236 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs @@ -41,8 +41,8 @@ public ZipkinSpan( bool? debug, bool? shared) { - Guard.ThrowIfNullOrWhitespace(traceId, nameof(traceId)); - Guard.ThrowIfNullOrWhitespace(id, nameof(id)); + Guard.ThrowIfNullOrWhitespace(traceId); + Guard.ThrowIfNullOrWhitespace(id); this.TraceId = traceId; this.ParentId = parentId; diff --git a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs index 899147ac9c8..646c13808bd 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs @@ -48,7 +48,7 @@ public class ZipkinExporter : BaseExporter /// Http client to use to upload telemetry. public ZipkinExporter(ZipkinExporterOptions options, HttpClient client = null) { - Guard.ThrowIfNull(options, nameof(options)); + Guard.ThrowIfNull(options); this.options = options; this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0) ? ZipkinExporterOptions.DefaultMaxPayloadSizeInBytes : options.MaxPayloadSizeInBytes.Value; diff --git a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs index ce57441e182..ee276e02e31 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs @@ -36,7 +36,7 @@ public static class ZipkinExporterHelperExtensions [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] public static TracerProviderBuilder AddZipkinExporter(this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Extensions.Hosting/CHANGELOG.md b/src/OpenTelemetry.Extensions.Hosting/CHANGELOG.md index 7431f10d428..a65a5cd7812 100644 --- a/src/OpenTelemetry.Extensions.Hosting/CHANGELOG.md +++ b/src/OpenTelemetry.Extensions.Hosting/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +* Fixes an issue where the initialization of some aspects of the SDK can be + delayed when using the `AddOpenTelemetryTracing` and + `AddOpenTelemetryMetrics` methods. Namely, self-diagnostics and the default + context propagator responsible for propagating trace context and baggage. + ([#2901](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2901)) + ## 1.0.0-rc9 Released 2022-Feb-02 diff --git a/src/OpenTelemetry.Extensions.Hosting/Implementation/MeterProviderBuilderHosting.cs b/src/OpenTelemetry.Extensions.Hosting/Implementation/MeterProviderBuilderHosting.cs index 4ee28ab5aac..6a9fba91ea9 100644 --- a/src/OpenTelemetry.Extensions.Hosting/Implementation/MeterProviderBuilderHosting.cs +++ b/src/OpenTelemetry.Extensions.Hosting/Implementation/MeterProviderBuilderHosting.cs @@ -30,7 +30,7 @@ internal sealed class MeterProviderBuilderHosting : MeterProviderBuilderBase, ID public MeterProviderBuilderHosting(IServiceCollection services) { - Guard.ThrowIfNull(services, nameof(services)); + Guard.ThrowIfNull(services); this.Services = services; } @@ -39,7 +39,7 @@ public MeterProviderBuilderHosting(IServiceCollection services) public MeterProviderBuilder Configure(Action configure) { - Guard.ThrowIfNull(configure, nameof(configure)); + Guard.ThrowIfNull(configure); this.configurationActions.Add(configure); return this; @@ -47,7 +47,7 @@ public MeterProviderBuilder Configure(Action configure) { - Guard.ThrowIfNull(configure, nameof(configure)); + Guard.ThrowIfNull(configure); this.configurationActions.Add(configure); return this; @@ -47,7 +47,7 @@ public TracerProviderBuilder Configure(ActionThe so that additional calls can be chained. public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Action configure) { - Guard.ThrowIfNull(configure, nameof(configure)); + Guard.ThrowIfNull(configure); var builder = new TracerProviderBuilderHosting(services); configure(builder); @@ -73,7 +74,7 @@ public static IServiceCollection AddOpenTelemetryMetrics(this IServiceCollection /// The so that additional calls can be chained. public static IServiceCollection AddOpenTelemetryMetrics(this IServiceCollection services, Action configure) { - Guard.ThrowIfNull(configure, nameof(configure)); + Guard.ThrowIfNull(configure); var builder = new MeterProviderBuilderHosting(services); configure(builder); @@ -88,8 +89,12 @@ public static IServiceCollection AddOpenTelemetryMetrics(this IServiceCollection /// The so that additional calls can be chained. private static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Func createTracerProvider) { - Guard.ThrowIfNull(services, nameof(services)); - Guard.ThrowIfNull(createTracerProvider, nameof(createTracerProvider)); + Guard.ThrowIfNull(services); + Guard.ThrowIfNull(createTracerProvider); + + // Accessing Sdk class is just to trigger its static ctor, + // which sets default Propagators and default Activity Id format + _ = Sdk.SuppressInstrumentation; try { @@ -115,6 +120,10 @@ private static IServiceCollection AddOpenTelemetryMetrics(this IServiceCollectio Debug.Assert(services != null, $"{nameof(services)} must not be null"); Debug.Assert(createMeterProvider != null, $"{nameof(createMeterProvider)} must not be null"); + // Accessing Sdk class is just to trigger its static ctor, + // which sets default Propagators and default Activity Id format + _ = Sdk.SuppressInstrumentation; + try { services.TryAddEnumerable(ServiceDescriptor.Singleton()); diff --git a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs index 258ac86de74..2d0e42efb01 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs @@ -42,7 +42,7 @@ public TextMapPropagator TextMapPropagator get => this.textMapPropagator; set { - Guard.ThrowIfNull(value, nameof(value)); + Guard.ThrowIfNull(value); this.textMapPropagator = value; } diff --git a/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md b/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md index 72b1c64778a..53604964ab5 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md +++ b/src/OpenTelemetry.Instrumentation.AspNet/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +* Fix: Http server span status is now unset for `400`-`499`. + ([#2904](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2904)) + ## Unreleased ## 1.0.0-rc9 diff --git a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs index 8bb28b9b45f..946de293ebf 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs @@ -26,13 +26,13 @@ namespace OpenTelemetry.Instrumentation.AspNet.Implementation { internal sealed class HttpInListener : IDisposable { - private readonly PropertyFetcher routeFetcher = new PropertyFetcher("Route"); - private readonly PropertyFetcher routeTemplateFetcher = new PropertyFetcher("RouteTemplate"); + private readonly PropertyFetcher routeFetcher = new("Route"); + private readonly PropertyFetcher routeTemplateFetcher = new("RouteTemplate"); private readonly AspNetInstrumentationOptions options; public HttpInListener(AspNetInstrumentationOptions options) { - Guard.ThrowIfNull(options, nameof(options)); + Guard.ThrowIfNull(options); this.options = options; @@ -57,12 +57,7 @@ public void Dispose() /// Span uri value. private static string GetUriTagValueFromRequestUri(Uri uri) { - if (string.IsNullOrEmpty(uri.UserInfo)) - { - return uri.ToString(); - } - - return string.Concat(uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.PathAndQuery, uri.Fragment); + return string.IsNullOrEmpty(uri.UserInfo) ? uri.ToString() : string.Concat(uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.PathAndQuery, uri.Fragment); } private void OnStartActivity(Activity activity, HttpContext context) @@ -135,7 +130,7 @@ private void OnStopActivity(Activity activity, HttpContext context) if (activity.GetStatus().StatusCode == StatusCode.Unset) { - activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(response.StatusCode)); + activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, response.StatusCode)); } var routeData = context.Request.RequestContext.RouteData; diff --git a/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs index 39f41ef969e..b58aeb83b88 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs @@ -35,7 +35,7 @@ public static TracerProviderBuilder AddAspNetInstrumentation( this TracerProviderBuilder builder, Action configureAspNetInstrumentationOptions = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var aspnetOptions = new AspNetInstrumentationOptions(); configureAspNetInstrumentationOptions?.Invoke(aspnetOptions); diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md b/src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md index 5fc15547ce5..d9862a25787 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +* Fix: Http server span status is now unset for `400`-`499`. + ([#2904](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2904)) + ## Unreleased ## 1.0.0-rc9 diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs index eb25f895cce..07606645a8f 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs @@ -43,18 +43,18 @@ internal class HttpInListener : ListenerHandler private const string DiagnosticSourceName = "Microsoft.AspNetCore"; private const string UnknownHostName = "UNKNOWN-HOST"; private static readonly Func> HttpRequestHeaderValuesGetter = (request, name) => request.Headers[name]; - private readonly PropertyFetcher startContextFetcher = new PropertyFetcher("HttpContext"); - private readonly PropertyFetcher stopContextFetcher = new PropertyFetcher("HttpContext"); - private readonly PropertyFetcher stopExceptionFetcher = new PropertyFetcher("Exception"); - private readonly PropertyFetcher beforeActionActionDescriptorFetcher = new PropertyFetcher("actionDescriptor"); - private readonly PropertyFetcher beforeActionAttributeRouteInfoFetcher = new PropertyFetcher("AttributeRouteInfo"); - private readonly PropertyFetcher beforeActionTemplateFetcher = new PropertyFetcher("Template"); + private readonly PropertyFetcher startContextFetcher = new("HttpContext"); + private readonly PropertyFetcher stopContextFetcher = new("HttpContext"); + private readonly PropertyFetcher stopExceptionFetcher = new("Exception"); + private readonly PropertyFetcher beforeActionActionDescriptorFetcher = new("actionDescriptor"); + private readonly PropertyFetcher beforeActionAttributeRouteInfoFetcher = new("AttributeRouteInfo"); + private readonly PropertyFetcher beforeActionTemplateFetcher = new("Template"); private readonly AspNetCoreInstrumentationOptions options; public HttpInListener(AspNetCoreInstrumentationOptions options) : base(DiagnosticSourceName) { - Guard.ThrowIfNull(options, nameof(options)); + Guard.ThrowIfNull(options); this.options = options; } @@ -87,7 +87,7 @@ public override void OnStartActivity(Activity activity, object payload) // Ensure context extraction irrespective of sampling decision var request = context.Request; var textMapPropagator = Propagators.DefaultTextMapPropagator; - if (!(textMapPropagator is TraceContextPropagator)) + if (textMapPropagator is not TraceContextPropagator) { var ctx = textMapPropagator.Extract(default, request, HttpRequestHeaderValuesGetter); @@ -144,7 +144,7 @@ public override void OnStartActivity(Activity activity, object payload) // see the spec https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md - if (request.Host.Port == null || request.Host.Port == 80 || request.Host.Port == 443) + if (request.Host.Port is null or 80 or 443) { activity.SetTag(SemanticConventions.AttributeHttpHost, request.Host.Host); } @@ -196,12 +196,12 @@ public override void OnStopActivity(Activity activity, object payload) } else if (activity.GetStatus().StatusCode == StatusCode.Unset) { - activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(response.StatusCode)); + activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, response.StatusCode)); } #else if (activity.GetStatus().StatusCode == StatusCode.Unset) { - activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(response.StatusCode)); + activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, response.StatusCode)); } #endif @@ -235,7 +235,7 @@ public override void OnStopActivity(Activity activity, object payload) } var textMapPropagator = Propagators.DefaultTextMapPropagator; - if (!(textMapPropagator is TraceContextPropagator)) + if (textMapPropagator is not TraceContextPropagator) { Baggage.Current = default; } diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs index 50ed827437d..8679638c559 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs @@ -32,7 +32,7 @@ public static class MeterProviderBuilderExtensions public static MeterProviderBuilder AddAspNetCoreInstrumentation( this MeterProviderBuilder builder) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); // TODO: Implement an IDeferredMeterProviderBuilder diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs index 1df5ec14ac2..8ff58d22c73 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs @@ -36,7 +36,7 @@ public static TracerProviderBuilder AddAspNetCoreInstrumentation( this TracerProviderBuilder builder, Action configureAspNetCoreInstrumentationOptions = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs index 9c4580a39ad..33c51475ca8 100644 --- a/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs @@ -37,7 +37,7 @@ public static TracerProviderBuilder AddGrpcClientInstrumentation( this TracerProviderBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var grpcOptions = new GrpcClientInstrumentationOptions(); configure?.Invoke(grpcOptions); diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 6168796f28a..a6d4d8b26eb 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -183,7 +183,7 @@ public override void OnStopActivity(Activity activity, object payload) if (currentStatusCode == StatusCode.Unset) { - activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode((int)response.StatusCode)); + activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode)); } try diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index b4e6d545cad..17427bf10c3 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -122,7 +122,7 @@ private static void AddResponseTags(HttpWebResponse response, Activity activity) { activity.SetTag(SemanticConventions.AttributeHttpStatusCode, (int)response.StatusCode); - activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode((int)response.StatusCode)); + activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode)); try { @@ -150,7 +150,7 @@ private static void AddExceptionTags(Exception exception, Activity activity) { activity.SetTag(SemanticConventions.AttributeHttpStatusCode, (int)response.StatusCode); - status = SpanHelper.ResolveSpanStatusForHttpStatusCode((int)response.StatusCode); + status = SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode); } else { diff --git a/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs index e92ad676897..3057108d90d 100644 --- a/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs @@ -32,7 +32,7 @@ public static class MeterProviderBuilderExtensions public static MeterProviderBuilder AddHttpClientInstrumentation( this MeterProviderBuilder builder) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); // TODO: Implement an IDeferredMeterProviderBuilder diff --git a/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs index feef1d353de..073fde0eac2 100644 --- a/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs @@ -61,7 +61,7 @@ public static TracerProviderBuilder AddHttpClientInstrumentation( this TracerProviderBuilder builder, Action configureHttpClientInstrumentationOptions = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var httpClientOptions = new HttpClientInstrumentationOptions(); diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs index de11906f615..a12ae44c884 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs @@ -36,7 +36,7 @@ public static TracerProviderBuilder AddSqlClientInstrumentation( this TracerProviderBuilder builder, Action configureSqlClientInstrumentationOptions = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); var sqlOptions = new SqlClientInstrumentationOptions(); configureSqlClientInstrumentationOptions?.Invoke(sqlOptions); diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs index 81c2e790d6d..819e79b343a 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs @@ -59,7 +59,7 @@ internal class StackExchangeRedisCallsInstrumentation : IDisposable /// Configuration options for redis instrumentation. public StackExchangeRedisCallsInstrumentation(IConnectionMultiplexer connection, StackExchangeRedisCallsInstrumentationOptions options) { - Guard.ThrowIfNull(connection, nameof(connection)); + Guard.ThrowIfNull(connection); this.options = options ?? new StackExchangeRedisCallsInstrumentationOptions(); diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs index 7814ed11671..e9aade22702 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs @@ -43,7 +43,7 @@ public static TracerProviderBuilder AddRedisInstrumentation( IConnectionMultiplexer connection = null, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); if (builder is not IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs b/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs index e184fc69c66..8c9062c4c6c 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs @@ -37,7 +37,7 @@ internal sealed class ScopeManagerShim : IScopeManager public ScopeManagerShim(Tracer tracer) { - Guard.ThrowIfNull(tracer, nameof(tracer)); + Guard.ThrowIfNull(tracer); this.tracer = tracer; } @@ -69,7 +69,7 @@ public IScope Active /// public IScope Activate(ISpan span, bool finishSpanOnDispose) { - var shim = Guard.ThrowIfNotOfType(span, nameof(span)); + var shim = Guard.ThrowIfNotOfType(span); var scope = Tracer.WithSpan(shim.Span); diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs index 6a27eefe635..683165a089b 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs @@ -81,8 +81,8 @@ internal sealed class SpanBuilderShim : ISpanBuilder public SpanBuilderShim(Tracer tracer, string spanName, IList rootOperationNamesForActivityBasedAutoInstrumentations = null) { - Guard.ThrowIfNull(tracer, nameof(tracer)); - Guard.ThrowIfNull(spanName, nameof(spanName)); + Guard.ThrowIfNull(tracer); + Guard.ThrowIfNull(spanName); this.tracer = tracer; this.spanName = spanName; @@ -130,7 +130,7 @@ public ISpanBuilder AddReference(string referenceType, ISpanContext referencedCo return this; } - Guard.ThrowIfNull(referenceType, nameof(referenceType)); + Guard.ThrowIfNull(referenceType); // TODO There is no relation between OpenTracing.References (referenceType) and OpenTelemetry Link var actualContext = GetOpenTelemetrySpanContext(referencedContext); @@ -279,7 +279,7 @@ public ISpanBuilder WithTag(string key, double value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.BooleanTag tag, bool value) { - Guard.ThrowIfNull(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); + Guard.ThrowIfNull(tag?.Key); return this.WithTag(tag.Key, value); } @@ -287,7 +287,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.BooleanTag tag, bool value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.IntOrStringTag tag, string value) { - Guard.ThrowIfNull(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); + Guard.ThrowIfNull(tag?.Key); if (int.TryParse(value, out var result)) { @@ -300,7 +300,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.IntOrStringTag tag, string v /// public ISpanBuilder WithTag(global::OpenTracing.Tag.IntTag tag, int value) { - Guard.ThrowIfNull(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); + Guard.ThrowIfNull(tag?.Key); return this.WithTag(tag.Key, value); } @@ -308,7 +308,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.IntTag tag, int value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.StringTag tag, string value) { - Guard.ThrowIfNull(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); + Guard.ThrowIfNull(tag?.Key); return this.WithTag(tag.Key, value); } @@ -321,7 +321,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.StringTag tag, string value) /// span is not a valid SpanShim object. private static TelemetrySpan GetOpenTelemetrySpan(ISpan span) { - var shim = Guard.ThrowIfNotOfType(span, nameof(span)); + var shim = Guard.ThrowIfNotOfType(span); return shim.Span; } @@ -334,7 +334,7 @@ private static TelemetrySpan GetOpenTelemetrySpan(ISpan span) /// context is not a valid SpanContextShim object. private static SpanContext GetOpenTelemetrySpanContext(ISpanContext spanContext) { - var shim = Guard.ThrowIfNotOfType(spanContext, nameof(spanContext)); + var shim = Guard.ThrowIfNotOfType(spanContext); return shim.SpanContext; } diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs index 56aa2738d01..0ce964a3302 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs @@ -46,7 +46,7 @@ internal sealed class SpanShim : ISpan public SpanShim(TelemetrySpan span) { - Guard.ThrowIfNull(span, nameof(span)); + Guard.ThrowIfNull(span); if (!span.Context.IsValid) { @@ -80,7 +80,7 @@ public string GetBaggageItem(string key) /// public ISpan Log(DateTimeOffset timestamp, IEnumerable> fields) { - Guard.ThrowIfNull(fields, nameof(fields)); + Guard.ThrowIfNull(fields); var payload = ConvertToEventPayload(fields); var eventName = payload.Item1; @@ -141,7 +141,7 @@ public ISpan Log(IEnumerable> fields) /// public ISpan Log(string @event) { - Guard.ThrowIfNull(@event, nameof(@event)); + Guard.ThrowIfNull(@event); this.Span.AddEvent(@event); return this; @@ -150,7 +150,7 @@ public ISpan Log(string @event) /// public ISpan Log(DateTimeOffset timestamp, string @event) { - Guard.ThrowIfNull(@event, nameof(@event)); + Guard.ThrowIfNull(@event); this.Span.AddEvent(@event, timestamp); return this; @@ -166,7 +166,7 @@ public ISpan SetBaggageItem(string key, string value) /// public ISpan SetOperationName(string operationName) { - Guard.ThrowIfNull(operationName, nameof(operationName)); + Guard.ThrowIfNull(operationName); this.Span.UpdateName(operationName); return this; @@ -175,7 +175,7 @@ public ISpan SetOperationName(string operationName) /// public ISpan SetTag(string key, string value) { - Guard.ThrowIfNull(key, nameof(key)); + Guard.ThrowIfNull(key); this.Span.SetAttribute(key, value); return this; @@ -184,7 +184,7 @@ public ISpan SetTag(string key, string value) /// public ISpan SetTag(string key, bool value) { - Guard.ThrowIfNull(key, nameof(key)); + Guard.ThrowIfNull(key); // Special case the OpenTracing Error Tag // see https://opentracing.io/specification/conventions/ @@ -203,7 +203,7 @@ public ISpan SetTag(string key, bool value) /// public ISpan SetTag(string key, int value) { - Guard.ThrowIfNull(key, nameof(key)); + Guard.ThrowIfNull(key); this.Span.SetAttribute(key, value); return this; @@ -212,7 +212,7 @@ public ISpan SetTag(string key, int value) /// public ISpan SetTag(string key, double value) { - Guard.ThrowIfNull(key, nameof(key)); + Guard.ThrowIfNull(key); this.Span.SetAttribute(key, value); return this; diff --git a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs index c702c1252d5..906d78315f8 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs @@ -28,8 +28,8 @@ public class TracerShim : global::OpenTracing.ITracer public TracerShim(Trace.Tracer tracer, TextMapPropagator textFormat) { - Guard.ThrowIfNull(tracer, nameof(tracer)); - Guard.ThrowIfNull(textFormat, nameof(textFormat)); + Guard.ThrowIfNull(tracer); + Guard.ThrowIfNull(textFormat); this.tracer = tracer; this.propagator = textFormat; @@ -51,8 +51,8 @@ public TracerShim(Trace.Tracer tracer, TextMapPropagator textFormat) /// public global::OpenTracing.ISpanContext Extract(IFormat format, TCarrier carrier) { - Guard.ThrowIfNull(format, nameof(format)); - Guard.ThrowIfNull(carrier, nameof(carrier)); + Guard.ThrowIfNull(format); + Guard.ThrowIfNull(carrier); PropagationContext propagationContext = default; @@ -92,10 +92,10 @@ public void Inject( IFormat format, TCarrier carrier) { - Guard.ThrowIfNull(spanContext, nameof(spanContext)); - var shim = Guard.ThrowIfNotOfType(spanContext, nameof(spanContext)); - Guard.ThrowIfNull(format, nameof(format)); - Guard.ThrowIfNull(carrier, nameof(carrier)); + Guard.ThrowIfNull(spanContext); + var shim = Guard.ThrowIfNotOfType(spanContext); + Guard.ThrowIfNull(format); + Guard.ThrowIfNull(carrier); if ((format == BuiltinFormats.TextMap || format == BuiltinFormats.HttpHeaders) && carrier is ITextMap textMapCarrier) { diff --git a/src/OpenTelemetry/.publicApi/net461/PublicAPI.Unshipped.txt b/src/OpenTelemetry/.publicApi/net461/PublicAPI.Unshipped.txt index 79e52486ff0..bee50adc683 100644 --- a/src/OpenTelemetry/.publicApi/net461/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry/.publicApi/net461/PublicAPI.Unshipped.txt @@ -1,6 +1,14 @@ OpenTelemetry.BaseExporter.ForceFlush(int timeoutMilliseconds = -1) -> bool OpenTelemetry.Batch.Batch(T[] items, int count) -> void OpenTelemetry.Batch.Count.get -> long +OpenTelemetry.Metrics.MetricReaderOptions +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderOptions() -> void +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderType.set -> void +OpenTelemetry.Metrics.MetricReaderOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions +OpenTelemetry.Metrics.MetricReaderOptions.PeriodicExportingMetricReaderOptions.set -> void +OpenTelemetry.Metrics.MetricReaderOptions.Temporality.get -> OpenTelemetry.Metrics.AggregationTemporality +OpenTelemetry.Metrics.MetricReaderOptions.Temporality.set -> void OpenTelemetry.Metrics.AggregationTemporality OpenTelemetry.Metrics.AggregationTemporality.Cumulative = 1 -> OpenTelemetry.Metrics.AggregationTemporality OpenTelemetry.Metrics.AggregationTemporality.Delta = 2 -> OpenTelemetry.Metrics.AggregationTemporality @@ -104,6 +112,8 @@ OpenTelemetry.ReadOnlyTagCollection.Enumerator.Enumerator() -> void OpenTelemetry.ReadOnlyTagCollection.Enumerator.MoveNext() -> bool OpenTelemetry.ReadOnlyTagCollection.GetEnumerator() -> OpenTelemetry.ReadOnlyTagCollection.Enumerator OpenTelemetry.ReadOnlyTagCollection.ReadOnlyTagCollection() -> void +OpenTelemetry.Resources.IResourceDetector +OpenTelemetry.Resources.IResourceDetector.Detect() -> OpenTelemetry.Resources.Resource OpenTelemetry.Trace.BatchExportActivityProcessorOptions OpenTelemetry.Trace.BatchExportActivityProcessorOptions.BatchExportActivityProcessorOptions() -> void override OpenTelemetry.BaseExportProcessor.OnForceFlush(int timeoutMilliseconds) -> bool diff --git a/src/OpenTelemetry/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt index 79e52486ff0..bee50adc683 100644 --- a/src/OpenTelemetry/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry/.publicApi/netstandard2.0/PublicAPI.Unshipped.txt @@ -1,6 +1,14 @@ OpenTelemetry.BaseExporter.ForceFlush(int timeoutMilliseconds = -1) -> bool OpenTelemetry.Batch.Batch(T[] items, int count) -> void OpenTelemetry.Batch.Count.get -> long +OpenTelemetry.Metrics.MetricReaderOptions +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderOptions() -> void +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderType.get -> OpenTelemetry.Metrics.MetricReaderType +OpenTelemetry.Metrics.MetricReaderOptions.MetricReaderType.set -> void +OpenTelemetry.Metrics.MetricReaderOptions.PeriodicExportingMetricReaderOptions.get -> OpenTelemetry.Metrics.PeriodicExportingMetricReaderOptions +OpenTelemetry.Metrics.MetricReaderOptions.PeriodicExportingMetricReaderOptions.set -> void +OpenTelemetry.Metrics.MetricReaderOptions.Temporality.get -> OpenTelemetry.Metrics.AggregationTemporality +OpenTelemetry.Metrics.MetricReaderOptions.Temporality.set -> void OpenTelemetry.Metrics.AggregationTemporality OpenTelemetry.Metrics.AggregationTemporality.Cumulative = 1 -> OpenTelemetry.Metrics.AggregationTemporality OpenTelemetry.Metrics.AggregationTemporality.Delta = 2 -> OpenTelemetry.Metrics.AggregationTemporality @@ -104,6 +112,8 @@ OpenTelemetry.ReadOnlyTagCollection.Enumerator.Enumerator() -> void OpenTelemetry.ReadOnlyTagCollection.Enumerator.MoveNext() -> bool OpenTelemetry.ReadOnlyTagCollection.GetEnumerator() -> OpenTelemetry.ReadOnlyTagCollection.Enumerator OpenTelemetry.ReadOnlyTagCollection.ReadOnlyTagCollection() -> void +OpenTelemetry.Resources.IResourceDetector +OpenTelemetry.Resources.IResourceDetector.Detect() -> OpenTelemetry.Resources.Resource OpenTelemetry.Trace.BatchExportActivityProcessorOptions OpenTelemetry.Trace.BatchExportActivityProcessorOptions.BatchExportActivityProcessorOptions() -> void override OpenTelemetry.BaseExportProcessor.OnForceFlush(int timeoutMilliseconds) -> bool diff --git a/src/OpenTelemetry/BaseExportProcessor.cs b/src/OpenTelemetry/BaseExportProcessor.cs index de8678524f0..4bddbeff445 100644 --- a/src/OpenTelemetry/BaseExportProcessor.cs +++ b/src/OpenTelemetry/BaseExportProcessor.cs @@ -19,6 +19,26 @@ namespace OpenTelemetry { + /// + /// Type of Export Processor to be used. + /// + public enum ExportProcessorType + { + /// + /// Use SimpleExportProcessor. + /// Refer to the + /// specification for more information. + /// + Simple, + + /// + /// Use BatchExportProcessor. + /// Refer to + /// specification for more information. + /// + Batch, + } + /// /// Implements processor that exports telemetry objects. /// @@ -35,7 +55,7 @@ public abstract class BaseExportProcessor : BaseProcessor /// Exporter instance. protected BaseExportProcessor(BaseExporter exporter) { - Guard.ThrowIfNull(exporter, nameof(exporter)); + Guard.ThrowIfNull(exporter); this.exporter = exporter; } diff --git a/src/OpenTelemetry/BaseExporter.cs b/src/OpenTelemetry/BaseExporter.cs index cb83c28ac93..f188b07282c 100644 --- a/src/OpenTelemetry/BaseExporter.cs +++ b/src/OpenTelemetry/BaseExporter.cs @@ -76,7 +76,7 @@ public abstract class BaseExporter : IDisposable /// public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); try { @@ -109,7 +109,7 @@ public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (Interlocked.Increment(ref this.shutdownCount) > 1) { diff --git a/src/OpenTelemetry/BaseProcessor.cs b/src/OpenTelemetry/BaseProcessor.cs index bf7ba828acf..4115b108ee6 100644 --- a/src/OpenTelemetry/BaseProcessor.cs +++ b/src/OpenTelemetry/BaseProcessor.cs @@ -82,7 +82,7 @@ public virtual void OnEnd(T data) /// public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); try { @@ -115,7 +115,7 @@ public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (Interlocked.CompareExchange(ref this.shutdownCount, 1, 0) != 0) { diff --git a/src/OpenTelemetry/Batch.cs b/src/OpenTelemetry/Batch.cs index a77e5c973c5..df54bb81131 100644 --- a/src/OpenTelemetry/Batch.cs +++ b/src/OpenTelemetry/Batch.cs @@ -41,8 +41,8 @@ namespace OpenTelemetry /// The number of items in the batch. public Batch(T[] items, int count) { - Guard.ThrowIfNull(items, nameof(items)); - Guard.ThrowIfOutOfRange(count, nameof(count), 0, items.Length); + Guard.ThrowIfNull(items); + Guard.ThrowIfOutOfRange(count, min: 0, max: items.Length); this.item = null; this.circularBuffer = null; diff --git a/src/OpenTelemetry/BatchExportProcessor.cs b/src/OpenTelemetry/BatchExportProcessor.cs index 6f9193225b0..276fa4de6df 100644 --- a/src/OpenTelemetry/BatchExportProcessor.cs +++ b/src/OpenTelemetry/BatchExportProcessor.cs @@ -61,10 +61,10 @@ protected BatchExportProcessor( int maxExportBatchSize = DefaultMaxExportBatchSize) : base(exporter) { - Guard.ThrowIfOutOfRange(maxQueueSize, nameof(maxQueueSize), min: 1); - Guard.ThrowIfOutOfRange(maxExportBatchSize, nameof(maxExportBatchSize), min: 1, max: maxQueueSize, maxName: nameof(maxQueueSize)); - Guard.ThrowIfOutOfRange(scheduledDelayMilliseconds, nameof(scheduledDelayMilliseconds), min: 1); - Guard.ThrowIfOutOfRange(exporterTimeoutMilliseconds, nameof(exporterTimeoutMilliseconds), min: 0); + Guard.ThrowIfOutOfRange(maxQueueSize, min: 1); + Guard.ThrowIfOutOfRange(maxExportBatchSize, min: 1, max: maxQueueSize, maxName: nameof(maxQueueSize)); + Guard.ThrowIfOutOfRange(scheduledDelayMilliseconds, min: 1); + Guard.ThrowIfOutOfRange(exporterTimeoutMilliseconds, min: 0); this.circularBuffer = new CircularBuffer(maxQueueSize); this.scheduledDelayMilliseconds = scheduledDelayMilliseconds; diff --git a/src/OpenTelemetry/CHANGELOG.md b/src/OpenTelemetry/CHANGELOG.md index 17e717053cb..4b8511ce1ed 100644 --- a/src/OpenTelemetry/CHANGELOG.md +++ b/src/OpenTelemetry/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +* Make `IResourceDetector` public to allow custom implementations of resource detectors. + ([2897](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2897)) + ## 1.2.0-rc2 Released 2022-Feb-02 diff --git a/src/OpenTelemetry/CompositeProcessor.cs b/src/OpenTelemetry/CompositeProcessor.cs index 19260b1dd6c..49c2258bd49 100644 --- a/src/OpenTelemetry/CompositeProcessor.cs +++ b/src/OpenTelemetry/CompositeProcessor.cs @@ -30,7 +30,7 @@ public class CompositeProcessor : BaseProcessor public CompositeProcessor(IEnumerable> processors) { - Guard.ThrowIfNull(processors, nameof(processors)); + Guard.ThrowIfNull(processors); using var iter = processors.GetEnumerator(); if (!iter.MoveNext()) @@ -49,7 +49,7 @@ public CompositeProcessor(IEnumerable> processors) public CompositeProcessor AddProcessor(BaseProcessor processor) { - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(processor); var node = new DoublyLinkedListNode(processor) { diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs index ad5852878d8..812fc572ced 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs @@ -27,7 +27,7 @@ internal class DiagnosticSourceListener : IObserver public DiagnosticSourceListener(ListenerHandler handler) { - Guard.ThrowIfNull(handler, nameof(handler)); + Guard.ThrowIfNull(handler); this.handler = handler; } diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs index 1e1a15dce5f..a1bc100585f 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs @@ -42,7 +42,7 @@ public DiagnosticSourceSubscriber( Func diagnosticSourceFilter, Func isEnabledFilter) { - Guard.ThrowIfNull(handlerFactory, nameof(handlerFactory)); + Guard.ThrowIfNull(handlerFactory); this.listenerSubscriptions = new List(); this.handlerFactory = handlerFactory; diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs index 1bcafb11dbf..dc0e1028fa8 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs @@ -46,7 +46,7 @@ public PropertyFetcher(string propertyName) /// Property fetched. public T Fetch(object obj) { - Guard.ThrowIfNull(obj, nameof(obj)); + Guard.ThrowIfNull(obj); if (!this.TryFetch(obj, out T value, true)) { @@ -135,10 +135,7 @@ public override bool TryFetch(object obj, out T value) return true; } - if (this.innerFetcher == null) - { - this.innerFetcher = Create(obj.GetType().GetTypeInfo(), this.propertyName); - } + this.innerFetcher ??= Create(obj.GetType().GetTypeInfo(), this.propertyName); return this.innerFetcher.TryFetch(obj, out value); } diff --git a/src/OpenTelemetry/ExportProcessorType.cs b/src/OpenTelemetry/ExportProcessorType.cs deleted file mode 100644 index a466f666e7e..00000000000 --- a/src/OpenTelemetry/ExportProcessorType.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry -{ - /// - /// Type of Export Processor to be used. - /// - public enum ExportProcessorType - { - /// - /// Use SimpleExportProcessor. - /// Refer to the - /// specification for more information. - /// - Simple, - - /// - /// Use BatchExportProcessor. - /// Refer to - /// specification for more information. - /// - Batch, - } -} diff --git a/src/OpenTelemetry/Internal/CircularBuffer.cs b/src/OpenTelemetry/Internal/CircularBuffer.cs index 8cc1f22ff2c..16614d00213 100644 --- a/src/OpenTelemetry/Internal/CircularBuffer.cs +++ b/src/OpenTelemetry/Internal/CircularBuffer.cs @@ -36,7 +36,7 @@ internal class CircularBuffer /// The capacity of the circular buffer, must be a positive integer. public CircularBuffer(int capacity) { - Guard.ThrowIfOutOfRange(capacity, nameof(capacity), min: 1); + Guard.ThrowIfOutOfRange(capacity, min: 1); this.Capacity = capacity; this.trait = new T[capacity]; @@ -79,7 +79,7 @@ public int Count /// public bool Add(T value) { - Guard.ThrowIfNull(value, nameof(value)); + Guard.ThrowIfNull(value); while (true) { @@ -119,7 +119,7 @@ public bool TryAdd(T value, int maxSpinCount) return this.Add(value); } - Guard.ThrowIfNull(value, nameof(value)); + Guard.ThrowIfNull(value); var spinCountDown = maxSpinCount; diff --git a/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs b/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs index 0061000c3f0..df3f89df0aa 100644 --- a/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs +++ b/src/OpenTelemetry/Internal/EnvironmentVariableHelper.cs @@ -78,7 +78,7 @@ public static bool LoadNumeric(string envVarKey, out int result) if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result)) { - throw new FormatException($"{envVarKey} environment variable has an invalid value: '${value}'"); + throw new FormatException($"{envVarKey} environment variable has an invalid value: '{value}'"); } return true; diff --git a/src/OpenTelemetry/Internal/PooledList.cs b/src/OpenTelemetry/Internal/PooledList.cs index 52eea3d3eb4..d00ba265796 100644 --- a/src/OpenTelemetry/Internal/PooledList.cs +++ b/src/OpenTelemetry/Internal/PooledList.cs @@ -52,7 +52,7 @@ public static PooledList Create() public static void Add(ref PooledList list, T item) { - Guard.ThrowIfNull(list.buffer, $"{nameof(list)}.{nameof(list.buffer)}"); + Guard.ThrowIfNull(list.buffer); var buffer = list.buffer; diff --git a/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs b/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs index 5581f5ee2ab..a2f701f07ff 100644 --- a/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs +++ b/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs @@ -43,7 +43,7 @@ internal class SelfDiagnosticsEventListener : EventListener public SelfDiagnosticsEventListener(EventLevel logLevel, SelfDiagnosticsConfigRefresher configRefresher) { - Guard.ThrowIfNull(configRefresher, nameof(configRefresher)); + Guard.ThrowIfNull(configRefresher); this.logLevel = logLevel; this.configRefresher = configRefresher; diff --git a/src/OpenTelemetry/BatchLogRecordExportProcessor.cs b/src/OpenTelemetry/Logs/BatchLogRecordExportProcessor.cs similarity index 100% rename from src/OpenTelemetry/BatchLogRecordExportProcessor.cs rename to src/OpenTelemetry/Logs/BatchLogRecordExportProcessor.cs diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs b/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs index d600a305cde..574dfbefb55 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs @@ -29,8 +29,8 @@ internal class OpenTelemetryLogger : ILogger internal OpenTelemetryLogger(string categoryName, OpenTelemetryLoggerProvider provider) { - Guard.ThrowIfNull(categoryName, nameof(categoryName)); - Guard.ThrowIfNull(provider, nameof(provider)); + Guard.ThrowIfNull(categoryName); + Guard.ThrowIfNull(provider); this.categoryName = categoryName; this.provider = provider; diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs index 6b6b1542ead..1985446e4cd 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs @@ -58,7 +58,7 @@ public class OpenTelemetryLoggerOptions /// Returns for chaining. public OpenTelemetryLoggerOptions AddProcessor(BaseProcessor processor) { - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(processor); this.Processors.Add(processor); @@ -73,7 +73,7 @@ public OpenTelemetryLoggerOptions AddProcessor(BaseProcessor processo /// Returns for chaining. public OpenTelemetryLoggerOptions SetResourceBuilder(ResourceBuilder resourceBuilder) { - Guard.ThrowIfNull(resourceBuilder, nameof(resourceBuilder)); + Guard.ThrowIfNull(resourceBuilder); this.ResourceBuilder = resourceBuilder; return this; diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs index 85fdbfeb405..543fe687ab4 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs @@ -46,7 +46,7 @@ public OpenTelemetryLoggerProvider(IOptionsMonitor o internal OpenTelemetryLoggerProvider(OpenTelemetryLoggerOptions options) { - Guard.ThrowIfNull(options, nameof(options)); + Guard.ThrowIfNull(options); this.Options = options; this.Resource = options.ResourceBuilder.Build(); @@ -97,7 +97,7 @@ public ILogger CreateLogger(string categoryName) internal OpenTelemetryLoggerProvider AddProcessor(BaseProcessor processor) { - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(processor); processor.SetParentProvider(this); diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs index 0b48ea5d35e..354ad87868c 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs @@ -28,7 +28,7 @@ public static class OpenTelemetryLoggingExtensions { public static ILoggingBuilder AddOpenTelemetry(this ILoggingBuilder builder, Action configure = null) { - Guard.ThrowIfNull(builder, nameof(builder)); + Guard.ThrowIfNull(builder); builder.AddConfiguration(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); diff --git a/src/OpenTelemetry/SimpleLogRecordExportProcessor.cs b/src/OpenTelemetry/Logs/SimpleLogRecordExportProcessor.cs similarity index 100% rename from src/OpenTelemetry/SimpleLogRecordExportProcessor.cs rename to src/OpenTelemetry/Logs/SimpleLogRecordExportProcessor.cs diff --git a/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs b/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs index 4b7b845a754..0f9be5b07d9 100644 --- a/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs +++ b/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs @@ -29,7 +29,7 @@ public class BaseExportingMetricReader : MetricReader public BaseExportingMetricReader(BaseExporter exporter) { - Guard.ThrowIfNull(exporter, nameof(exporter)); + Guard.ThrowIfNull(exporter); this.exporter = exporter; diff --git a/src/OpenTelemetry/Metrics/CompositeMetricReader.cs b/src/OpenTelemetry/Metrics/CompositeMetricReader.cs index 537cec59385..b06339118f6 100644 --- a/src/OpenTelemetry/Metrics/CompositeMetricReader.cs +++ b/src/OpenTelemetry/Metrics/CompositeMetricReader.cs @@ -34,7 +34,7 @@ internal sealed partial class CompositeMetricReader : MetricReader public CompositeMetricReader(IEnumerable readers) { - Guard.ThrowIfNull(readers, nameof(readers)); + Guard.ThrowIfNull(readers); using var iter = readers.GetEnumerator(); if (!iter.MoveNext()) @@ -54,7 +54,7 @@ public CompositeMetricReader(IEnumerable readers) public CompositeMetricReader AddReader(MetricReader reader) { - Guard.ThrowIfNull(reader, nameof(reader)); + Guard.ThrowIfNull(reader); var node = new DoublyLinkedListNode(reader) { diff --git a/src/OpenTelemetry/Metrics/MeterProviderBuilderBase.cs b/src/OpenTelemetry/Metrics/MeterProviderBuilderBase.cs index 18817cf5b66..81236946f10 100644 --- a/src/OpenTelemetry/Metrics/MeterProviderBuilderBase.cs +++ b/src/OpenTelemetry/Metrics/MeterProviderBuilderBase.cs @@ -47,7 +47,7 @@ protected MeterProviderBuilderBase() /// public override MeterProviderBuilder AddInstrumentation(Func instrumentationFactory) { - Guard.ThrowIfNull(instrumentationFactory, nameof(instrumentationFactory)); + Guard.ThrowIfNull(instrumentationFactory); this.instrumentationFactories.Add( new InstrumentationFactory( @@ -61,11 +61,11 @@ public override MeterProviderBuilder AddInstrumentation(Func public override MeterProviderBuilder AddMeter(params string[] names) { - Guard.ThrowIfNull(names, nameof(names)); + Guard.ThrowIfNull(names); foreach (var name in names) { - Guard.ThrowIfNullOrWhitespace(name, nameof(name)); + Guard.ThrowIfNullOrWhitespace(name); this.meterSources.Add(name); } diff --git a/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs b/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs index d9f6b99dbe1..91bcf619800 100644 --- a/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs +++ b/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs @@ -42,8 +42,8 @@ public static class MeterProviderExtensions /// public static bool ForceFlush(this MeterProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfNull(provider, nameof(provider)); - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfNull(provider); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (provider is MeterProviderSdk meterProviderSdk) { @@ -82,8 +82,8 @@ public static bool ForceFlush(this MeterProvider provider, int timeoutMillisecon /// public static bool Shutdown(this MeterProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfNull(provider, nameof(provider)); - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfNull(provider); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (provider is MeterProviderSdk meterProviderSdk) { diff --git a/src/OpenTelemetry/Metrics/MeterProviderSdk.cs b/src/OpenTelemetry/Metrics/MeterProviderSdk.cs index dab408f3e22..665ee354f05 100644 --- a/src/OpenTelemetry/Metrics/MeterProviderSdk.cs +++ b/src/OpenTelemetry/Metrics/MeterProviderSdk.cs @@ -49,7 +49,7 @@ internal MeterProviderSdk( foreach (var reader in readers) { - Guard.ThrowIfNull(reader, nameof(reader)); + Guard.ThrowIfNull(reader); reader.SetParentProvider(this); reader.SetMaxMetricStreams(maxMetricStreams); diff --git a/src/OpenTelemetry/Metrics/MetricPointsAccessor.cs b/src/OpenTelemetry/Metrics/MetricPointsAccessor.cs index ef5c1dc0054..e650964b73f 100644 --- a/src/OpenTelemetry/Metrics/MetricPointsAccessor.cs +++ b/src/OpenTelemetry/Metrics/MetricPointsAccessor.cs @@ -33,7 +33,7 @@ public readonly struct MetricPointsAccessor internal MetricPointsAccessor(MetricPoint[] metricsPoints, int[] metricPointsToProcess, long targetCount, DateTimeOffset start, DateTimeOffset end) { - Guard.ThrowIfNull(metricsPoints, nameof(metricsPoints)); + Guard.ThrowIfNull(metricsPoints); this.metricsPoints = metricsPoints; this.metricPointsToProcess = metricPointsToProcess; diff --git a/src/OpenTelemetry/Metrics/MetricReader.cs b/src/OpenTelemetry/Metrics/MetricReader.cs index fb202a9fe64..98c2bb1d70c 100644 --- a/src/OpenTelemetry/Metrics/MetricReader.cs +++ b/src/OpenTelemetry/Metrics/MetricReader.cs @@ -84,7 +84,7 @@ public AggregationTemporality Temporality /// public bool Collect(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); var shouldRunCollect = false; var tcs = this.collectionTcs; @@ -147,7 +147,7 @@ public bool Collect(int timeoutMilliseconds = Timeout.Infinite) /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (Interlocked.CompareExchange(ref this.shutdownCount, 1, 0) != 0) { diff --git a/src/OpenTelemetry/Metrics/MetricReaderOptions.cs b/src/OpenTelemetry/Metrics/MetricReaderOptions.cs new file mode 100644 index 00000000000..d9fe24b909d --- /dev/null +++ b/src/OpenTelemetry/Metrics/MetricReaderOptions.cs @@ -0,0 +1,58 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace OpenTelemetry.Metrics; + +/// +/// Options for configuring either a or . +/// +public class MetricReaderOptions +{ + private const MetricReaderType MetricReaderTypeUnspecified = (MetricReaderType)(-1); + private MetricReaderType metricReaderType = MetricReaderTypeUnspecified; + + /// + /// Gets or sets the AggregationTemporality used for Histogram + /// and Sum metrics. + /// + public AggregationTemporality Temporality { get; set; } = AggregationTemporality.Cumulative; + + /// + /// Gets or sets the to use. Defaults to MetricReaderType.Manual. + /// + public MetricReaderType MetricReaderType + { + get + { + if (this.metricReaderType == MetricReaderTypeUnspecified) + { + this.metricReaderType = MetricReaderType.Manual; + } + + return this.metricReaderType; + } + + set + { + this.metricReaderType = value; + } + } + + /// + /// Gets or sets the options. Ignored unless MetricReaderType is Periodic. + /// + public PeriodicExportingMetricReaderOptions PeriodicExportingMetricReaderOptions { get; set; } = new PeriodicExportingMetricReaderOptions(); +} diff --git a/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs b/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs index f6cdcdff155..8a4021f1095 100644 --- a/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs +++ b/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs @@ -39,8 +39,8 @@ public PeriodicExportingMetricReader( int exportTimeoutMilliseconds = DefaultExportTimeoutMilliseconds) : base(exporter) { - Guard.ThrowIfOutOfRange(exportIntervalMilliseconds, nameof(exportIntervalMilliseconds), min: 1); - Guard.ThrowIfOutOfRange(exportTimeoutMilliseconds, nameof(exportTimeoutMilliseconds), min: 0); + Guard.ThrowIfOutOfRange(exportIntervalMilliseconds, min: 1); + Guard.ThrowIfOutOfRange(exportTimeoutMilliseconds, min: 0); if ((this.SupportedExportModes & ExportModes.Push) != ExportModes.Push) { diff --git a/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs b/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs index af193f7f7ad..2b57840ccd1 100644 --- a/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs +++ b/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs @@ -52,7 +52,7 @@ internal static ThreadStaticStorage GetStorage() [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SplitToKeysAndValues(ReadOnlySpan> tags, int tagLength, out string[] tagKeys, out object[] tagValues) { - Guard.ThrowIfZero(tagLength, $"There must be at least one tag to use {nameof(ThreadStaticStorage)}", $"{nameof(tagLength)}"); + Guard.ThrowIfZero(tagLength, $"There must be at least one tag to use {nameof(ThreadStaticStorage)}"); if (tagLength <= MaxTagCacheSize) { diff --git a/src/OpenTelemetry/Resources/IResourceDetector.cs b/src/OpenTelemetry/Resources/IResourceDetector.cs index 7fd4e652317..a55459807db 100644 --- a/src/OpenTelemetry/Resources/IResourceDetector.cs +++ b/src/OpenTelemetry/Resources/IResourceDetector.cs @@ -19,7 +19,7 @@ namespace OpenTelemetry.Resources /// /// An interface for Resource detectors. /// - internal interface IResourceDetector + public interface IResourceDetector { /// /// Called to get a resource with attributes from detector. diff --git a/src/OpenTelemetry/Resources/Resource.cs b/src/OpenTelemetry/Resources/Resource.cs index 72cb6cab4e4..1ec6bda90fc 100644 --- a/src/OpenTelemetry/Resources/Resource.cs +++ b/src/OpenTelemetry/Resources/Resource.cs @@ -109,7 +109,7 @@ private static KeyValuePair SanitizeAttribute(KeyValuePair resourceAttributes = new Dictionary(); - Guard.ThrowIfNullOrEmpty(serviceName, nameof(serviceName)); + Guard.ThrowIfNullOrEmpty(serviceName); resourceAttributes.Add(ResourceSemanticConventions.AttributeServiceName, serviceName); diff --git a/src/OpenTelemetry/BatchActivityExportProcessor.cs b/src/OpenTelemetry/Trace/BatchActivityExportProcessor.cs similarity index 100% rename from src/OpenTelemetry/BatchActivityExportProcessor.cs rename to src/OpenTelemetry/Trace/BatchActivityExportProcessor.cs diff --git a/src/OpenTelemetry/Trace/ParentBasedSampler.cs b/src/OpenTelemetry/Trace/ParentBasedSampler.cs index e83e94b8d12..deb9d0eb3ec 100644 --- a/src/OpenTelemetry/Trace/ParentBasedSampler.cs +++ b/src/OpenTelemetry/Trace/ParentBasedSampler.cs @@ -43,7 +43,7 @@ public sealed class ParentBasedSampler : Sampler /// The to be called for root span/activity. public ParentBasedSampler(Sampler rootSampler) { - Guard.ThrowIfNull(rootSampler, nameof(rootSampler)); + Guard.ThrowIfNull(rootSampler); this.rootSampler = rootSampler; this.Description = $"ParentBased{{{rootSampler.Description}}}"; diff --git a/src/OpenTelemetry/SimpleActivityExportProcessor.cs b/src/OpenTelemetry/Trace/SimpleActivityExportProcessor.cs similarity index 100% rename from src/OpenTelemetry/SimpleActivityExportProcessor.cs rename to src/OpenTelemetry/Trace/SimpleActivityExportProcessor.cs diff --git a/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs b/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs index 049c620e48d..d1c9d364a85 100644 --- a/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs +++ b/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs @@ -37,7 +37,7 @@ public sealed class TraceIdRatioBasedSampler /// public TraceIdRatioBasedSampler(double probability) { - Guard.ThrowIfOutOfRange(probability, nameof(probability), min: 0.0, max: 1.0); + Guard.ThrowIfOutOfRange(probability, min: 0.0, max: 1.0); this.probability = probability; diff --git a/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs b/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs index 1502dd4e18f..7e442515bcf 100644 --- a/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs +++ b/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs @@ -43,7 +43,7 @@ public override TracerProviderBuilder AddInstrumentation( Func instrumentationFactory) where TInstrumentation : class { - Guard.ThrowIfNull(instrumentationFactory, nameof(instrumentationFactory)); + Guard.ThrowIfNull(instrumentationFactory); this.instrumentationFactories.Add( new InstrumentationFactory( @@ -57,11 +57,11 @@ public override TracerProviderBuilder AddInstrumentation( /// public override TracerProviderBuilder AddSource(params string[] names) { - Guard.ThrowIfNull(names, nameof(names)); + Guard.ThrowIfNull(names); foreach (var name in names) { - Guard.ThrowIfNullOrWhitespace(name, nameof(name)); + Guard.ThrowIfNullOrWhitespace(name); // TODO: We need to fix the listening model. // Today it ignores version. @@ -74,7 +74,7 @@ public override TracerProviderBuilder AddSource(params string[] names) /// public override TracerProviderBuilder AddLegacySource(string operationName) { - Guard.ThrowIfNullOrWhitespace(operationName, nameof(operationName)); + Guard.ThrowIfNullOrWhitespace(operationName); this.legacyActivityOperationNames.Add(operationName); @@ -129,7 +129,7 @@ internal TracerProviderBuilder SetErrorStatusOnException(bool enabled) /// Returns for chaining. internal TracerProviderBuilder SetSampler(Sampler sampler) { - Guard.ThrowIfNull(sampler, nameof(sampler)); + Guard.ThrowIfNull(sampler); this.sampler = sampler; return this; @@ -143,7 +143,7 @@ internal TracerProviderBuilder SetSampler(Sampler sampler) /// Returns for chaining. internal TracerProviderBuilder SetResourceBuilder(ResourceBuilder resourceBuilder) { - Guard.ThrowIfNull(resourceBuilder, nameof(resourceBuilder)); + Guard.ThrowIfNull(resourceBuilder); this.resourceBuilder = resourceBuilder; return this; @@ -156,7 +156,7 @@ internal TracerProviderBuilder SetResourceBuilder(ResourceBuilder resourceBuilde /// Returns for chaining. internal TracerProviderBuilder AddProcessor(BaseProcessor processor) { - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(processor); this.processors.Add(processor); diff --git a/src/OpenTelemetry/Trace/TracerProviderExtensions.cs b/src/OpenTelemetry/Trace/TracerProviderExtensions.cs index 555c1cfe6e1..44016245f7d 100644 --- a/src/OpenTelemetry/Trace/TracerProviderExtensions.cs +++ b/src/OpenTelemetry/Trace/TracerProviderExtensions.cs @@ -25,8 +25,8 @@ public static class TracerProviderExtensions { public static TracerProvider AddProcessor(this TracerProvider provider, BaseProcessor processor) { - Guard.ThrowIfNull(provider, nameof(provider)); - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(provider); + Guard.ThrowIfNull(processor); if (provider is TracerProviderSdk tracerProviderSdk) { @@ -56,8 +56,8 @@ public static TracerProvider AddProcessor(this TracerProvider provider, BaseProc /// public static bool ForceFlush(this TracerProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfNull(provider, nameof(provider)); - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfNull(provider); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (provider is TracerProviderSdk tracerProviderSdk) { @@ -96,8 +96,8 @@ public static bool ForceFlush(this TracerProvider provider, int timeoutMilliseco /// public static bool Shutdown(this TracerProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - Guard.ThrowIfNull(provider, nameof(provider)); - Guard.ThrowIfInvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); + Guard.ThrowIfNull(provider); + Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); if (provider is TracerProviderSdk tracerProviderSdk) { diff --git a/src/OpenTelemetry/Trace/TracerProviderSdk.cs b/src/OpenTelemetry/Trace/TracerProviderSdk.cs index 973a1c450de..04d07246bc9 100644 --- a/src/OpenTelemetry/Trace/TracerProviderSdk.cs +++ b/src/OpenTelemetry/Trace/TracerProviderSdk.cs @@ -263,7 +263,7 @@ internal TracerProviderSdk( internal TracerProviderSdk AddProcessor(BaseProcessor processor) { - Guard.ThrowIfNull(processor, nameof(processor)); + Guard.ThrowIfNull(processor); processor.SetParentProvider(this); diff --git a/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsExtensionsTests.cs b/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsExtensionsTests.cs new file mode 100644 index 00000000000..0dfca9cc3cd --- /dev/null +++ b/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsExtensionsTests.cs @@ -0,0 +1,33 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using Xunit; + +namespace OpenTelemetry.Exporter.Jaeger.Tests; + +public class JaegerExporterOptionsExtensionsTests +{ + [Theory] + [InlineData("udp/thrift.compact", JaegerExportProtocol.UdpCompactThrift)] + [InlineData("http/thrift.binary", JaegerExportProtocol.HttpBinaryThrift)] + [InlineData("unsupported", null)] + public void ToJaegerExportProtocol_Protocol_MapsToCorrectValue(string protocol, JaegerExportProtocol? expectedExportProtocol) + { + var exportProtocol = protocol.ToJaegerExportProtocol(); + + Assert.Equal(expectedExportProtocol, exportProtocol); + } +} diff --git a/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsTests.cs b/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsTests.cs index 992cac0591d..89d0dc17360 100644 --- a/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsTests.cs +++ b/test/OpenTelemetry.Exporter.Jaeger.Tests/JaegerExporterOptionsTests.cs @@ -23,12 +23,12 @@ public class JaegerExporterOptionsTests : IDisposable { public JaegerExporterOptionsTests() { - this.ClearEnvVars(); + ClearEnvVars(); } public void Dispose() { - this.ClearEnvVars(); + ClearEnvVars(); } [Fact] @@ -40,6 +40,7 @@ public void JaegerExporterOptions_Defaults() Assert.Equal(6831, options.AgentPort); Assert.Equal(4096, options.MaxPayloadSizeInBytes); Assert.Equal(ExportProcessorType.Batch, options.ExportProcessorType); + Assert.Equal(JaegerExportProtocol.UdpCompactThrift, options.Protocol); Assert.Equal(JaegerExporterOptions.DefaultJaegerEndpoint, options.Endpoint.ToString()); } @@ -48,17 +49,23 @@ public void JaegerExporterOptions_EnvironmentVariableOverride() { Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelAgentHostEnvVarKey, "jeager-host"); Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelAgentPortEnvVarKey, "123"); + Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelProtocolEnvVarKey, "http/thrift.binary"); + Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelEndpointEnvVarKey, "http://custom-endpoint:12345"); var options = new JaegerExporterOptions(); Assert.Equal("jeager-host", options.AgentHost); Assert.Equal(123, options.AgentPort); + Assert.Equal(JaegerExportProtocol.HttpBinaryThrift, options.Protocol); + Assert.Equal(new Uri("http://custom-endpoint:12345"), options.Endpoint); } - [Fact] - public void JaegerExporterOptions_InvalidPortEnvironmentVariableOverride() + [Theory] + [InlineData(JaegerExporterOptions.OTelAgentPortEnvVarKey)] + [InlineData(JaegerExporterOptions.OTelProtocolEnvVarKey)] + public void JaegerExporterOptions_InvalidEnvironmentVariableOverride(string envVar) { - Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelAgentPortEnvVarKey, "invalid"); + Environment.SetEnvironmentVariable(envVar, "invalid"); Assert.Throws(() => new JaegerExporterOptions()); } @@ -79,14 +86,18 @@ public void JaegerExporterOptions_SetterOverridesEnvironmentVariable() [Fact] public void JaegerExporterOptions_EnvironmentVariableNames() { + Assert.Equal("OTEL_EXPORTER_JAEGER_PROTOCOL", JaegerExporterOptions.OTelProtocolEnvVarKey); Assert.Equal("OTEL_EXPORTER_JAEGER_AGENT_HOST", JaegerExporterOptions.OTelAgentHostEnvVarKey); Assert.Equal("OTEL_EXPORTER_JAEGER_AGENT_PORT", JaegerExporterOptions.OTelAgentPortEnvVarKey); + Assert.Equal("OTEL_EXPORTER_JAEGER_ENDPOINT", JaegerExporterOptions.OTelEndpointEnvVarKey); } - private void ClearEnvVars() + private static void ClearEnvVars() { + Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelProtocolEnvVarKey, null); Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelAgentHostEnvVarKey, null); Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelAgentPortEnvVarKey, null); + Environment.SetEnvironmentVariable(JaegerExporterOptions.OTelEndpointEnvVarKey, null); } } } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs index 970f96daaea..3a9b32b179e 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs @@ -173,9 +173,9 @@ public void AppendExportPath_EndpointNotSet_EnvironmentVariableNotDefined_NotApp var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf }; - options.AppendExportPath(options.Endpoint, "test/path"); + options.AppendExportPath("test/path"); - Assert.Equal("http://localhost:4317/", options.Endpoint.AbsoluteUri); + Assert.Equal("http://localhost:4318/", options.Endpoint.AbsoluteUri); } [Fact] @@ -185,7 +185,7 @@ public void AppendExportPath_EndpointNotSet_EnvironmentVariableDefined_Appended( var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf }; - options.AppendExportPath(options.Endpoint, "test/path"); + options.AppendExportPath("test/path"); Assert.Equal("http://test:8888/test/path", options.Endpoint.AbsoluteUri); @@ -198,10 +198,9 @@ public void AppendExportPath_EndpointSetEqualToEnvironmentVariable_EnvironmentVa Environment.SetEnvironmentVariable(OtlpExporterOptions.EndpointEnvVarName, "http://test:8888"); var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf }; - var originalEndpoint = options.Endpoint; options.Endpoint = new Uri("http://test:8888"); - options.AppendExportPath(originalEndpoint, "test/path"); + options.AppendExportPath("test/path"); Assert.Equal("http://test:8888/", options.Endpoint.AbsoluteUri); @@ -219,7 +218,7 @@ public void AppendExportPath_EndpointSet_EnvironmentVariableNotDefined_NotAppend var originalEndpoint = options.Endpoint; options.Endpoint = new Uri(endpoint); - options.AppendExportPath(originalEndpoint, "test/path"); + options.AppendExportPath("test/path"); Assert.Equal(endpoint, options.Endpoint.AbsoluteUri); } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs index 2b7a612fa06..f92b7996885 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs @@ -42,6 +42,19 @@ public void OtlpExporterOptions_Defaults() Assert.Equal(OtlpExportProtocol.Grpc, options.Protocol); } + [Fact] + public void OtlpExporterOptions_DefaultsForHttpProtobuf() + { + var options = new OtlpExporterOptions + { + Protocol = OtlpExportProtocol.HttpProtobuf, + }; + Assert.Equal(new Uri("http://localhost:4318"), options.Endpoint); + Assert.Null(options.Headers); + Assert.Equal(10000, options.TimeoutMilliseconds); + Assert.Equal(OtlpExportProtocol.HttpProtobuf, options.Protocol); + } + [Fact] public void OtlpExporterOptions_EnvironmentVariableOverride() { @@ -104,6 +117,26 @@ public void OtlpExporterOptions_SetterOverridesEnvironmentVariable() Assert.Equal(OtlpExportProtocol.HttpProtobuf, options.Protocol); } + [Fact] + public void OtlpExporterOptions_ProtocolSetterDoesNotOverrideCustomEndpointFromEnvVariables() + { + Environment.SetEnvironmentVariable(OtlpExporterOptions.EndpointEnvVarName, "http://test:8888"); + + var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.Grpc }; + + Assert.Equal(new Uri("http://test:8888"), options.Endpoint); + Assert.Equal(OtlpExportProtocol.Grpc, options.Protocol); + } + + [Fact] + public void OtlpExporterOptions_ProtocolSetterDoesNotOverrideCustomEndpointFromSetter() + { + var options = new OtlpExporterOptions { Endpoint = new Uri("http://test:8888"), Protocol = OtlpExportProtocol.Grpc }; + + Assert.Equal(new Uri("http://test:8888"), options.Endpoint); + Assert.Equal(OtlpExportProtocol.Grpc, options.Protocol); + } + [Fact] public void OtlpExporterOptions_EnvironmentVariableNames() { diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs index 564e404076e..3b69bbf5fae 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs @@ -14,10 +14,14 @@ // limitations under the License. // +using System; using System.Collections.Generic; +using System.Diagnostics; using Microsoft.Extensions.Logging; using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation; +using OpenTelemetry.Internal; using OpenTelemetry.Logs; +using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; @@ -26,14 +30,9 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests public class OtlpLogExporterTests : Http2UnencryptedSupportTests { [Fact] - public void ToOtlpLogRecordTest() + public void CheckToOtlpLogRecordStateValues() { - // Just a basic test to demonstrate an - // approach useful for testing. - // This needs to be expanded to - // actually test the conversion. List logRecords = new List(); - using var loggerFactory = LoggerFactory.Create(builder => { builder.AddOpenTelemetry(options => @@ -44,32 +43,202 @@ public void ToOtlpLogRecordTest() }); }); - // TODO: - // Validate attributes, severity, traceid,spanid etc. - - var logger = loggerFactory.CreateLogger("log-category"); + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99); + Assert.Single(logRecords); + var logRecord = logRecords[0]; var otlpLogRecord = logRecord.ToOtlpLog(); + Assert.NotNull(otlpLogRecord); Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue); - logRecords.Clear(); + Assert.Contains("name", otlpLogRecord.Attributes.ToString()); + Assert.Contains("tomato", otlpLogRecord.Attributes.ToString()); + Assert.Contains("{OriginalFormat}", otlpLogRecord.Attributes.ToString()); + } + [Fact] + public void CheckToOtlpLogRecordEventId() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.IncludeFormattedMessage = true; + options.ParseStateValues = true; + options.AddInMemoryExporter(logRecords); + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); logger.LogInformation(new EventId(10, null), "Hello from {name} {price}.", "tomato", 2.99); Assert.Single(logRecords); - logRecord = logRecords[0]; - otlpLogRecord = logRecord.ToOtlpLog(); + + var logRecord = logRecords[0]; + var otlpLogRecord = logRecord.ToOtlpLog(); + Assert.NotNull(otlpLogRecord); Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue); + + var otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString(); + + // Event + Assert.Contains("Id", otlpLogRecordAttributes); + Assert.Contains("10", otlpLogRecordAttributes); + logRecords.Clear(); logger.LogInformation(new EventId(10, "MyEvent10"), "Hello from {name} {price}.", "tomato", 2.99); Assert.Single(logRecords); + logRecord = logRecords[0]; otlpLogRecord = logRecord.ToOtlpLog(); Assert.NotNull(otlpLogRecord); Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue); + + otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString(); + + // Event + Assert.Contains("Id", otlpLogRecordAttributes); + Assert.Contains("10", otlpLogRecordAttributes); + Assert.Contains("Name", otlpLogRecordAttributes); + Assert.Contains("MyEvent10", otlpLogRecordAttributes); + } + + [Fact] + public void CheckToOtlpLogRecordTraceIdSpanIdFlagWithNoActivity() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddInMemoryExporter(logRecords); + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); + logger.LogInformation("Log when there is no activity."); + var logRecord = logRecords[0]; + var otlpLogRecord = logRecord.ToOtlpLog(); + + Assert.Null(Activity.Current); + Assert.True(otlpLogRecord.TraceId.IsEmpty); + Assert.True(otlpLogRecord.SpanId.IsEmpty); + Assert.True(otlpLogRecord.Flags == 0); + } + + [Fact] + public void CheckToOtlpLogRecordSpanIdTraceIdAndFlag() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddInMemoryExporter(logRecords); + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); + + ActivityTraceId expectedTraceId = default; + ActivitySpanId expectedSpanId = default; + using (var activity = new Activity(Utils.GetCurrentMethodName()).Start()) + { + logger.LogInformation("Log within an activity."); + + expectedTraceId = activity.TraceId; + expectedSpanId = activity.SpanId; + } + + var logRecord = logRecords[0]; + var otlpLogRecord = logRecord.ToOtlpLog(); + + Assert.Equal(expectedTraceId.ToString(), ActivityTraceId.CreateFromBytes(otlpLogRecord.TraceId.ToByteArray()).ToString()); + Assert.Equal(expectedSpanId.ToString(), ActivitySpanId.CreateFromBytes(otlpLogRecord.SpanId.ToByteArray()).ToString()); + Assert.Equal((uint)logRecord.TraceFlags, otlpLogRecord.Flags); + } + + [Fact] + public void CheckToOtlpLogRecordSeverityText() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddInMemoryExporter(logRecords); + options.IncludeFormattedMessage = true; + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); + logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99); + Assert.Single(logRecords); + + var logRecord = logRecords[0]; + var otlpLogRecord = logRecord.ToOtlpLog(); + + Assert.NotNull(otlpLogRecord); + Assert.Equal(logRecord.LogLevel.ToString(), otlpLogRecord.SeverityText); + } + + [Fact] + public void CheckToOtlpLogRecordFormattedMessage() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddInMemoryExporter(logRecords); + options.IncludeFormattedMessage = true; + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); + logger.LogInformation("OpenTelemetry {Greeting} {Subject}!", "Hello", "World"); + Assert.Single(logRecords); + + var logRecord = logRecords[0]; + var otlpLogRecord = logRecord.ToOtlpLog(); + + Assert.NotNull(otlpLogRecord); + Assert.Equal(logRecord.FormattedMessage, otlpLogRecord.Body.StringValue); + } + + [Fact] + public void CheckToOtlpLogRecordExceptionAttributes() + { + List logRecords = new List(); + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddInMemoryExporter(logRecords); + }); + }); + + var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); + logger.LogInformation(new Exception("Exception Message"), "Exception Occurred"); + + var logRecord = logRecords[0]; + var loggedException = logRecord.Exception; + var otlpLogRecord = logRecord.ToOtlpLog(); + + Assert.NotNull(otlpLogRecord); + var otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString(); + Assert.Contains(SemanticConventions.AttributeExceptionType, otlpLogRecordAttributes); + Assert.Contains(logRecord.Exception.GetType().Name, otlpLogRecordAttributes); + + Assert.Contains(SemanticConventions.AttributeExceptionMessage, otlpLogRecordAttributes); + Assert.Contains(logRecord.Exception.Message, otlpLogRecordAttributes); + + Assert.Contains(SemanticConventions.AttributeExceptionStacktrace, otlpLogRecordAttributes); + Assert.Contains(logRecord.Exception.ToInvariantString(), otlpLogRecordAttributes); } } } diff --git a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs index 465c3192173..bc1588d001e 100644 --- a/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNet.Tests/HttpInListenerTests.cs @@ -137,14 +137,7 @@ public void AspNetRequestsAreCollectedSuccessfully( return httpContext.Request.Path != filter; }; - if (setStatusToErrorInEnrich) - { - options.Enrich = GetEnrichmentAction(Status.Error); - } - else - { - options.Enrich = GetEnrichmentAction(default); - } + options.Enrich = GetEnrichmentAction(setStatusToErrorInEnrich ? Status.Error : default); options.RecordException = recordException; }) @@ -205,7 +198,7 @@ public void AspNetRequestsAreCollectedSuccessfully( } // Host includes port if it isn't 80 or 443. - if (expectedUri.Port == 80 || expectedUri.Port == 443) + if (expectedUri.Port is 80 or 443) { Assert.Equal( expectedUri.Host, diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs index db77e75cc2c..1c2b4174d9a 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs @@ -399,40 +399,38 @@ public async Task ExtractContextIrrespectiveOfSamplingDecision(SamplingDecision Sdk.SetDefaultTextMapPropagator(new ExtractOnlyPropagator(activityContext, expectedBaggage)); // Arrange - using (var testFactory = this.factory + using var testFactory = this.factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { this.tracerProvider = Sdk.CreateTracerProviderBuilder() - .SetSampler(new TestSampler(samplingDecision)) - .AddAspNetCoreInstrumentation() - .Build(); - }))) - { - using var client = testFactory.CreateClient(); + .SetSampler(new TestSampler(samplingDecision)) + .AddAspNetCoreInstrumentation() + .Build(); + })); + using var client = testFactory.CreateClient(); - // Test TraceContext Propagation - var request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityTraceContext"); - var response = await client.SendAsync(request); - var childActivityTraceContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); + // Test TraceContext Propagation + var request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityTraceContext"); + var response = await client.SendAsync(request); + var childActivityTraceContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - Assert.Equal(expectedTraceId.ToString(), childActivityTraceContext["TraceId"]); - Assert.Equal(expectedTraceState, childActivityTraceContext["TraceState"]); - Assert.NotEqual(expectedParentSpanId.ToString(), childActivityTraceContext["ParentSpanId"]); // there is a new activity created in instrumentation therefore the ParentSpanId is different that what is provided in the headers + Assert.Equal(expectedTraceId.ToString(), childActivityTraceContext["TraceId"]); + Assert.Equal(expectedTraceState, childActivityTraceContext["TraceState"]); + Assert.NotEqual(expectedParentSpanId.ToString(), childActivityTraceContext["ParentSpanId"]); // there is a new activity created in instrumentation therefore the ParentSpanId is different that what is provided in the headers - // Test Baggage Context Propagation - request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityBaggageContext"); + // Test Baggage Context Propagation + request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityBaggageContext"); - response = await client.SendAsync(request); - var childActivityBaggageContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); + response = await client.SendAsync(request); + var childActivityBaggageContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - Assert.Single(childActivityBaggageContext, item => item.Key == "key1" && item.Value == "value1"); - Assert.Single(childActivityBaggageContext, item => item.Key == "key2" && item.Value == "value2"); - } + Assert.Single(childActivityBaggageContext, item => item.Key == "key1" && item.Value == "value1"); + Assert.Single(childActivityBaggageContext, item => item.Key == "key2" && item.Value == "value2"); } finally { @@ -458,50 +456,48 @@ public async Task ExtractContextIrrespectiveOfTheFilterApplied() // Arrange bool isFilterCalled = false; - using (var testFactory = this.factory + using var testFactory = this.factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { this.tracerProvider = Sdk.CreateTracerProviderBuilder() - .AddAspNetCoreInstrumentation(options => - { - options.Filter = context => + .AddAspNetCoreInstrumentation(options => { - isFilterCalled = true; - return false; - }; - }) - .Build(); - }))) - { - using var client = testFactory.CreateClient(); + options.Filter = context => + { + isFilterCalled = true; + return false; + }; + }) + .Build(); + })); + using var client = testFactory.CreateClient(); - // Test TraceContext Propagation - var request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityTraceContext"); - var response = await client.SendAsync(request); + // Test TraceContext Propagation + var request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityTraceContext"); + var response = await client.SendAsync(request); - // Ensure that filter was called - Assert.True(isFilterCalled); + // Ensure that filter was called + Assert.True(isFilterCalled); - var childActivityTraceContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); + var childActivityTraceContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - Assert.Equal(expectedTraceId.ToString(), childActivityTraceContext["TraceId"]); - Assert.Equal(expectedTraceState, childActivityTraceContext["TraceState"]); - Assert.NotEqual(expectedParentSpanId.ToString(), childActivityTraceContext["ParentSpanId"]); // there is a new activity created in instrumentation therefore the ParentSpanId is different that what is provided in the headers + Assert.Equal(expectedTraceId.ToString(), childActivityTraceContext["TraceId"]); + Assert.Equal(expectedTraceState, childActivityTraceContext["TraceState"]); + Assert.NotEqual(expectedParentSpanId.ToString(), childActivityTraceContext["ParentSpanId"]); // there is a new activity created in instrumentation therefore the ParentSpanId is different that what is provided in the headers - // Test Baggage Context Propagation - request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityBaggageContext"); + // Test Baggage Context Propagation + request = new HttpRequestMessage(HttpMethod.Get, "/api/GetChildActivityBaggageContext"); - response = await client.SendAsync(request); - var childActivityBaggageContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); + response = await client.SendAsync(request); + var childActivityBaggageContext = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - Assert.Single(childActivityBaggageContext, item => item.Key == "key1" && item.Value == "value1"); - Assert.Single(childActivityBaggageContext, item => item.Key == "key2" && item.Value == "value2"); - } + Assert.Single(childActivityBaggageContext, item => item.Key == "key1" && item.Value == "value1"); + Assert.Single(childActivityBaggageContext, item => item.Key == "key2" && item.Value == "value2"); } finally { diff --git a/test/OpenTelemetry.Tests.Stress.Logs/DummyProcessor.cs b/test/OpenTelemetry.Tests.Stress.Logs/DummyProcessor.cs new file mode 100644 index 00000000000..004bb3aba94 --- /dev/null +++ b/test/OpenTelemetry.Tests.Stress.Logs/DummyProcessor.cs @@ -0,0 +1,27 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using OpenTelemetry; +using OpenTelemetry.Logs; + +namespace OpenTelemetry.Tests.Stress; + +internal class DummyProcessor : BaseProcessor +{ + public override void OnEnd(LogRecord record) + { + } +} diff --git a/test/OpenTelemetry.Tests.Stress.Logs/OpenTelemetry.Tests.Stress.Logs.csproj b/test/OpenTelemetry.Tests.Stress.Logs/OpenTelemetry.Tests.Stress.Logs.csproj new file mode 100644 index 00000000000..2067f9dec5d --- /dev/null +++ b/test/OpenTelemetry.Tests.Stress.Logs/OpenTelemetry.Tests.Stress.Logs.csproj @@ -0,0 +1,19 @@ + + + + Exe + netcoreapp3.1;net5.0;net6.0;net462 + false + + + + + + + + + + + + + diff --git a/test/OpenTelemetry.Tests.Stress.Logs/Payload.cs b/test/OpenTelemetry.Tests.Stress.Logs/Payload.cs new file mode 100644 index 00000000000..37fdcfcc243 --- /dev/null +++ b/test/OpenTelemetry.Tests.Stress.Logs/Payload.cs @@ -0,0 +1,120 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace OpenTelemetry.Tests.Stress; + +internal class Payload +{ + public int Field001 = 0; + public float Field002 = 2.718281828f; + public double Field003 = 3.141592653589793d; + public string Field004 = "Hello, World!"; + public bool Field005 = true; + public int Field006 = 6; + public int Field007 = 7; + public int Field008 = 8; + public int Field009 = 9; + public int Field010 = 10; + public int Field011 = 11; + public int Field012 = 12; + public int Field013 = 13; + public int Field014 = 14; + public int Field015 = 15; + public int Field016 = 16; + public int Field017 = 17; + public int Field018 = 18; + public int Field019 = 19; + public int Field020 = 20; + public int Field021 = 21; + public int Field022 = 22; + public int Field023 = 23; + public int Field024 = 24; + public int Field025 = 25; + public int Field026 = 26; + public int Field027 = 27; + public int Field028 = 28; + public int Field029 = 29; + public int Field030 = 30; + public int Field031 = 31; + public int Field032 = 32; + public int Field033 = 33; + public int Field034 = 34; + public int Field035 = 35; + public int Field036 = 36; + public int Field037 = 37; + public int Field038 = 38; + public int Field039 = 39; + public int Field040 = 40; + public int Field041 = 41; + public int Field042 = 42; + public int Field043 = 43; + public int Field044 = 44; + public int Field045 = 45; + public int Field046 = 46; + public int Field047 = 47; + public int Field048 = 48; + public int Field049 = 49; + public int Field050 = 50; + public int Field051 = 51; + public int Field052 = 52; + public int Field053 = 53; + public int Field054 = 54; + public int Field055 = 55; + public int Field056 = 56; + public int Field057 = 57; + public int Field058 = 58; + public int Field059 = 59; + public int Field060 = 60; + public int Field061 = 61; + public int Field062 = 62; + public int Field063 = 63; + public int Field064 = 64; + public int Field065 = 65; + public int Field066 = 66; + public int Field067 = 67; + public int Field068 = 68; + public int Field069 = 69; + public int Field070 = 70; + public int Field071 = 71; + public int Field072 = 72; + public int Field073 = 73; + public int Field074 = 74; + public int Field075 = 75; + public int Field076 = 76; + public int Field077 = 77; + public int Field078 = 78; + public int Field079 = 79; + public int Field080 = 80; + public int Field081 = 81; + public int Field082 = 82; + public int Field083 = 83; + public int Field084 = 84; + public int Field085 = 85; + public int Field086 = 86; + public int Field087 = 87; + public int Field088 = 88; + public int Field089 = 89; + public int Field090 = 90; + public int Field091 = 91; + public int Field092 = 92; + public int Field093 = 93; + public int Field094 = 94; + public int Field095 = 95; + public int Field096 = 96; + public int Field097 = 97; + public int Field098 = 98; + public int Field099 = 99; +} diff --git a/test/OpenTelemetry.Tests.Stress.Logs/Program.cs b/test/OpenTelemetry.Tests.Stress.Logs/Program.cs new file mode 100644 index 00000000000..1239e08432c --- /dev/null +++ b/test/OpenTelemetry.Tests.Stress.Logs/Program.cs @@ -0,0 +1,53 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System.Runtime.CompilerServices; +using Microsoft.Extensions.Logging; +using OpenTelemetry.Logs; + +namespace OpenTelemetry.Tests.Stress; + +public partial class Program +{ + private static ILogger logger; + private static Payload payload = new Payload(); + + public static void Main() + { + using var loggerFactory = LoggerFactory.Create(builder => + { + builder.AddOpenTelemetry(options => + { + options.AddProcessor(new DummyProcessor()); + }); + }); + + logger = loggerFactory.CreateLogger(); + + Stress(prometheusPort: 9184); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected static void Run() + { + logger.Log( + logLevel: LogLevel.Information, + eventId: 2, + state: payload, + exception: null, + formatter: (state, ex) => string.Empty); + } +} diff --git a/test/OpenTelemetry.Tests.Stress.Logs/README.md b/test/OpenTelemetry.Tests.Stress.Logs/README.md new file mode 100644 index 00000000000..20c4b87db6e --- /dev/null +++ b/test/OpenTelemetry.Tests.Stress.Logs/README.md @@ -0,0 +1,14 @@ +# OpenTelemetry Stress Tests for Logs + +This is Stress Test specifically for logging, and is +based on the [OpenTelemetry.Tests.Stress](../OpenTelemetry.Tests.Stress/README.md). + +* [Running the stress test](#running-the-stress-test) + +## Running the stress test + +Open a console, run the following command from the current folder: + +```sh +dotnet run --framework net6.0 --configuration Release +``` diff --git a/test/OpenTelemetry.Tests/Context/PropagatorsTest.cs b/test/OpenTelemetry.Tests/Context/PropagatorsTest.cs index c6765568a4e..4f09112e104 100644 --- a/test/OpenTelemetry.Tests/Context/PropagatorsTest.cs +++ b/test/OpenTelemetry.Tests/Context/PropagatorsTest.cs @@ -15,11 +15,9 @@ // using System; -using OpenTelemetry.Context.Propagation; -using OpenTelemetry.Context.Propagation.Tests; using Xunit; -namespace OpenTelemetry.Context.Tests +namespace OpenTelemetry.Context.Propagation.Tests { public class PropagatorsTest : IDisposable { diff --git a/test/OpenTelemetry.Tests/Internal/GuardTest.cs b/test/OpenTelemetry.Tests/Internal/GuardTest.cs index 66807540905..01e23d3d788 100644 --- a/test/OpenTelemetry.Tests/Internal/GuardTest.cs +++ b/test/OpenTelemetry.Tests/Internal/GuardTest.cs @@ -16,11 +16,19 @@ using System; using System.Threading; -using OpenTelemetry.Internal; using Xunit; -namespace OpenTelemetry.Tests.Internal +namespace OpenTelemetry.Internal.Tests { +#pragma warning disable SA1402 // File may only contain a single type +#pragma warning disable SA1649 // File name should match first type name + public class Thing +#pragma warning restore SA1649 // File name should match first type name +#pragma warning restore SA1402 // File may only contain a single type + { + public string Bar { get; set; } + } + public class GuardTest { [Fact] @@ -33,8 +41,20 @@ public void NullTest() Guard.ThrowIfNull("hello"); // Invalid - var ex1 = Assert.Throws(() => Guard.ThrowIfNull(null, "null")); + object potato = null; + var ex1 = Assert.Throws(() => Guard.ThrowIfNull(potato)); Assert.Contains("Must not be null", ex1.Message); + Assert.Equal("potato", ex1.ParamName); + + object @event = null; + var ex2 = Assert.Throws(() => Guard.ThrowIfNull(@event)); + Assert.Contains("Must not be null", ex2.Message); + Assert.Equal("@event", ex2.ParamName); + + Thing thing = null; + var ex3 = Assert.Throws(() => Guard.ThrowIfNull(thing?.Bar)); + Assert.Contains("Must not be null", ex3.Message); + Assert.Equal("thing?.Bar", ex3.ParamName); } [Fact] @@ -47,9 +67,16 @@ public void NullOrEmptyTest() // Invalid var ex1 = Assert.Throws(() => Guard.ThrowIfNullOrEmpty(null)); Assert.Contains("Must not be null or empty", ex1.Message); + Assert.Equal("null", ex1.ParamName); var ex2 = Assert.Throws(() => Guard.ThrowIfNullOrEmpty(string.Empty)); Assert.Contains("Must not be null or empty", ex2.Message); + Assert.Equal("string.Empty", ex2.ParamName); + + var x = string.Empty; + var ex3 = Assert.Throws(() => Guard.ThrowIfNullOrEmpty(x)); + Assert.Contains("Must not be null or empty", ex3.Message); + Assert.Equal("x", ex3.ParamName); } [Fact] @@ -61,12 +88,15 @@ public void NullOrWhitespaceTest() // Invalid var ex1 = Assert.Throws(() => Guard.ThrowIfNullOrWhitespace(null)); Assert.Contains("Must not be null or whitespace", ex1.Message); + Assert.Equal("null", ex1.ParamName); var ex2 = Assert.Throws(() => Guard.ThrowIfNullOrWhitespace(string.Empty)); Assert.Contains("Must not be null or whitespace", ex2.Message); + Assert.Equal("string.Empty", ex2.ParamName); var ex3 = Assert.Throws(() => Guard.ThrowIfNullOrWhitespace(" \t\n\r")); Assert.Contains("Must not be null or whitespace", ex3.Message); + Assert.Equal("\" \\t\\n\\r\"", ex3.ParamName); } [Fact] @@ -80,6 +110,7 @@ public void InvalidTimeoutTest() // Invalid var ex1 = Assert.Throws(() => Guard.ThrowIfInvalidTimeout(-100)); Assert.Contains("Must be non-negative or 'Timeout.Infinite'", ex1.Message); + Assert.Equal("-100", ex1.ParamName); } [Fact] @@ -126,7 +157,7 @@ public void TypeTest() // Invalid var ex1 = Assert.Throws(() => Guard.ThrowIfNotOfType(100)); - Assert.Equal("Cannot cast 'N/A' from 'Int32' to 'Double'", ex1.Message); + Assert.Equal("Cannot cast '100' from 'Int32' to 'Double'", ex1.Message); } [Fact] @@ -138,6 +169,7 @@ public void ZeroTest() // Invalid var ex1 = Assert.Throws(() => Guard.ThrowIfZero(0)); Assert.Contains("Must not be zero", ex1.Message); + Assert.Equal("0", ex1.ParamName); } } } diff --git a/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs b/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs index 2d75c883ac5..bd75f35d2b0 100644 --- a/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs +++ b/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs @@ -520,6 +520,48 @@ public void ViewToDropSingleInstrument() Assert.Equal("counterInteresting", metric.Name); } + [Fact] + public void ViewToDropSingleInstrumentObservableCounter() + { + using var meter = new Meter(Utils.GetCurrentMethodName()); + var exportedItems = new List(); + using var meterProvider = Sdk.CreateMeterProviderBuilder() + .AddMeter(meter.Name) + .AddView("observableCounterNotInteresting", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) + .AddInMemoryExporter(exportedItems) + .Build(); + + // Expecting one metric stream. + meter.CreateObservableCounter("observableCounterNotInteresting", () => { return 10; }, "ms"); + meter.CreateObservableCounter("observableCounterInteresting", () => { return 10; }, "ms"); + + meterProvider.ForceFlush(MaxTimeToAllowForFlush); + Assert.Single(exportedItems); + var metric = exportedItems[0]; + Assert.Equal("observableCounterInteresting", metric.Name); + } + + [Fact] + public void ViewToDropSingleInstrumentObservableGauge() + { + using var meter = new Meter(Utils.GetCurrentMethodName()); + var exportedItems = new List(); + using var meterProvider = Sdk.CreateMeterProviderBuilder() + .AddMeter(meter.Name) + .AddView("observableGaugeNotInteresting", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) + .AddInMemoryExporter(exportedItems) + .Build(); + + // Expecting one metric stream. + meter.CreateObservableGauge("observableGaugeNotInteresting", () => { return 10; }, "ms"); + meter.CreateObservableGauge("observableGaugeInteresting", () => { return 10; }, "ms"); + + meterProvider.ForceFlush(MaxTimeToAllowForFlush); + Assert.Single(exportedItems); + var metric = exportedItems[0]; + Assert.Equal("observableGaugeInteresting", metric.Name); + } + [Fact] public void ViewToDropMultipleInstruments() { diff --git a/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs b/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs index bb5dfdb8feb..67afcbb57b8 100644 --- a/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs +++ b/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs @@ -35,37 +35,35 @@ public static void MethodsAreImplementedConsistentlyWithTheirAttributes(EventSou private static void VerifyMethodImplementation(EventSource eventSource, MethodInfo eventMethod) { - using (var listener = new TestEventListener()) + using var listener = new TestEventListener(); + listener.EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All); + try { - listener.EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All); - try - { - object[] eventArguments = GenerateEventArguments(eventMethod); - eventMethod.Invoke(eventSource, eventArguments); + object[] eventArguments = GenerateEventArguments(eventMethod); + eventMethod.Invoke(eventSource, eventArguments); - EventWrittenEventArgs actualEvent = null; + EventWrittenEventArgs actualEvent = null; - actualEvent = listener.Messages.First(q => q.EventName == eventMethod.Name); + actualEvent = listener.Messages.First(q => q.EventName == eventMethod.Name); - VerifyEventId(eventMethod, actualEvent); - VerifyEventLevel(eventMethod, actualEvent); + VerifyEventId(eventMethod, actualEvent); + VerifyEventLevel(eventMethod, actualEvent); - if (eventMethod.Name != "ExporterErrorResult") - { - VerifyEventMessage(eventMethod, actualEvent, eventArguments); - } - } - catch (Exception e) - { - var name = eventMethod.DeclaringType.Name + "." + eventMethod.Name; - - throw new Exception("Method '" + name + "' is implemented incorrectly.", e); - } - finally + if (eventMethod.Name != "ExporterErrorResult") { - listener.ClearMessages(); + VerifyEventMessage(eventMethod, actualEvent, eventArguments); } } + catch (Exception e) + { + var name = eventMethod.DeclaringType.Name + "." + eventMethod.Name; + + throw new Exception("Method '" + name + "' is implemented incorrectly.", e); + } + finally + { + listener.ClearMessages(); + } } private static object[] GenerateEventArguments(MethodInfo eventMethod) diff --git a/test/OpenTelemetry.Tests/Shared/InMemoryEventListener.cs b/test/OpenTelemetry.Tests/Shared/InMemoryEventListener.cs index 05224ee38ab..dfaf067fe63 100644 --- a/test/OpenTelemetry.Tests/Shared/InMemoryEventListener.cs +++ b/test/OpenTelemetry.Tests/Shared/InMemoryEventListener.cs @@ -21,7 +21,7 @@ namespace OpenTelemetry.Tests { internal class InMemoryEventListener : EventListener { - public ConcurrentQueue Events = new ConcurrentQueue(); + public ConcurrentQueue Events = new(); public InMemoryEventListener(EventSource eventSource, EventLevel minLevel = EventLevel.Verbose) { diff --git a/test/OpenTelemetry.Tests/Shared/TestEventListener.cs b/test/OpenTelemetry.Tests/Shared/TestEventListener.cs index caa1e7c6e44..9c6ffc3e562 100644 --- a/test/OpenTelemetry.Tests/Shared/TestEventListener.cs +++ b/test/OpenTelemetry.Tests/Shared/TestEventListener.cs @@ -92,10 +92,7 @@ protected override void OnEventSourceCreated(EventSource eventSource) { // Check for null because this method is called by the base class constror before we can initialize it Action callback = this.OnOnEventSourceCreated; - if (callback != null) - { - callback(eventSource); - } + callback?.Invoke(eventSource); } } }