From 6e6afdbc3614cfc52d20825a25f06bd80b5ba64e Mon Sep 17 00:00:00 2001 From: Michael Maxwell Date: Mon, 18 Oct 2021 10:29:54 -0700 Subject: [PATCH] Identified all exception throws in code base (#2416) --- src/OpenTelemetry.Api/Baggage.cs | 6 +- .../Propagation/CompositeTextMapPropagator.cs | 5 +- .../Propagation/TraceContextPropagator.cs | 2 +- .../Context/RuntimeContext.cs | 74 +++----- .../Internal/EnumerationHelper.cs | 1 + src/OpenTelemetry.Api/Internal/Guard.cs | 171 ++++++++++++++++++ .../OpenTelemetry.Api.csproj | 4 + src/OpenTelemetry.Api/Trace/SpanAttributes.cs | 12 +- .../ConsoleExporterHelperExtensions.cs | 6 +- .../ConsoleExporterLoggingExtensions.cs | 6 +- .../ConsoleExporterMetricsExtensions.cs | 6 +- .../InMemoryExporterHelperExtensions.cs | 13 +- .../InMemoryExporterLoggingExtensions.cs | 13 +- .../InMemoryExporterMetricsExtensions.cs | 13 +- .../ApacheThrift/Protocol/TProtocol.cs | 10 +- .../ApacheThrift/TBaseClient.cs | 5 +- .../Implementation/Batch.cs | 5 +- .../Implementation/BufferWriter.cs | 6 +- .../JaegerThriftClientTransport.cs | 4 +- .../JaegerExporter.cs | 11 +- .../JaegerExporterHelperExtensions.cs | 6 +- .../ExportClient/BaseOtlpGrpcExportClient.cs | 11 +- .../OtlpMetricExporterExtensions.cs | 6 +- .../OtlpTraceExporterHelperExtensions.cs | 6 +- .../PrometheusExporterMetricsHttpServer.cs | 4 +- ...sExporterMeterProviderBuilderExtensions.cs | 6 +- .../ZPagesExporter.cs | 6 +- .../ZPagesExporterHelperExtensions.cs | 6 +- .../ZPagesExporterStatsHttpServer.cs | 5 +- .../Implementation/ZipkinSpan.cs | 12 +- .../ZipkinExporter.cs | 5 +- .../ZipkinExporterHelperExtensions.cs | 6 +- .../TracerProviderBuilderHosting.cs | 10 +- .../OpenTelemetryServicesExtensions.cs | 17 +- .../TelemetryHttpModuleOptions.cs | 8 +- .../Implementation/HttpInListener.cs | 5 +- .../TracerProviderBuilderExtensions.cs | 6 +- .../Implementation/HttpInListener.cs | 5 +- .../MeterProviderBuilderExtensions.cs | 7 +- .../TracerProviderBuilderExtensions.cs | 6 +- .../TracerProviderBuilderExtensions.cs | 6 +- .../MeterProviderBuilderExtensions.cs | 7 +- .../TracerProviderBuilderExtensions.cs | 8 +- .../TracerProviderBuilderExtensions.cs | 6 +- .../StackExchangeRedisCallsInstrumentation.cs | 6 +- .../TracerProviderBuilderExtensions.cs | 44 +++-- .../ScopeManagerShim.cs | 10 +- .../SpanBuilderShim.cs | 73 +++----- .../SpanContextShim.cs | 2 +- .../SpanShim.cs | 83 +++------ .../TracerShim.cs | 48 ++--- src/OpenTelemetry/BaseExportProcessor.cs | 4 +- src/OpenTelemetry/BaseExporter.cs | 7 +- src/OpenTelemetry/BaseProcessor.cs | 14 +- src/OpenTelemetry/Batch.cs | 10 +- src/OpenTelemetry/BatchExportProcessor.cs | 23 +-- src/OpenTelemetry/CompositeProcessor.cs | 13 +- .../DiagnosticSourceListener.cs | 5 +- .../DiagnosticSourceSubscriber.cs | 5 +- .../PropertyFetcher.cs | 5 +- src/OpenTelemetry/Internal/CircularBuffer.cs | 16 +- src/OpenTelemetry/Internal/PooledList.cs | 7 +- .../Internal/SelfDiagnosticsEventListener.cs | 4 +- src/OpenTelemetry/Logs/OpenTelemetryLogger.cs | 8 +- .../Logs/OpenTelemetryLoggerOptions.cs | 10 +- .../Logs/OpenTelemetryLoggerProvider.cs | 10 +- .../Logs/OpenTelemetryLoggingExtensions.cs | 6 +- .../Metrics/BaseExportingMetricReader.cs | 5 +- src/OpenTelemetry/Metrics/BatchMetricPoint.cs | 5 +- .../Metrics/CompositeMetricReader.cs | 14 +- .../Metrics/MeterProviderExtensions.cs | 27 +-- src/OpenTelemetry/Metrics/MeterProviderSdk.cs | 5 +- src/OpenTelemetry/Metrics/MetricReader.cs | 33 +--- .../Metrics/PeriodicExportingMetricReader.cs | 2 +- .../Metrics/ThreadStaticStorage.cs | 9 +- src/OpenTelemetry/Resources/Resource.cs | 76 ++++---- .../Resources/ResourceBuilder.cs | 12 +- .../Resources/ResourceBuilderExtensions.cs | 6 +- src/OpenTelemetry/Trace/ExceptionProcessor.cs | 2 +- src/OpenTelemetry/Trace/ParentBasedSampler.cs | 6 +- .../Trace/TraceIdRatioBasedSampler.cs | 6 +- .../Trace/TracerProviderBuilderBase.cs | 38 ++-- .../Trace/TracerProviderBuilderExtensions.cs | 2 +- .../Trace/TracerProviderExtensions.cs | 37 +--- src/OpenTelemetry/Trace/TracerProviderSdk.cs | 5 +- .../ThriftUdpClientTransportTests.cs | 2 +- .../ScopeManagerShimTests.cs | 2 +- .../SpanShimTests.cs | 12 +- .../TracerShimTests.cs | 2 +- test/OpenTelemetry.Tests/BaggageTests.cs | 2 +- .../Context/RuntimeContextTest.cs | 2 +- .../OpenTelemetry.Tests/Internal/GuardTest.cs | 143 +++++++++++++++ 92 files changed, 741 insertions(+), 670 deletions(-) create mode 100644 src/OpenTelemetry.Api/Internal/Guard.cs create mode 100644 test/OpenTelemetry.Tests/Internal/GuardTest.cs diff --git a/src/OpenTelemetry.Api/Baggage.cs b/src/OpenTelemetry.Api/Baggage.cs index ac80a5250b5..ce1b4d4c1ce 100644 --- a/src/OpenTelemetry.Api/Baggage.cs +++ b/src/OpenTelemetry.Api/Baggage.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Linq; using OpenTelemetry.Context; +using OpenTelemetry.Internal; namespace OpenTelemetry { @@ -238,10 +239,7 @@ public IReadOnlyDictionary GetBaggage() /// Baggage item or if nothing was found. public string GetBaggage(string name) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentNullException(nameof(name)); - } + Guard.NullOrEmpty(name, nameof(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 35e7d972113..7897ff8210c 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/CompositeTextMapPropagator.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; +using OpenTelemetry.Internal; namespace OpenTelemetry.Context.Propagation { @@ -34,7 +35,9 @@ public class CompositeTextMapPropagator : TextMapPropagator /// List of wire context propagator. public CompositeTextMapPropagator(IEnumerable propagators) { - this.propagators = new List(propagators ?? throw new ArgumentNullException(nameof(propagators))); + Guard.Null(propagators, nameof(propagators)); + + this.propagators = new List(propagators); } /// diff --git a/src/OpenTelemetry.Api/Context/Propagation/TraceContextPropagator.cs b/src/OpenTelemetry.Api/Context/Propagation/TraceContextPropagator.cs index 58b9804a261..fc18d3a7851 100644 --- a/src/OpenTelemetry.Api/Context/Propagation/TraceContextPropagator.cs +++ b/src/OpenTelemetry.Api/Context/Propagation/TraceContextPropagator.cs @@ -330,7 +330,7 @@ private static byte HexCharToByte(char c) return (byte)(c - 'a' + 10); } - throw new ArgumentOutOfRangeException(nameof(c), c, $"Invalid character: {c}."); + throw new ArgumentOutOfRangeException(nameof(c), c, "Must be within: [0-9] or [a-f]"); } private static bool ValidateKey(ReadOnlySpan key) diff --git a/src/OpenTelemetry.Api/Context/RuntimeContext.cs b/src/OpenTelemetry.Api/Context/RuntimeContext.cs index 3b7308adfca..1520f64bbdd 100644 --- a/src/OpenTelemetry.Api/Context/RuntimeContext.cs +++ b/src/OpenTelemetry.Api/Context/RuntimeContext.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Concurrent; using System.Runtime.CompilerServices; +using OpenTelemetry.Internal; namespace OpenTelemetry.Context { @@ -40,16 +41,13 @@ public static class RuntimeContext /// The slot registered. public static RuntimeContextSlot RegisterSlot(string slotName) { - if (string.IsNullOrEmpty(slotName)) - { - throw new ArgumentException($"{nameof(slotName)} cannot be null or empty string."); - } + Guard.NullOrEmpty(slotName, nameof(slotName)); lock (Slots) { if (Slots.ContainsKey(slotName)) { - throw new InvalidOperationException($"The context slot {slotName} is already registered."); + throw new InvalidOperationException($"Context slot already registered: '{slotName}'"); } var type = ContextSlotType.MakeGenericType(typeof(T)); @@ -68,17 +66,10 @@ public static RuntimeContextSlot RegisterSlot(string slotName) /// The slot previously registered. public static RuntimeContextSlot GetSlot(string slotName) { - if (string.IsNullOrEmpty(slotName)) - { - throw new ArgumentException($"{nameof(slotName)} cannot be null or empty string."); - } - - if (!Slots.TryGetValue(slotName, out var slot)) - { - throw new ArgumentException($"The context slot {slotName} could not be found."); - } - - return slot as RuntimeContextSlot ?? throw new ArgumentException($"The context slot {slotName} cannot be cast as {typeof(RuntimeContextSlot)}."); + Guard.NullOrEmpty(slotName, nameof(slotName)); + var slot = GuardNotFound(slotName); + var contextSlot = Guard.Type>(slot, nameof(slot)); + return contextSlot; } /* @@ -136,23 +127,10 @@ public static T GetValue(string slotName) /// The value to be set. public static void SetValue(string slotName, object value) { - if (string.IsNullOrEmpty(slotName)) - { - throw new ArgumentException($"{nameof(slotName)} cannot be null or empty string."); - } - - if (!Slots.TryGetValue(slotName, out var slot)) - { - throw new ArgumentException($"The context slot {slotName} could not be found."); - } - - if (slot is IRuntimeContextSlotValueAccessor runtimeContextSlotValueAccessor) - { - runtimeContextSlotValueAccessor.Value = value; - return; - } - - throw new NotSupportedException($"The context slot {slotName} value cannot be accessed as an object."); + Guard.NullOrEmpty(slotName, nameof(slotName)); + var slot = GuardNotFound(slotName); + var runtimeContextSlotValueAccessor = Guard.Type(slot, nameof(slot)); + runtimeContextSlotValueAccessor.Value = value; } /// @@ -162,22 +140,10 @@ public static void SetValue(string slotName, object value) /// The value retrieved from the context slot. public static object GetValue(string slotName) { - if (string.IsNullOrEmpty(slotName)) - { - throw new ArgumentException($"{nameof(slotName)} cannot be null or empty string."); - } - - if (!Slots.TryGetValue(slotName, out var slot)) - { - throw new ArgumentException($"The context slot {slotName} could not be found."); - } - - if (slot is IRuntimeContextSlotValueAccessor runtimeContextSlotValueAccessor) - { - return runtimeContextSlotValueAccessor.Value; - } - - throw new NotSupportedException($"The context slot {slotName} value cannot be accessed as an object."); + Guard.NullOrEmpty(slotName, nameof(slotName)); + var slot = GuardNotFound(slotName); + var runtimeContextSlotValueAccessor = Guard.Type(slot, nameof(slot)); + return runtimeContextSlotValueAccessor.Value; } // For testing purpose @@ -185,5 +151,15 @@ internal static void Clear() { Slots.Clear(); } + + private static object GuardNotFound(string slotName) + { + if (!Slots.TryGetValue(slotName, out var slot)) + { + throw new ArgumentException($"Context slot not found: '{slotName}'"); + } + + return slot; + } } } diff --git a/src/OpenTelemetry.Api/Internal/EnumerationHelper.cs b/src/OpenTelemetry.Api/Internal/EnumerationHelper.cs index 0c9abc43c95..319d87f2d26 100644 --- a/src/OpenTelemetry.Api/Internal/EnumerationHelper.cs +++ b/src/OpenTelemetry.Api/Internal/EnumerationHelper.cs @@ -14,6 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // + using System; using System.Collections; using System.Collections.Generic; diff --git a/src/OpenTelemetry.Api/Internal/Guard.cs b/src/OpenTelemetry.Api/Internal/Guard.cs new file mode 100644 index 00000000000..73f5caa261f --- /dev/null +++ b/src/OpenTelemetry.Api/Internal/Guard.cs @@ -0,0 +1,171 @@ +// +// 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; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace OpenTelemetry.Internal +{ + /// + /// Methods for guarding against exception throwing values. + /// + public static class Guard + { + private const string DefaultParamName = "N/A"; + + /// + /// Throw an exception if the value is null. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Null(object value, string paramName = DefaultParamName) + { + if (value is null) + { + throw new ArgumentNullException(paramName, "Must not be null"); + } + } + + /// + /// Throw an exception if the value is null or empty. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void NullOrEmpty(string value, string paramName = DefaultParamName) + { + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentException("Must not be null or empty", paramName); + } + } + + /// + /// Throw an exception if the value is null or whitespace. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void NullOrWhitespace(string value, string paramName = DefaultParamName) + { + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Must not be null or whitespace", paramName); + } + } + + /// + /// Throw an exception if the value is zero. + /// + /// The value to check. + /// The message to use in the thrown exception. + /// The parameter name to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Zero(int value, string message = "Must not be zero", string paramName = DefaultParamName) + { + if (value == 0) + { + throw new ArgumentException(message, paramName); + } + } + + /// + /// Throw an exception if the value is not considered a valid timeout. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void InvalidTimeout(int value, string paramName = DefaultParamName) + { + Range(value, paramName, min: Timeout.Infinite, message: $"Must be non-negative or '{nameof(Timeout)}.{nameof(Timeout.Infinite)}'"); + } + + /// + /// Throw an exception if the value is not within the given range. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + /// The inclusive lower bound. + /// The inclusive upper bound. + /// The name of the lower bound. + /// The name of the upper bound. + /// An optional custom message to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Range(int value, string paramName = DefaultParamName, 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); + } + + /// + /// Throw an exception if the value is not within the given range. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + /// The inclusive lower bound. + /// The inclusive upper bound. + /// The name of the lower bound. + /// The name of the upper bound. + /// An optional custom message to use in the thrown exception. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Range(double value, string paramName = DefaultParamName, 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); + } + + /// + /// Throw an exception if the value is not within the given range. + /// + /// The value to check. + /// The parameter name to use in the thrown exception. + /// The type to attempt to convert to. + /// The value casted to the specified type. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Type(object value, string paramName = DefaultParamName) + { + if (value is not T result) + { + throw new InvalidCastException($"Cannot cast '{paramName}' from '{value.GetType().Name}' to '{typeof(T).Name}'"); + } + + return result; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Range(T value, string paramName, T min, T max, string minName, string maxName, string message) + where T : IComparable + { + if (value.CompareTo(min) < 0 || value.CompareTo(max) > 0) + { + var minMessage = minName != null ? $": {minName}" : string.Empty; + var maxMessage = maxName != null ? $": {maxName}" : string.Empty; + var exMessage = message ?? $"Must be in the range: [{min}{minMessage}, {max}{maxMessage}]"; + throw new ArgumentOutOfRangeException(paramName, value, exMessage); + } + } + } +} diff --git a/src/OpenTelemetry.Api/OpenTelemetry.Api.csproj b/src/OpenTelemetry.Api/OpenTelemetry.Api.csproj index 76ed1bb9395..f48c0e1b22b 100644 --- a/src/OpenTelemetry.Api/OpenTelemetry.Api.csproj +++ b/src/OpenTelemetry.Api/OpenTelemetry.Api.csproj @@ -19,4 +19,8 @@ + + + + diff --git a/src/OpenTelemetry.Api/Trace/SpanAttributes.cs b/src/OpenTelemetry.Api/Trace/SpanAttributes.cs index 3722651e9e2..14d2a481fa1 100644 --- a/src/OpenTelemetry.Api/Trace/SpanAttributes.cs +++ b/src/OpenTelemetry.Api/Trace/SpanAttributes.cs @@ -14,9 +14,9 @@ // limitations under the License. // -using System; using System.Collections.Generic; using System.Diagnostics; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -41,10 +41,7 @@ public SpanAttributes() public SpanAttributes(IEnumerable> attributes) : this() { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + Guard.Null(attributes, nameof(attributes)); foreach (KeyValuePair kvp in attributes) { @@ -136,10 +133,7 @@ public void Add(string key, double[] values) private void AddInternal(string key, object value) { - if (key == null) - { - throw new ArgumentNullException(key); - } + Guard.Null(key, nameof(key)); this.Attributes[key] = value; } diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs index a73e9a4e76d..db7413bd261 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterHelperExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -30,10 +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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs b/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs index acd1b29430b..eee27b3820e 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Logs { @@ -29,10 +30,7 @@ public static class ConsoleExporterLoggingExtensions /// The instance of to chain the calls. public static OpenTelemetryLoggerOptions AddConsoleExporter(this OpenTelemetryLoggerOptions loggerOptions, Action configure = null) { - if (loggerOptions == null) - { - throw new ArgumentNullException(nameof(loggerOptions)); - } + Guard.Null(loggerOptions, nameof(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 73576264287..cd56b910dc3 100644 --- a/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs +++ b/src/OpenTelemetry.Exporter.Console/ConsoleExporterMetricsExtensions.cs @@ -17,6 +17,7 @@ using System; using System.Threading; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -31,10 +32,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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(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 47babe1f435..7fffc434464 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterHelperExtensions.cs @@ -14,10 +14,10 @@ // limitations under the License. // -using System; using System.Collections.Generic; using System.Diagnostics; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -32,15 +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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (exportedItems == null) - { - throw new ArgumentNullException(nameof(exportedItems)); - } + Guard.Null(builder, nameof(builder)); + Guard.Null(exportedItems, nameof(exportedItems)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs index c500949d602..e7ab23e8b1f 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterLoggingExtensions.cs @@ -14,9 +14,9 @@ // limitations under the License. // -using System; using System.Collections.Generic; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Logs { @@ -24,15 +24,8 @@ public static class InMemoryExporterLoggingExtensions { public static OpenTelemetryLoggerOptions AddInMemoryExporter(this OpenTelemetryLoggerOptions loggerOptions, ICollection exportedItems) { - if (loggerOptions == null) - { - throw new ArgumentNullException(nameof(loggerOptions)); - } - - if (exportedItems == null) - { - throw new ArgumentNullException(nameof(exportedItems)); - } + Guard.Null(loggerOptions, nameof(loggerOptions)); + Guard.Null(exportedItems, nameof(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 77ca217bb68..64d56303815 100644 --- a/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs +++ b/src/OpenTelemetry.Exporter.InMemory/InMemoryExporterMetricsExtensions.cs @@ -14,9 +14,9 @@ // limitations under the License. // -using System; using System.Collections.Generic; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -30,15 +30,8 @@ public static class InMemoryExporterMetricsExtensions /// The instance of to chain the calls. public static MeterProviderBuilder AddInMemoryExporter(this MeterProviderBuilder builder, ICollection exportedItems) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (exportedItems == null) - { - throw new ArgumentNullException(nameof(exportedItems)); - } + Guard.Null(builder, nameof(builder)); + Guard.Null(exportedItems, nameof(exportedItems)); return builder.AddReader(new BaseExportingMetricReader(new InMemoryExporter(exportedItems))); } diff --git a/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/Protocol/TProtocol.cs b/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/Protocol/TProtocol.cs index 86bc82eb231..14f4f43327e 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/Protocol/TProtocol.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/Protocol/TProtocol.cs @@ -52,14 +52,12 @@ public void Dispose() public void IncrementRecursionDepth() { - if (RecursionDepth < RecursionLimit) + if (RecursionDepth >= RecursionLimit) { - ++RecursionDepth; - } - else - { - throw new TProtocolException(TProtocolException.DEPTH_LIMIT, "Depth limit exceeded"); + throw new TProtocolException(TProtocolException.DEPTH_LIMIT, $"Depth of recursion exceeded the limit: {RecursionLimit}"); } + + ++RecursionDepth; } public void DecrementRecursionDepth() diff --git a/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/TBaseClient.cs b/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/TBaseClient.cs index bcbd524b4b7..0b3d94eb7ad 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/TBaseClient.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/ApacheThrift/TBaseClient.cs @@ -18,6 +18,7 @@ // under the License. using System; +using OpenTelemetry.Internal; using Thrift.Protocol; namespace Thrift @@ -37,7 +38,9 @@ internal abstract class TBaseClient protected TBaseClient(TProtocol outputProtocol) { - _outputProtocol = outputProtocol ?? throw new ArgumentNullException(nameof(outputProtocol)); + Guard.Null(outputProtocol, nameof(outputProtocol)); + + _outputProtocol = outputProtocol; } public TProtocol OutputProtocol => _outputProtocol; diff --git a/src/OpenTelemetry.Exporter.Jaeger/Implementation/Batch.cs b/src/OpenTelemetry.Exporter.Jaeger/Implementation/Batch.cs index 36965771c09..64872199d1d 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/Implementation/Batch.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/Implementation/Batch.cs @@ -14,7 +14,6 @@ // limitations under the License. // -using System; using System.Runtime.CompilerServices; using System.Text; using OpenTelemetry.Internal; @@ -29,7 +28,9 @@ internal class Batch public Batch(Process process) { - this.Process = process ?? throw new ArgumentNullException(nameof(process)); + Guard.Null(process, nameof(process)); + + this.Process = process; this.spanMessages = PooledList.Create(); } diff --git a/src/OpenTelemetry.Exporter.Jaeger/Implementation/BufferWriter.cs b/src/OpenTelemetry.Exporter.Jaeger/Implementation/BufferWriter.cs index cc32111b6fe..8e034e77f89 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/Implementation/BufferWriter.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/Implementation/BufferWriter.cs @@ -14,6 +14,7 @@ // limitations under the License. // using System; +using OpenTelemetry.Internal; namespace OpenTelemetry.Exporter.Jaeger.Implementation { @@ -23,10 +24,7 @@ internal sealed class BufferWriter public BufferWriter(int initialCapacity) { - if (initialCapacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(initialCapacity), initialCapacity, "initialCapacity should be non-negative."); - } + Guard.Range(initialCapacity, nameof(initialCapacity), min: 0); this.Buffer = new byte[initialCapacity]; } diff --git a/src/OpenTelemetry.Exporter.Jaeger/Implementation/JaegerThriftClientTransport.cs b/src/OpenTelemetry.Exporter.Jaeger/Implementation/JaegerThriftClientTransport.cs index 4d30cbfacad..ed6364cbb2d 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/Implementation/JaegerThriftClientTransport.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/Implementation/JaegerThriftClientTransport.cs @@ -64,11 +64,11 @@ public override int Flush() } catch (SocketException se) { - throw new TTransportException(TTransportException.ExceptionType.Unknown, $"Cannot flush because of socket exception. UDP Packet size was {buffer.Count}. Exception message: {se.Message}"); + throw new TTransportException(TTransportException.ExceptionType.Unknown, $"Cannot flush due to a '{nameof(SocketException)}' - UDP Packet size: '{buffer.Count}'", se); } catch (Exception e) { - throw new TTransportException(TTransportException.ExceptionType.Unknown, $"Cannot flush closed transport. {e.Message}"); + throw new TTransportException(TTransportException.ExceptionType.Unknown, "Cannot flush closed transport", e); } finally { diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs index 5d2a888c8ac..51590cd6e53 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporter.cs @@ -20,6 +20,7 @@ using System.Linq; using System.Runtime.CompilerServices; using OpenTelemetry.Exporter.Jaeger.Implementation; +using OpenTelemetry.Internal; using OpenTelemetry.Resources; using Thrift.Protocol; using Thrift.Transport; @@ -45,10 +46,7 @@ public JaegerExporter(JaegerExporterOptions options) internal JaegerExporter(JaegerExporterOptions options, TTransport clientTransport = null) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + Guard.Null(options, nameof(options)); this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0) ? JaegerExporterOptions.DefaultMaxPayloadSizeInBytes : options.MaxPayloadSizeInBytes.Value; this.protocolFactory = new TCompactProtocol.Factory(); @@ -95,10 +93,7 @@ public override ExportResult Export(in Batch activityBatch) internal void SetResourceAndInitializeBatch(Resource resource) { - if (resource is null) - { - throw new ArgumentNullException(nameof(resource)); - } + Guard.Null(resource, nameof(resource)); var process = this.Process; diff --git a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs index 827b35047b7..74e350f8c8f 100644 --- a/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Jaeger/JaegerExporterHelperExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -33,10 +34,7 @@ public static class JaegerExporterHelperExtensions [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] public static TracerProviderBuilder AddJaegerExporter(this TracerProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs index c3dc00c19c5..aee71c7fd91 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs @@ -14,13 +14,13 @@ // limitations under the License. // -using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; #if NETSTANDARD2_1 || NET5_0_OR_GREATER using Grpc.Net.Client; #endif +using OpenTelemetry.Internal; namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient { @@ -30,13 +30,10 @@ internal abstract class BaseOtlpGrpcExportClient : IExportClientThe instance of to chain the calls. public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs index ebb9e8f8d8f..3072c1bdb48 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpTraceExporterHelperExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -32,10 +33,7 @@ public static class OtlpTraceExporterHelperExtensions /// The instance of to chain the calls. public static TracerProviderBuilder AddOtlpExporter(this TracerProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMetricsHttpServer.cs b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMetricsHttpServer.cs index 72fc61dbca7..f4b562aedbc 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMetricsHttpServer.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/Implementation/PrometheusExporterMetricsHttpServer.cs @@ -18,6 +18,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; +using OpenTelemetry.Internal; namespace OpenTelemetry.Exporter.Prometheus { @@ -39,8 +40,9 @@ internal sealed class PrometheusExporterMetricsHttpServer : IDisposable /// The instance. public PrometheusExporterMetricsHttpServer(PrometheusExporter exporter) { - this.exporter = exporter ?? throw new ArgumentNullException(nameof(exporter)); + Guard.Null(exporter, nameof(exporter)); + this.exporter = exporter; if ((exporter.Options.HttpListenerPrefixes?.Count ?? 0) <= 0) { throw new ArgumentException("No HttpListenerPrefixes were specified on PrometheusExporterOptions."); diff --git a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs index 3be9b5eadb3..c2e6e26515b 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/PrometheusExporterMeterProviderBuilderExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -29,10 +30,7 @@ public static class PrometheusExporterMeterProviderBuilderExtensions /// The instance of to chain the calls. public static MeterProviderBuilder AddPrometheusExporter(this MeterProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) { diff --git a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs index 58db8eb0f10..a7b2eba27b9 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporter.cs @@ -14,10 +14,10 @@ // limitations under the License. // -using System; using System.Diagnostics; using System.Timers; using OpenTelemetry.Exporter.ZPages.Implementation; +using OpenTelemetry.Internal; using Timer = System.Timers.Timer; namespace OpenTelemetry.Exporter.ZPages @@ -37,7 +37,9 @@ public class ZPagesExporter : BaseExporter /// Options for the exporter. public ZPagesExporter(ZPagesExporterOptions options) { - ZPagesActivityTracker.RetentionTime = options?.RetentionTime ?? throw new ArgumentNullException(nameof(options)); + Guard.Null(options?.RetentionTime, $"{nameof(options)}?.{nameof(options.RetentionTime)}"); + + ZPagesActivityTracker.RetentionTime = options.RetentionTime; this.Options = options; diff --git a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs index 546490010b8..a27e956eaef 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterHelperExtensions.cs @@ -17,6 +17,7 @@ using System; using OpenTelemetry.Exporter.ZPages; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -36,10 +37,7 @@ public static TracerProviderBuilder AddZPagesExporter( this TracerProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(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 5d9d8d988cf..6b8ab4c1ed5 100644 --- a/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs +++ b/src/OpenTelemetry.Exporter.ZPages/ZPagesExporterStatsHttpServer.cs @@ -21,6 +21,7 @@ using System.Threading; using System.Threading.Tasks; using OpenTelemetry.Exporter.ZPages.Implementation; +using OpenTelemetry.Internal; namespace OpenTelemetry.Exporter.ZPages { @@ -41,7 +42,9 @@ public class ZPagesExporterStatsHttpServer : IDisposable /// The instance. public ZPagesExporterStatsHttpServer(ZPagesExporter exporter) { - this.httpListener.Prefixes.Add(exporter?.Options?.Url ?? throw new ArgumentNullException(nameof(exporter))); + Guard.Null(exporter?.Options?.Url, $"{nameof(exporter)}?.{nameof(exporter.Options)}?.{nameof(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 160d646f4c5..42b9914249a 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs @@ -14,7 +14,6 @@ // limitations under the License. // -using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -42,15 +41,8 @@ public ZipkinSpan( bool? debug, bool? shared) { - if (string.IsNullOrWhiteSpace(traceId)) - { - throw new ArgumentNullException(nameof(traceId)); - } - - if (string.IsNullOrWhiteSpace(id)) - { - throw new ArgumentNullException(nameof(id)); - } + Guard.NullOrWhitespace(traceId, nameof(traceId)); + Guard.NullOrWhitespace(id, nameof(id)); this.TraceId = traceId; this.ParentId = parentId; diff --git a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs index d07767842ba..3f7330f05f6 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporter.cs @@ -27,6 +27,7 @@ using System.Threading; using System.Threading.Tasks; using OpenTelemetry.Exporter.Zipkin.Implementation; +using OpenTelemetry.Internal; using OpenTelemetry.Resources; namespace OpenTelemetry.Exporter @@ -47,7 +48,9 @@ public class ZipkinExporter : BaseExporter /// Http client to use to upload telemetry. public ZipkinExporter(ZipkinExporterOptions options, HttpClient client = null) { - this.options = options ?? throw new ArgumentNullException(nameof(options)); + Guard.Null(options, nameof(options)); + + this.options = options; this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0) ? ZipkinExporterOptions.DefaultMaxPayloadSizeInBytes : options.MaxPayloadSizeInBytes.Value; this.httpClient = client ?? new HttpClient(); } diff --git a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs index 78c8ca3adcf..dc243aa3467 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterHelperExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Exporter; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -33,10 +34,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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Extensions.Hosting/Implementation/TracerProviderBuilderHosting.cs b/src/OpenTelemetry.Extensions.Hosting/Implementation/TracerProviderBuilderHosting.cs index f56e9d12aea..6c1dd460dc0 100644 --- a/src/OpenTelemetry.Extensions.Hosting/Implementation/TracerProviderBuilderHosting.cs +++ b/src/OpenTelemetry.Extensions.Hosting/Implementation/TracerProviderBuilderHosting.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -29,17 +30,16 @@ internal sealed class TracerProviderBuilderHosting : TracerProviderBuilderBase, public TracerProviderBuilderHosting(IServiceCollection services) { - this.Services = services ?? throw new ArgumentNullException(nameof(services)); + Guard.Null(services, nameof(services)); + + this.Services = services; } public IServiceCollection Services { get; } public TracerProviderBuilder Configure(Action configure) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + Guard.Null(configure, nameof(configure)); this.configurationActions.Add(configure); return this; diff --git a/src/OpenTelemetry.Extensions.Hosting/OpenTelemetryServicesExtensions.cs b/src/OpenTelemetry.Extensions.Hosting/OpenTelemetryServicesExtensions.cs index 7f180613c27..169d1af16af 100644 --- a/src/OpenTelemetry.Extensions.Hosting/OpenTelemetryServicesExtensions.cs +++ b/src/OpenTelemetry.Extensions.Hosting/OpenTelemetryServicesExtensions.cs @@ -18,6 +18,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using OpenTelemetry.Extensions.Hosting.Implementation; +using OpenTelemetry.Internal; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; @@ -46,10 +47,7 @@ public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection /// The so that additional calls can be chained. public static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Action configure) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + Guard.Null(configure, nameof(configure)); var builder = new TracerProviderBuilderHosting(services); configure(builder); @@ -92,15 +90,8 @@ public static IServiceCollection AddOpenTelemetryMetrics(this IServiceCollection /// The so that additional calls can be chained. private static IServiceCollection AddOpenTelemetryTracing(this IServiceCollection services, Func createTracerProvider) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (createTracerProvider is null) - { - throw new ArgumentNullException(nameof(createTracerProvider)); - } + Guard.Null(services, nameof(services)); + Guard.Null(createTracerProvider, nameof(createTracerProvider)); try { diff --git a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs index 5110bfeb769..2b2b14945cb 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModuleOptions.cs @@ -18,6 +18,7 @@ using System.Diagnostics; using System.Web; using OpenTelemetry.Context.Propagation; +using OpenTelemetry.Internal; namespace OpenTelemetry.Instrumentation.AspNet { @@ -39,7 +40,12 @@ internal TelemetryHttpModuleOptions() public TextMapPropagator TextMapPropagator { get => this.textMapPropagator; - set => this.textMapPropagator = value ?? throw new ArgumentNullException(nameof(value)); + set + { + Guard.Null(value, nameof(value)); + + this.textMapPropagator = value; + } } /// diff --git a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs index 89fd7e55d6e..7d2f4335563 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet/Implementation/HttpInListener.cs @@ -19,6 +19,7 @@ using System.Web; using System.Web.Routing; using OpenTelemetry.Context.Propagation; +using OpenTelemetry.Internal; using OpenTelemetry.Trace; namespace OpenTelemetry.Instrumentation.AspNet.Implementation @@ -31,7 +32,9 @@ internal sealed class HttpInListener : IDisposable public HttpInListener(AspNetInstrumentationOptions options) { - this.options = options ?? throw new ArgumentNullException(nameof(options)); + Guard.Null(options, nameof(options)); + + this.options = options; TelemetryHttpModule.Options.TextMapPropagator = Propagators.DefaultTextMapPropagator; diff --git a/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs index 035b6c9e8da..28f43041e80 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet/TracerProviderBuilderExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Instrumentation.AspNet; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -34,10 +35,7 @@ public static TracerProviderBuilder AddAspNetInstrumentation( this TracerProviderBuilder builder, Action configureAspNetInstrumentationOptions = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); var aspnetOptions = new AspNetInstrumentationOptions(); configureAspNetInstrumentationOptions?.Invoke(aspnetOptions); diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs index e9a44826ee9..1291a63fb0d 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs @@ -25,6 +25,7 @@ using System.Text; using Microsoft.AspNetCore.Http; using OpenTelemetry.Context.Propagation; +using OpenTelemetry.Internal; #if !NETSTANDARD2_0 using OpenTelemetry.Instrumentation.GrpcNetClient; #endif @@ -53,7 +54,9 @@ internal class HttpInListener : ListenerHandler public HttpInListener(AspNetCoreInstrumentationOptions options) : base(DiagnosticSourceName) { - this.options = options ?? throw new ArgumentNullException(nameof(options)); + Guard.Null(options, nameof(options)); + + this.options = options; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The objects should not be disposed.")] diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs index 060fb62b48b..7b813462c0f 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/MeterProviderBuilderExtensions.cs @@ -14,8 +14,8 @@ // limitations under the License. // -using System; using OpenTelemetry.Instrumentation.AspNetCore; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -32,10 +32,7 @@ public static class MeterProviderBuilderExtensions public static MeterProviderBuilder AddAspNetCoreInstrumentation( this MeterProviderBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); // TODO: Implement an IDeferredMeterProviderBuilder diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs index 211a72ce14b..08df61076ab 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/TracerProviderBuilderExtensions.cs @@ -17,6 +17,7 @@ using System; using OpenTelemetry.Instrumentation.AspNetCore; using OpenTelemetry.Instrumentation.AspNetCore.Implementation; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -35,10 +36,7 @@ public static TracerProviderBuilder AddAspNetCoreInstrumentation( this TracerProviderBuilder builder, Action configureAspNetCoreInstrumentationOptions = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { diff --git a/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs index 1da31b89e96..0e09f180e46 100644 --- a/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.GrpcNetClient/TracerProviderBuilderExtensions.cs @@ -17,6 +17,7 @@ using System; using OpenTelemetry.Instrumentation.GrpcNetClient; using OpenTelemetry.Instrumentation.GrpcNetClient.Implementation; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -36,10 +37,7 @@ public static TracerProviderBuilder AddGrpcClientInstrumentation( this TracerProviderBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); var grpcOptions = new GrpcClientInstrumentationOptions(); configure?.Invoke(grpcOptions); diff --git a/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs index 661e8bdf82d..83c8e60ea24 100644 --- a/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/MeterProviderBuilderExtensions.cs @@ -14,8 +14,8 @@ // limitations under the License. // -using System; using OpenTelemetry.Instrumentation.Http; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -32,10 +32,7 @@ public static class MeterProviderBuilderExtensions public static MeterProviderBuilder AddHttpClientInstrumentation( this MeterProviderBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); // TODO: Implement an IDeferredMeterProviderBuilder diff --git a/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs index 6aa9a00ac0c..4716f0a1281 100644 --- a/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs @@ -17,6 +17,9 @@ using System; using OpenTelemetry.Instrumentation.Http; using OpenTelemetry.Instrumentation.Http.Implementation; +#if !NETFRAMEWORK +using OpenTelemetry.Internal; +#endif namespace OpenTelemetry.Trace { @@ -58,10 +61,7 @@ public static TracerProviderBuilder AddHttpClientInstrumentation( this TracerProviderBuilder builder, Action configureHttpClientInstrumentationOptions = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); var httpClientOptions = new HttpClientInstrumentationOptions(); diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs index c7ecae29ede..262bc7d18d1 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/TracerProviderBuilderExtensions.cs @@ -17,6 +17,7 @@ using System; using OpenTelemetry.Instrumentation.SqlClient; using OpenTelemetry.Instrumentation.SqlClient.Implementation; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -35,10 +36,7 @@ public static TracerProviderBuilder AddSqlClientInstrumentation( this TracerProviderBuilder builder, Action configureSqlClientInstrumentationOptions = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(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 5a85e3d416a..72cb7755057 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/StackExchangeRedisCallsInstrumentation.cs @@ -20,6 +20,7 @@ using System.Diagnostics; using System.Threading; using OpenTelemetry.Instrumentation.StackExchangeRedis.Implementation; +using OpenTelemetry.Internal; using OpenTelemetry.Trace; using StackExchange.Redis; using StackExchange.Redis.Profiling; @@ -58,10 +59,7 @@ internal class StackExchangeRedisCallsInstrumentation : IDisposable /// Configuration options for redis instrumentation. public StackExchangeRedisCallsInstrumentation(IConnectionMultiplexer connection, StackExchangeRedisCallsInstrumentationOptions options) { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } + Guard.Null(connection, nameof(connection)); this.options = options ?? new StackExchangeRedisCallsInstrumentationOptions(); diff --git a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs index 78d9d154d95..68d3e30861d 100644 --- a/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.StackExchangeRedis/TracerProviderBuilderExtensions.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.Instrumentation.StackExchangeRedis; +using OpenTelemetry.Internal; using StackExchange.Redis; namespace OpenTelemetry.Trace @@ -42,38 +43,35 @@ public static TracerProviderBuilder AddRedisInstrumentation( IConnectionMultiplexer connection = null, Action configure = null) { - if (builder == null) + Guard.Null(builder, nameof(builder)); + + if (builder is not IDeferredTracerProviderBuilder deferredTracerProviderBuilder) { - throw new ArgumentNullException(nameof(builder)); + if (connection == null) + { + throw new NotSupportedException($"StackExchange.Redis {nameof(IConnectionMultiplexer)} must be supplied when dependency injection is unavailable - to enable dependency injection use the OpenTelemetry.Extensions.Hosting package"); + } + + return AddRedisInstrumentation(builder, connection, new StackExchangeRedisCallsInstrumentationOptions(), configure); } - if (builder is IDeferredTracerProviderBuilder deferredTracerProviderBuilder) + return deferredTracerProviderBuilder.Configure((sp, builder) => { - return deferredTracerProviderBuilder.Configure((sp, builder) => + if (connection == null) { + connection = (IConnectionMultiplexer)sp.GetService(typeof(IConnectionMultiplexer)); if (connection == null) { - connection = (IConnectionMultiplexer)sp.GetService(typeof(IConnectionMultiplexer)); - if (connection == null) - { - throw new InvalidOperationException("StackExchange.Redis IConnectionMultiplexer could not be resolved through application IServiceProvider."); - } + throw new InvalidOperationException($"StackExchange.Redis {nameof(IConnectionMultiplexer)} could not be resolved through application {nameof(IServiceProvider)}"); } + } - AddRedisInstrumentation( - builder, - connection, - sp.GetOptions(), - configure); - }); - } - - if (connection == null) - { - throw new NotSupportedException("StackExchange.Redis IConnectionMultiplexer must be supplied when dependency injection is unavailable. To enable dependency injection use the OpenTelemetry.Extensions.Hosting package."); - } - - return AddRedisInstrumentation(builder, connection, new StackExchangeRedisCallsInstrumentationOptions(), configure); + AddRedisInstrumentation( + builder, + connection, + sp.GetOptions(), + configure); + }); } private static TracerProviderBuilder AddRedisInstrumentation( diff --git a/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs b/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs index 46673a96b95..6f435d93ad8 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs @@ -19,6 +19,7 @@ #if DEBUG using System.Threading; #endif +using OpenTelemetry.Internal; using OpenTelemetry.Trace; using OpenTracing; @@ -36,7 +37,9 @@ internal sealed class ScopeManagerShim : IScopeManager public ScopeManagerShim(Tracer tracer) { - this.tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); + Guard.Null(tracer, nameof(tracer)); + + this.tracer = tracer; } #if DEBUG @@ -66,10 +69,7 @@ public IScope Active /// public IScope Activate(ISpan span, bool finishSpanOnDispose) { - if (!(span is SpanShim shim)) - { - throw new ArgumentException("span is not a valid SpanShim object"); - } + var shim = Guard.Type(span, nameof(span)); var scope = Tracer.WithSpan(shim.Span); diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs index 82c8b20f70d..177d0969b71 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanBuilderShim.cs @@ -17,8 +17,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using global::OpenTracing; +using OpenTelemetry.Internal; using OpenTelemetry.Trace; +using OpenTracing; namespace OpenTelemetry.Shims.OpenTracing { @@ -32,7 +33,7 @@ internal sealed class SpanBuilderShim : ISpanBuilder /// /// The tracer. /// - private readonly Trace.Tracer tracer; + private readonly Tracer tracer; /// /// The span name. @@ -65,7 +66,7 @@ internal sealed class SpanBuilderShim : ISpanBuilder /// /// The parent as an SpanContext, if any. /// - private Trace.SpanContext parentSpanContext; + private SpanContext parentSpanContext; /// /// The explicit start time, if any. @@ -74,19 +75,22 @@ internal sealed class SpanBuilderShim : ISpanBuilder private bool ignoreActiveSpan; - private Trace.SpanKind spanKind; + private SpanKind spanKind; private bool error; - public SpanBuilderShim(Trace.Tracer tracer, string spanName, IList rootOperationNamesForActivityBasedAutoInstrumentations = null) + public SpanBuilderShim(Tracer tracer, string spanName, IList rootOperationNamesForActivityBasedAutoInstrumentations = null) { - this.tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); - this.spanName = spanName ?? throw new ArgumentNullException(nameof(spanName)); + Guard.Null(tracer, nameof(tracer)); + Guard.Null(spanName, nameof(spanName)); + + this.tracer = tracer; + this.spanName = spanName; this.ScopeManager = new ScopeManagerShim(this.tracer); this.rootOperationNamesForActivityBasedAutoInstrumentations = rootOperationNamesForActivityBasedAutoInstrumentations ?? this.rootOperationNamesForActivityBasedAutoInstrumentations; } - private global::OpenTracing.IScopeManager ScopeManager { get; } + private IScopeManager ScopeManager { get; } private bool ParentSet => this.parentSpan != null || this.parentSpanContext.IsValid; @@ -98,7 +102,7 @@ public ISpanBuilder AsChildOf(ISpanContext parent) return this; } - return this.AddReference(global::OpenTracing.References.ChildOf, parent); + return this.AddReference(References.ChildOf, parent); } /// @@ -126,10 +130,7 @@ public ISpanBuilder AddReference(string referenceType, ISpanContext referencedCo return this; } - if (referenceType is null) - { - throw new ArgumentNullException(nameof(referenceType)); - } + Guard.Null(referenceType, nameof(referenceType)); // TODO There is no relation between OpenTracing.References (referenceType) and OpenTelemetry Link var actualContext = GetOpenTelemetrySpanContext(referencedContext); @@ -140,7 +141,7 @@ public ISpanBuilder AddReference(string referenceType, ISpanContext referencedCo } else { - this.links.Add(new Trace.Link(actualContext)); + this.links.Add(new Link(actualContext)); } return this; @@ -191,7 +192,7 @@ public ISpan Start() if (this.error) { - span.SetStatus(Trace.Status.Error); + span.SetStatus(Status.Error); } return new SpanShim(span); @@ -222,11 +223,11 @@ public ISpanBuilder WithTag(string key, string value) { this.spanKind = value switch { - global::OpenTracing.Tag.Tags.SpanKindClient => Trace.SpanKind.Client, - global::OpenTracing.Tag.Tags.SpanKindServer => Trace.SpanKind.Server, - global::OpenTracing.Tag.Tags.SpanKindProducer => Trace.SpanKind.Producer, - global::OpenTracing.Tag.Tags.SpanKindConsumer => Trace.SpanKind.Consumer, - _ => Trace.SpanKind.Internal, + global::OpenTracing.Tag.Tags.SpanKindClient => SpanKind.Client, + global::OpenTracing.Tag.Tags.SpanKindServer => SpanKind.Server, + global::OpenTracing.Tag.Tags.SpanKindProducer => SpanKind.Producer, + global::OpenTracing.Tag.Tags.SpanKindConsumer => SpanKind.Consumer, + _ => SpanKind.Internal, }; } else if (global::OpenTracing.Tag.Tags.Error.Key.Equals(key, StringComparison.Ordinal) && bool.TryParse(value, out var booleanValue)) @@ -278,10 +279,7 @@ public ISpanBuilder WithTag(string key, double value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.BooleanTag tag, bool value) { - if (tag == null || tag.Key == null) - { - throw new ArgumentNullException(nameof(tag)); - } + Guard.Null(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); return this.WithTag(tag.Key, value); } @@ -289,10 +287,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.BooleanTag tag, bool value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.IntOrStringTag tag, string value) { - if (tag == null || tag.Key == null) - { - throw new ArgumentNullException(nameof(tag)); - } + Guard.Null(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); if (int.TryParse(value, out var result)) { @@ -305,10 +300,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.IntOrStringTag tag, string v /// public ISpanBuilder WithTag(global::OpenTracing.Tag.IntTag tag, int value) { - if (tag == null || tag.Key == null) - { - throw new ArgumentNullException(nameof(tag)); - } + Guard.Null(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); return this.WithTag(tag.Key, value); } @@ -316,10 +308,7 @@ public ISpanBuilder WithTag(global::OpenTracing.Tag.IntTag tag, int value) /// public ISpanBuilder WithTag(global::OpenTracing.Tag.StringTag tag, string value) { - if (tag == null || tag.Key == null) - { - throw new ArgumentNullException(nameof(tag)); - } + Guard.Null(tag?.Key, $"{nameof(tag)}?.{nameof(tag.Key)}"); return this.WithTag(tag.Key, value); } @@ -332,10 +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) { - if (!(span is SpanShim shim)) - { - throw new ArgumentException("span is not a valid SpanShim object"); - } + var shim = Guard.Type(span, nameof(span)); return shim.Span; } @@ -346,12 +332,9 @@ private static TelemetrySpan GetOpenTelemetrySpan(ISpan span) /// The span context. /// the OpenTelemetry SpanContext. /// context is not a valid SpanContextShim object. - private static Trace.SpanContext GetOpenTelemetrySpanContext(ISpanContext spanContext) + private static SpanContext GetOpenTelemetrySpanContext(ISpanContext spanContext) { - if (!(spanContext is SpanContextShim shim)) - { - throw new ArgumentException("context is not a valid SpanContextShim object"); - } + var shim = Guard.Type(spanContext, nameof(spanContext)); return shim.SpanContext; } diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs index 4a91597b017..cecf5b14894 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanContextShim.cs @@ -26,7 +26,7 @@ public SpanContextShim(in Trace.SpanContext spanContext) { if (!spanContext.IsValid) { - throw new ArgumentException(nameof(spanContext)); + throw new ArgumentException($"Invalid '{nameof(Trace.SpanContext)}'", nameof(spanContext)); } this.SpanContext = spanContext; diff --git a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs index f046fe22416..c72ebe15b7c 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/SpanShim.cs @@ -17,12 +17,13 @@ using System; using System.Collections.Generic; using System.Linq; -using global::OpenTracing; +using OpenTelemetry.Internal; using OpenTelemetry.Trace; +using OpenTracing; namespace OpenTelemetry.Shims.OpenTracing { - internal sealed class SpanShim : global::OpenTracing.ISpan + internal sealed class SpanShim : ISpan { /// /// The default event name if not specified. @@ -45,13 +46,13 @@ internal sealed class SpanShim : global::OpenTracing.ISpan public SpanShim(TelemetrySpan span) { - this.Span = span ?? throw new ArgumentNullException(nameof(span), "Parameter cannot be null"); - - if (!this.Span.Context.IsValid) + Guard.Null(span, nameof(span)); + if (!span.Context.IsValid) { - throw new ArgumentException("Passed span's context is not valid", nameof(this.Span.Context)); + throw new ArgumentException($"Invalid '{nameof(SpanContext)}'", nameof(span.Context)); } + this.Span = span; this.spanContextShim = new SpanContextShim(this.Span.Context); } @@ -76,12 +77,9 @@ public string GetBaggageItem(string key) => Baggage.GetBaggage(key); /// - public global::OpenTracing.ISpan Log(DateTimeOffset timestamp, IEnumerable> fields) + public ISpan Log(DateTimeOffset timestamp, IEnumerable> fields) { - if (fields is null) - { - throw new ArgumentNullException(nameof(fields), "Parameter cannot be null"); - } + Guard.Null(fields, nameof(fields)); var payload = ConvertToEventPayload(fields); var eventName = payload.Item1; @@ -134,79 +132,64 @@ public string GetBaggageItem(string key) } /// - public global::OpenTracing.ISpan Log(IEnumerable> fields) + public ISpan Log(IEnumerable> fields) { return this.Log(DateTimeOffset.MinValue, fields); } /// - public global::OpenTracing.ISpan Log(string @event) + public ISpan Log(string @event) { - if (@event is null) - { - throw new ArgumentNullException(nameof(@event), "Parameter cannot be null"); - } + Guard.Null(@event, nameof(@event)); this.Span.AddEvent(@event); return this; } /// - public global::OpenTracing.ISpan Log(DateTimeOffset timestamp, string @event) + public ISpan Log(DateTimeOffset timestamp, string @event) { - if (@event is null) - { - throw new ArgumentNullException(nameof(@event), "Parameter cannot be null"); - } + Guard.Null(@event, nameof(@event)); this.Span.AddEvent(@event, timestamp); return this; } /// - public global::OpenTracing.ISpan SetBaggageItem(string key, string value) + public ISpan SetBaggageItem(string key, string value) { Baggage.SetBaggage(key, value); return this; } /// - public global::OpenTracing.ISpan SetOperationName(string operationName) + public ISpan SetOperationName(string operationName) { - if (operationName is null) - { - throw new ArgumentNullException(nameof(operationName), "Parameter cannot be null"); - } + Guard.Null(operationName, nameof(operationName)); this.Span.UpdateName(operationName); return this; } /// - public global::OpenTracing.ISpan SetTag(string key, string value) + public ISpan SetTag(string key, string value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key), "Parameter cannot be null"); - } + Guard.Null(key, nameof(key)); this.Span.SetAttribute(key, value); return this; } /// - public global::OpenTracing.ISpan SetTag(string key, bool value) + public ISpan SetTag(string key, bool value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key), "Parameter cannot be null"); - } + Guard.Null(key, nameof(key)); // Special case the OpenTracing Error Tag // see https://opentracing.io/specification/conventions/ if (global::OpenTracing.Tag.Tags.Error.Key.Equals(key, StringComparison.Ordinal)) { - this.Span.SetStatus(value ? Trace.Status.Error : Trace.Status.Ok); + this.Span.SetStatus(value ? Status.Error : Status.Ok); } else { @@ -217,37 +200,31 @@ public string GetBaggageItem(string key) } /// - public global::OpenTracing.ISpan SetTag(string key, int value) + public ISpan SetTag(string key, int value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key), "Parameter cannot be null"); - } + Guard.Null(key, nameof(key)); this.Span.SetAttribute(key, value); return this; } /// - public global::OpenTracing.ISpan SetTag(string key, double value) + public ISpan SetTag(string key, double value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key), "Parameter cannot be null"); - } + Guard.Null(key, nameof(key)); this.Span.SetAttribute(key, value); return this; } /// - public global::OpenTracing.ISpan SetTag(global::OpenTracing.Tag.BooleanTag tag, bool value) + public ISpan SetTag(global::OpenTracing.Tag.BooleanTag tag, bool value) { return this.SetTag(tag?.Key, value); } /// - public global::OpenTracing.ISpan SetTag(global::OpenTracing.Tag.IntOrStringTag tag, string value) + public ISpan SetTag(global::OpenTracing.Tag.IntOrStringTag tag, string value) { if (int.TryParse(value, out var result)) { @@ -258,13 +235,13 @@ public string GetBaggageItem(string key) } /// - public global::OpenTracing.ISpan SetTag(global::OpenTracing.Tag.IntTag tag, int value) + public ISpan SetTag(global::OpenTracing.Tag.IntTag tag, int value) { return this.SetTag(tag?.Key, value); } /// - public global::OpenTracing.ISpan SetTag(global::OpenTracing.Tag.StringTag tag, string value) + public ISpan SetTag(global::OpenTracing.Tag.StringTag tag, string value) { return this.SetTag(tag?.Key, value); } diff --git a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs index f1540fcba8f..45a1ce7db9f 100644 --- a/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs +++ b/src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs @@ -14,10 +14,10 @@ // limitations under the License. // -using System; using System.Collections.Generic; -using global::OpenTracing.Propagation; using OpenTelemetry.Context.Propagation; +using OpenTelemetry.Internal; +using OpenTracing.Propagation; namespace OpenTelemetry.Shims.OpenTracing { @@ -28,9 +28,11 @@ public class TracerShim : global::OpenTracing.ITracer public TracerShim(Trace.Tracer tracer, TextMapPropagator textFormat) { - this.tracer = tracer ?? throw new ArgumentNullException(nameof(tracer), "Parameter cannot be null"); - this.propagator = textFormat ?? throw new ArgumentNullException(nameof(textFormat), "Parameter cannot be null"); + Guard.Null(tracer, nameof(tracer)); + Guard.Null(textFormat, nameof(textFormat)); + this.tracer = tracer; + this.propagator = textFormat; this.ScopeManager = new ScopeManagerShim(this.tracer); } @@ -47,17 +49,10 @@ public TracerShim(Trace.Tracer tracer, TextMapPropagator textFormat) } /// - public global::OpenTracing.ISpanContext Extract(global::OpenTracing.Propagation.IFormat format, TCarrier carrier) + public global::OpenTracing.ISpanContext Extract(IFormat format, TCarrier carrier) { - if (format is null) - { - throw new ArgumentNullException(nameof(format), "Parameter cannot be null"); - } - - if (carrier == null) - { - throw new ArgumentNullException(nameof(carrier), "Parameter cannot be null"); - } + Guard.Null(format, nameof(format)); + Guard.Null(carrier, nameof(carrier)); PropagationContext propagationContext = default; @@ -94,28 +89,13 @@ static IEnumerable GetCarrierKeyValue(Dictionary public void Inject( global::OpenTracing.ISpanContext spanContext, - global::OpenTracing.Propagation.IFormat format, + IFormat format, TCarrier carrier) { - if (spanContext is null) - { - throw new ArgumentNullException(nameof(spanContext), "Parameter cannot be null"); - } - - if (!(spanContext is SpanContextShim shim)) - { - throw new ArgumentException("Context is not a valid SpanContextShim object", nameof(shim)); - } - - if (format is null) - { - throw new ArgumentNullException(nameof(format), "Parameter cannot be null"); - } - - if (carrier == null) - { - throw new ArgumentNullException(nameof(carrier), "Parameter cannot be null"); - } + Guard.Null(spanContext, nameof(spanContext)); + var shim = Guard.Type(spanContext, nameof(spanContext)); + Guard.Null(format, nameof(format)); + Guard.Null(carrier, nameof(carrier)); if ((format == BuiltinFormats.TextMap || format == BuiltinFormats.HttpHeaders) && carrier is ITextMap textMapCarrier) { diff --git a/src/OpenTelemetry/BaseExportProcessor.cs b/src/OpenTelemetry/BaseExportProcessor.cs index 2d0a78ff467..b27af6db40e 100644 --- a/src/OpenTelemetry/BaseExportProcessor.cs +++ b/src/OpenTelemetry/BaseExportProcessor.cs @@ -35,7 +35,9 @@ public abstract class BaseExportProcessor : BaseProcessor /// Exporter instance. protected BaseExportProcessor(BaseExporter exporter) { - this.exporter = exporter ?? throw new ArgumentNullException(nameof(exporter)); + Guard.Null(exporter, nameof(exporter)); + + this.exporter = exporter; } /// diff --git a/src/OpenTelemetry/BaseExporter.cs b/src/OpenTelemetry/BaseExporter.cs index 9a3ac8dd4fb..079cd4be26e 100644 --- a/src/OpenTelemetry/BaseExporter.cs +++ b/src/OpenTelemetry/BaseExporter.cs @@ -68,7 +68,7 @@ public abstract class BaseExporter : IDisposable /// /// Returns true when shutdown succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -77,10 +77,7 @@ public abstract class BaseExporter : IDisposable /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (Interlocked.Increment(ref this.shutdownCount) > 1) { diff --git a/src/OpenTelemetry/BaseProcessor.cs b/src/OpenTelemetry/BaseProcessor.cs index c4734f6a828..8fc9f69f54b 100644 --- a/src/OpenTelemetry/BaseProcessor.cs +++ b/src/OpenTelemetry/BaseProcessor.cs @@ -74,7 +74,7 @@ public virtual void OnEnd(T data) /// /// Returns true when flush succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -82,10 +82,7 @@ public virtual void OnEnd(T data) /// public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) { - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); try { @@ -109,7 +106,7 @@ public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) /// /// Returns true when shutdown succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -118,10 +115,7 @@ public bool ForceFlush(int timeoutMilliseconds = Timeout.Infinite) /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (Interlocked.Increment(ref this.shutdownCount) > 1) { diff --git a/src/OpenTelemetry/Batch.cs b/src/OpenTelemetry/Batch.cs index cb2527a700a..85116ffe1df 100644 --- a/src/OpenTelemetry/Batch.cs +++ b/src/OpenTelemetry/Batch.cs @@ -37,7 +37,9 @@ namespace OpenTelemetry internal Batch(T item) { - this.item = item ?? throw new ArgumentNullException(nameof(item)); + Guard.Null(item, nameof(item)); + + this.item = item; this.circularBuffer = null; this.metrics = null; this.targetCount = 1; @@ -46,20 +48,22 @@ internal Batch(T item) internal Batch(CircularBuffer circularBuffer, int maxSize) { Debug.Assert(maxSize > 0, $"{nameof(maxSize)} should be a positive number."); + Guard.Null(circularBuffer, nameof(circularBuffer)); this.item = null; this.metrics = null; - this.circularBuffer = circularBuffer ?? throw new ArgumentNullException(nameof(circularBuffer)); + this.circularBuffer = circularBuffer; this.targetCount = circularBuffer.RemovedCount + Math.Min(maxSize, circularBuffer.Count); } internal Batch(T[] metrics, int maxSize) { Debug.Assert(maxSize > 0, $"{nameof(maxSize)} should be a positive number."); + Guard.Null(metrics, nameof(metrics)); this.item = null; this.circularBuffer = null; - this.metrics = metrics ?? throw new ArgumentNullException(nameof(metrics)); + this.metrics = metrics; this.targetCount = maxSize; } diff --git a/src/OpenTelemetry/BatchExportProcessor.cs b/src/OpenTelemetry/BatchExportProcessor.cs index 21e3f1a5bfe..2c102513d9d 100644 --- a/src/OpenTelemetry/BatchExportProcessor.cs +++ b/src/OpenTelemetry/BatchExportProcessor.cs @@ -60,25 +60,10 @@ protected BatchExportProcessor( int maxExportBatchSize = DefaultMaxExportBatchSize) : base(exporter) { - if (maxQueueSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxQueueSize), maxQueueSize, "maxQueueSize should be greater than zero."); - } - - if (maxExportBatchSize <= 0 || maxExportBatchSize > maxQueueSize) - { - throw new ArgumentOutOfRangeException(nameof(maxExportBatchSize), maxExportBatchSize, "maxExportBatchSize should be greater than zero and less than maxQueueSize."); - } - - if (scheduledDelayMilliseconds <= 0) - { - throw new ArgumentOutOfRangeException(nameof(scheduledDelayMilliseconds), scheduledDelayMilliseconds, "scheduledDelayMilliseconds should be greater than zero."); - } - - if (exporterTimeoutMilliseconds < 0) - { - throw new ArgumentOutOfRangeException(nameof(exporterTimeoutMilliseconds), exporterTimeoutMilliseconds, "exporterTimeoutMilliseconds should be non-negative."); - } + Guard.Range(maxQueueSize, nameof(maxQueueSize), min: 1); + Guard.Range(maxExportBatchSize, nameof(maxExportBatchSize), min: 1, max: maxQueueSize, maxName: nameof(maxQueueSize)); + Guard.Range(scheduledDelayMilliseconds, nameof(scheduledDelayMilliseconds), min: 1); + Guard.Range(exporterTimeoutMilliseconds, nameof(exporterTimeoutMilliseconds), min: 0); this.circularBuffer = new CircularBuffer(maxQueueSize); this.scheduledDelayMilliseconds = scheduledDelayMilliseconds; diff --git a/src/OpenTelemetry/CompositeProcessor.cs b/src/OpenTelemetry/CompositeProcessor.cs index 65ccccffed8..51b7859d844 100644 --- a/src/OpenTelemetry/CompositeProcessor.cs +++ b/src/OpenTelemetry/CompositeProcessor.cs @@ -30,16 +30,12 @@ public class CompositeProcessor : BaseProcessor public CompositeProcessor(IEnumerable> processors) { - if (processors == null) - { - throw new ArgumentNullException(nameof(processors)); - } + Guard.Null(processors, nameof(processors)); using var iter = processors.GetEnumerator(); - if (!iter.MoveNext()) { - throw new ArgumentException($"{nameof(processors)} collection is empty"); + throw new ArgumentException($"'{iter}' is null or empty", nameof(iter)); } this.head = new DoublyLinkedListNode(iter.Current); @@ -53,10 +49,7 @@ public CompositeProcessor(IEnumerable> processors) public CompositeProcessor AddProcessor(BaseProcessor processor) { - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(processor, nameof(processor)); var node = new DoublyLinkedListNode(processor) { diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs index 8c5c5f3db7e..e5791cdb4ea 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceListener.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using OpenTelemetry.Internal; namespace OpenTelemetry.Instrumentation { @@ -26,7 +27,9 @@ internal class DiagnosticSourceListener : IObserver public DiagnosticSourceListener(ListenerHandler handler) { - this.handler = handler ?? throw new ArgumentNullException(nameof(handler)); + Guard.Null(handler, nameof(handler)); + + this.handler = handler; } public void OnCompleted() diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs index 7af54876057..1a21408cd19 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/DiagnosticSourceSubscriber.cs @@ -17,6 +17,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using OpenTelemetry.Internal; namespace OpenTelemetry.Instrumentation { @@ -41,8 +42,10 @@ public DiagnosticSourceSubscriber( Func diagnosticSourceFilter, Func isEnabledFilter) { + Guard.Null(handlerFactory, nameof(handlerFactory)); + this.listenerSubscriptions = new List(); - this.handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory)); + this.handlerFactory = handlerFactory; this.diagnosticSourceFilter = diagnosticSourceFilter; this.isEnabledFilter = isEnabledFilter; } diff --git a/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs b/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs index 35bf7b9c9e6..e77e702b538 100644 --- a/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs +++ b/src/OpenTelemetry/DiagnosticSourceInstrumentation/PropertyFetcher.cs @@ -17,6 +17,7 @@ using System; using System.Linq; using System.Reflection; +using OpenTelemetry.Internal; namespace OpenTelemetry.Instrumentation { @@ -45,9 +46,11 @@ public PropertyFetcher(string propertyName) /// Property fetched. public T Fetch(object obj) { + Guard.Null(obj, nameof(obj)); + if (!this.TryFetch(obj, out T value)) { - throw new ArgumentException("Supplied object was null or did not match the expected type.", nameof(obj)); + throw new ArgumentException($"Unable to fetch property: '{nameof(obj)}'", nameof(obj)); } return value; diff --git a/src/OpenTelemetry/Internal/CircularBuffer.cs b/src/OpenTelemetry/Internal/CircularBuffer.cs index 58f1f26dec3..b5aec5ede55 100644 --- a/src/OpenTelemetry/Internal/CircularBuffer.cs +++ b/src/OpenTelemetry/Internal/CircularBuffer.cs @@ -14,7 +14,6 @@ // limitations under the License. // -using System; using System.Runtime.CompilerServices; using System.Threading; @@ -37,10 +36,7 @@ internal class CircularBuffer /// The capacity of the circular buffer, must be a positive integer. public CircularBuffer(int capacity) { - if (capacity <= 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "capacity should be greater than zero."); - } + Guard.Range(capacity, nameof(capacity), min: 1); this.Capacity = capacity; this.trait = new T[capacity]; @@ -83,10 +79,7 @@ public int Count /// public bool Add(T value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + Guard.Null(value, nameof(value)); while (true) { @@ -126,10 +119,7 @@ public bool TryAdd(T value, int maxSpinCount) return this.Add(value); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + Guard.Null(value, nameof(value)); var spinCountDown = maxSpinCount; diff --git a/src/OpenTelemetry/Internal/PooledList.cs b/src/OpenTelemetry/Internal/PooledList.cs index 3e7be9e57d6..c0f0b4491bb 100644 --- a/src/OpenTelemetry/Internal/PooledList.cs +++ b/src/OpenTelemetry/Internal/PooledList.cs @@ -52,12 +52,9 @@ public static PooledList Create() public static void Add(ref PooledList list, T item) { - var buffer = list.buffer; + Guard.Null(list.buffer, $"{nameof(list)}.{nameof(list.buffer)}"); - if (buffer == null) - { - throw new InvalidOperationException("Items cannot be added to an empty pool instance."); - } + var buffer = list.buffer; if (list.Count >= buffer.Length) { diff --git a/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs b/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs index dfc3c01f1c9..55138732b04 100644 --- a/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs +++ b/src/OpenTelemetry/Internal/SelfDiagnosticsEventListener.cs @@ -43,8 +43,10 @@ internal class SelfDiagnosticsEventListener : EventListener public SelfDiagnosticsEventListener(EventLevel logLevel, SelfDiagnosticsConfigRefresher configRefresher) { + Guard.Null(configRefresher, nameof(configRefresher)); + this.logLevel = logLevel; - this.configRefresher = configRefresher ?? throw new ArgumentNullException(nameof(configRefresher)); + this.configRefresher = configRefresher; List eventSources; lock (this.lockObj) diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs b/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs index 11ca152d64a..8647545190f 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLogger.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; +using OpenTelemetry.Internal; namespace OpenTelemetry.Logs { @@ -28,8 +29,11 @@ internal class OpenTelemetryLogger : ILogger internal OpenTelemetryLogger(string categoryName, OpenTelemetryLoggerProvider provider) { - this.categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName)); - this.provider = provider ?? throw new ArgumentNullException(nameof(provider)); + Guard.Null(categoryName, nameof(categoryName)); + Guard.Null(provider, nameof(provider)); + + this.categoryName = categoryName; + this.provider = provider; } internal IExternalScopeProvider ScopeProvider { get; set; } diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs index 2ef00398638..7c93853b5e2 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggerOptions.cs @@ -14,8 +14,8 @@ // limitations under the License. // -using System; using System.Collections.Generic; +using OpenTelemetry.Internal; using OpenTelemetry.Resources; namespace OpenTelemetry.Logs @@ -58,10 +58,7 @@ public class OpenTelemetryLoggerOptions /// Returns for chaining. public OpenTelemetryLoggerOptions AddProcessor(BaseProcessor processor) { - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(processor, nameof(processor)); this.Processors.Add(processor); @@ -76,8 +73,9 @@ public OpenTelemetryLoggerOptions AddProcessor(BaseProcessor processo /// Returns for chaining. public OpenTelemetryLoggerOptions SetResourceBuilder(ResourceBuilder resourceBuilder) { - this.ResourceBuilder = resourceBuilder ?? throw new ArgumentNullException(nameof(resourceBuilder)); + Guard.Null(resourceBuilder, nameof(resourceBuilder)); + this.ResourceBuilder = resourceBuilder; return this; } } diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs index 16d0f1f6b0d..4592bba465e 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggerProvider.cs @@ -14,10 +14,10 @@ // limitations under the License. // -using System; using System.Collections; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using OpenTelemetry.Internal; using OpenTelemetry.Resources; namespace OpenTelemetry.Logs @@ -46,8 +46,9 @@ public OpenTelemetryLoggerProvider(IOptionsMonitor o internal OpenTelemetryLoggerProvider(OpenTelemetryLoggerOptions options) { - this.Options = options ?? throw new ArgumentNullException(nameof(options)); + Guard.Null(options, nameof(options)); + this.Options = options; this.Resource = options.ResourceBuilder.Build(); foreach (var processor in options.Processors) @@ -96,10 +97,7 @@ public ILogger CreateLogger(string categoryName) internal OpenTelemetryLoggerProvider AddProcessor(BaseProcessor processor) { - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(processor, nameof(processor)); processor.SetParentProvider(this); diff --git a/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs b/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs index 7affea1ef02..f117fff6dc2 100644 --- a/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs +++ b/src/OpenTelemetry/Logs/OpenTelemetryLoggingExtensions.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Configuration; +using OpenTelemetry.Internal; using OpenTelemetry.Logs; namespace Microsoft.Extensions.Logging @@ -27,10 +28,7 @@ public static class OpenTelemetryLoggingExtensions { public static ILoggingBuilder AddOpenTelemetry(this ILoggingBuilder builder, Action configure = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + Guard.Null(builder, nameof(builder)); builder.AddConfiguration(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); diff --git a/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs b/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs index 2fe914f9fa9..60d6c2950ec 100644 --- a/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs +++ b/src/OpenTelemetry/Metrics/BaseExportingMetricReader.cs @@ -17,6 +17,7 @@ using System; using System.Diagnostics; using System.Threading; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -28,7 +29,9 @@ public class BaseExportingMetricReader : MetricReader public BaseExportingMetricReader(BaseExporter exporter) { - this.exporter = exporter ?? throw new ArgumentNullException(nameof(exporter)); + Guard.Null(exporter, nameof(exporter)); + + this.exporter = exporter; var exportorType = exporter.GetType(); var attributes = exportorType.GetCustomAttributes(typeof(AggregationTemporalityAttribute), true); diff --git a/src/OpenTelemetry/Metrics/BatchMetricPoint.cs b/src/OpenTelemetry/Metrics/BatchMetricPoint.cs index b17f5000ec5..99462f4df84 100644 --- a/src/OpenTelemetry/Metrics/BatchMetricPoint.cs +++ b/src/OpenTelemetry/Metrics/BatchMetricPoint.cs @@ -17,6 +17,7 @@ using System; using System.Collections; using System.Diagnostics; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -30,7 +31,9 @@ namespace OpenTelemetry.Metrics internal BatchMetricPoint(MetricPoint[] metricsPoints, int maxSize, DateTimeOffset start, DateTimeOffset end) { Debug.Assert(maxSize > 0, $"{nameof(maxSize)} should be a positive number."); - this.metricsPoints = metricsPoints ?? throw new ArgumentNullException(nameof(metricsPoints)); + Guard.Null(metricsPoints, nameof(metricsPoints)); + + this.metricsPoints = metricsPoints; this.targetCount = maxSize; this.start = start; this.end = end; diff --git a/src/OpenTelemetry/Metrics/CompositeMetricReader.cs b/src/OpenTelemetry/Metrics/CompositeMetricReader.cs index 6720341a17f..503288d89e7 100644 --- a/src/OpenTelemetry/Metrics/CompositeMetricReader.cs +++ b/src/OpenTelemetry/Metrics/CompositeMetricReader.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -29,16 +30,12 @@ internal class CompositeMetricReader : MetricReader public CompositeMetricReader(IEnumerable readers) { - if (readers == null) - { - throw new ArgumentNullException(nameof(readers)); - } + Guard.Null(readers, nameof(readers)); using var iter = readers.GetEnumerator(); - if (!iter.MoveNext()) { - throw new ArgumentException($"{nameof(readers)} collection is empty"); + throw new ArgumentException($"'{iter}' is null or empty", nameof(iter)); } this.head = new DoublyLinkedListNode(iter.Current); @@ -52,10 +49,7 @@ public CompositeMetricReader(IEnumerable readers) public CompositeMetricReader AddReader(MetricReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + Guard.Null(reader, nameof(reader)); var node = new DoublyLinkedListNode(reader) { diff --git a/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs b/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs index 004cafeb455..a5376dd4d89 100644 --- a/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs +++ b/src/OpenTelemetry/Metrics/MeterProviderExtensions.cs @@ -16,6 +16,7 @@ using System; using System.Threading; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -33,7 +34,7 @@ public static class MeterProviderExtensions /// /// Returns true when force flush succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -41,15 +42,8 @@ public static class MeterProviderExtensions /// public static bool ForceFlush(this MeterProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.Null(provider, nameof(provider)); + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (provider is MeterProviderSdk meterProviderSdk) { @@ -80,7 +74,7 @@ public static bool ForceFlush(this MeterProvider provider, int timeoutMillisecon /// /// Returns true when shutdown succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -89,15 +83,8 @@ public static bool ForceFlush(this MeterProvider provider, int timeoutMillisecon /// public static bool Shutdown(this MeterProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.Null(provider, nameof(provider)); + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (provider is MeterProviderSdk meterProviderSdk) { diff --git a/src/OpenTelemetry/Metrics/MeterProviderSdk.cs b/src/OpenTelemetry/Metrics/MeterProviderSdk.cs index d3e61961e5c..70b4f8b3ec1 100644 --- a/src/OpenTelemetry/Metrics/MeterProviderSdk.cs +++ b/src/OpenTelemetry/Metrics/MeterProviderSdk.cs @@ -54,10 +54,7 @@ internal MeterProviderSdk( foreach (var reader in readers) { - if (reader == null) - { - throw new ArgumentException("A null value was found.", nameof(readers)); - } + Guard.Null(reader, nameof(reader)); reader.SetParentProvider(this); diff --git a/src/OpenTelemetry/Metrics/MetricReader.cs b/src/OpenTelemetry/Metrics/MetricReader.cs index 65a8a47d2fe..8f1790b345c 100644 --- a/src/OpenTelemetry/Metrics/MetricReader.cs +++ b/src/OpenTelemetry/Metrics/MetricReader.cs @@ -17,6 +17,7 @@ using System; using System.Diagnostics; using System.Threading; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -60,7 +61,7 @@ public AggregationTemporality SupportedAggregationTemporality /// /// Returns true when metrics collection succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -68,10 +69,7 @@ public AggregationTemporality SupportedAggregationTemporality /// public bool Collect(int timeoutMilliseconds = Timeout.Infinite) { - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); try { @@ -95,7 +93,7 @@ public bool Collect(int timeoutMilliseconds = Timeout.Infinite) /// /// Returns true when shutdown succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -104,10 +102,7 @@ public bool Collect(int timeoutMilliseconds = Timeout.Infinite) /// public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (Interlocked.Increment(ref this.shutdownCount) > 1) { @@ -228,15 +223,8 @@ protected virtual void Dispose(bool disposing) private static void ValidateAggregationTemporality(AggregationTemporality preferred, AggregationTemporality supported) { - if ((int)(preferred & CumulativeAndDelta) == 0) - { - throw new ArgumentException($"PreferredAggregationTemporality has an invalid value {preferred}.", nameof(preferred)); - } - - if ((int)(supported & CumulativeAndDelta) == 0) - { - throw new ArgumentException($"SupportedAggregationTemporality has an invalid value {supported}.", nameof(supported)); - } + Guard.Zero((int)(preferred & CumulativeAndDelta), $"PreferredAggregationTemporality has an invalid value {preferred}", nameof(preferred)); + Guard.Zero((int)(supported & CumulativeAndDelta), $"SupportedAggregationTemporality has an invalid value {supported}", nameof(supported)); /* | Preferred | Supported | Valid | @@ -251,10 +239,9 @@ private static void ValidateAggregationTemporality(AggregationTemporality prefer | Delta | Cumulative | false | | Delta | Delta | true | */ - if ((int)(preferred & supported) == 0 || preferred > supported) - { - throw new ArgumentException($"PreferredAggregationTemporality {preferred} and SupportedAggregationTemporality {supported} are incompatible."); - } + string message = $"PreferredAggregationTemporality {preferred} and SupportedAggregationTemporality {supported} are incompatible"; + Guard.Zero((int)(preferred & supported), message, nameof(preferred)); + Guard.Range((int)preferred, nameof(preferred), max: (int)supported, maxName: nameof(supported), message: message); } } } diff --git a/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs b/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs index 22e8bb64381..d0dd39fe58e 100644 --- a/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs +++ b/src/OpenTelemetry/Metrics/PeriodicExportingMetricReader.cs @@ -49,7 +49,7 @@ public PeriodicExportingMetricReader( if ((this.SupportedExportModes & ExportModes.Push) != ExportModes.Push) { - throw new InvalidOperationException("The exporter does not support push mode."); + throw new InvalidOperationException($"The '{nameof(exporter)}' does not support '{nameof(ExportModes)}.{nameof(ExportModes.Push)}'"); } this.exportIntervalMilliseconds = exportIntervalMilliseconds; diff --git a/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs b/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs index c39485e3387..d13b30da7b3 100644 --- a/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs +++ b/src/OpenTelemetry/Metrics/ThreadStaticStorage.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { @@ -40,17 +41,19 @@ private ThreadStaticStorage() [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ThreadStaticStorage GetStorage() { - if (ThreadStaticStorage.storage == null) + if (storage == null) { - ThreadStaticStorage.storage = new ThreadStaticStorage(); + storage = new ThreadStaticStorage(); } - return ThreadStaticStorage.storage; + return storage; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SplitToKeysAndValues(ReadOnlySpan> tags, int tagLength, out string[] tagKeys, out object[] tagValues) { + Guard.Zero(tagLength, $"There must be at least one tag to use {nameof(ThreadStaticStorage)}", $"{nameof(tagLength)}"); + if (tagLength <= MaxTagCacheSize) { tagKeys = this.tagStorage[tagLength - 1].TagKey; diff --git a/src/OpenTelemetry/Resources/Resource.cs b/src/OpenTelemetry/Resources/Resource.cs index 11099497812..b2d0e9aa1ba 100644 --- a/src/OpenTelemetry/Resources/Resource.cs +++ b/src/OpenTelemetry/Resources/Resource.cs @@ -14,6 +14,7 @@ // limitations under the License. // +using System; using System.Collections.Generic; using System.Linq; using OpenTelemetry.Internal; @@ -107,58 +108,55 @@ private static KeyValuePair SanitizeAttribute(KeyValuePair -using System; using System.Collections.Generic; +using OpenTelemetry.Internal; namespace OpenTelemetry.Resources { @@ -90,10 +90,7 @@ public Resource Build() // https://github.com/open-telemetry/oteps/blob/master/text/0111-auto-resource-detection.md internal ResourceBuilder AddDetector(IResourceDetector resourceDetector) { - if (resourceDetector == null) - { - throw new ArgumentNullException(nameof(resourceDetector)); - } + Guard.Null(resourceDetector, nameof(resourceDetector)); Resource resource = resourceDetector.Detect(); @@ -107,10 +104,7 @@ internal ResourceBuilder AddDetector(IResourceDetector resourceDetector) internal ResourceBuilder AddResource(Resource resource) { - if (resource == null) - { - throw new ArgumentNullException(nameof(resource)); - } + Guard.Null(resource, nameof(resource)); this.resources.Add(resource); diff --git a/src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs b/src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs index 9dd30fc1236..766583c7c7a 100644 --- a/src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs +++ b/src/OpenTelemetry/Resources/ResourceBuilderExtensions.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using OpenTelemetry.Internal; namespace OpenTelemetry.Resources { @@ -55,10 +56,7 @@ public static ResourceBuilder AddService( { Dictionary resourceAttributes = new Dictionary(); - if (string.IsNullOrEmpty(serviceName)) - { - throw new ArgumentNullException(nameof(serviceName)); - } + Guard.NullOrEmpty(serviceName, nameof(serviceName)); resourceAttributes.Add(ResourceSemanticConventions.AttributeServiceName, serviceName); diff --git a/src/OpenTelemetry/Trace/ExceptionProcessor.cs b/src/OpenTelemetry/Trace/ExceptionProcessor.cs index 84a4ca253d9..e8e1e9d6c6c 100644 --- a/src/OpenTelemetry/Trace/ExceptionProcessor.cs +++ b/src/OpenTelemetry/Trace/ExceptionProcessor.cs @@ -39,7 +39,7 @@ public ExceptionProcessor() } catch (Exception ex) { - throw new NotSupportedException("System.Runtime.InteropServices.Marshal.GetExceptionPointers is not supported.", ex); + throw new NotSupportedException($"'{typeof(Marshal).FullName}.GetExceptionPointers' is not supported", ex); } } diff --git a/src/OpenTelemetry/Trace/ParentBasedSampler.cs b/src/OpenTelemetry/Trace/ParentBasedSampler.cs index a88aad4082c..fff7c623a00 100644 --- a/src/OpenTelemetry/Trace/ParentBasedSampler.cs +++ b/src/OpenTelemetry/Trace/ParentBasedSampler.cs @@ -13,8 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // -using System; + using System.Diagnostics; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -42,8 +43,9 @@ public sealed class ParentBasedSampler : Sampler /// The to be called for root span/activity. public ParentBasedSampler(Sampler rootSampler) { - this.rootSampler = rootSampler ?? throw new ArgumentNullException(nameof(rootSampler)); + Guard.Null(rootSampler, nameof(rootSampler)); + this.rootSampler = rootSampler; this.Description = $"ParentBased{{{rootSampler.Description}}}"; this.remoteParentSampled = new AlwaysOnSampler(); diff --git a/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs b/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs index 5a5523610d4..936ff7781f2 100644 --- a/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs +++ b/src/OpenTelemetry/Trace/TraceIdRatioBasedSampler.cs @@ -16,6 +16,7 @@ using System; using System.Globalization; +using OpenTelemetry.Internal; namespace OpenTelemetry.Trace { @@ -36,10 +37,7 @@ public sealed class TraceIdRatioBasedSampler /// public TraceIdRatioBasedSampler(double probability) { - if (probability < 0.0 || probability > 1.0) - { - throw new ArgumentOutOfRangeException(nameof(probability), probability, "Probability must be in range [0.0, 1.0]"); - } + Guard.Range(probability, nameof(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 0b752dd15cd..ef88b44f353 100644 --- a/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs +++ b/src/OpenTelemetry/Trace/TracerProviderBuilderBase.cs @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using OpenTelemetry.Internal; using OpenTelemetry.Resources; namespace OpenTelemetry.Trace @@ -42,10 +43,7 @@ public override TracerProviderBuilder AddInstrumentation( Func instrumentationFactory) where TInstrumentation : class { - if (instrumentationFactory == null) - { - throw new ArgumentNullException(nameof(instrumentationFactory)); - } + Guard.Null(instrumentationFactory, nameof(instrumentationFactory)); this.instrumentationFactories.Add( new InstrumentationFactory( @@ -59,17 +57,11 @@ public override TracerProviderBuilder AddInstrumentation( /// public override TracerProviderBuilder AddSource(params string[] names) { - if (names == null) - { - throw new ArgumentNullException(nameof(names)); - } + Guard.Null(names, nameof(names)); foreach (var name in names) { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException($"{nameof(names)} contains null or whitespace string."); - } + Guard.NullOrWhitespace(name, nameof(name)); // TODO: We need to fix the listening model. // Today it ignores version. @@ -82,10 +74,7 @@ public override TracerProviderBuilder AddSource(params string[] names) /// public override TracerProviderBuilder AddLegacySource(string operationName) { - if (string.IsNullOrWhiteSpace(operationName)) - { - throw new ArgumentException($"{nameof(operationName)} contains null or whitespace string."); - } + Guard.NullOrWhitespace(operationName, nameof(operationName)); this.legacyActivityOperationNames[operationName] = true; @@ -93,7 +82,7 @@ public override TracerProviderBuilder AddLegacySource(string operationName) } /// - /// Sets whether the status of + /// Sets whether the status of /// should be set to Status.Error when it ended abnormally due to an unhandled exception. /// /// Enabled or not. @@ -117,7 +106,7 @@ internal TracerProviderBuilder SetErrorStatusOnException(bool enabled) } catch (Exception ex) { - throw new NotSupportedException("SetErrorStatusOnException is not supported on this platform.", ex); + throw new NotSupportedException($"'{nameof(this.SetErrorStatusOnException)}' is not supported on this platform", ex); } } } @@ -140,7 +129,9 @@ internal TracerProviderBuilder SetErrorStatusOnException(bool enabled) /// Returns for chaining. internal TracerProviderBuilder SetSampler(Sampler sampler) { - this.sampler = sampler ?? throw new ArgumentNullException(nameof(sampler)); + Guard.Null(sampler, nameof(sampler)); + + this.sampler = sampler; return this; } @@ -152,7 +143,9 @@ internal TracerProviderBuilder SetSampler(Sampler sampler) /// Returns for chaining. internal TracerProviderBuilder SetResourceBuilder(ResourceBuilder resourceBuilder) { - this.resourceBuilder = resourceBuilder ?? throw new ArgumentNullException(nameof(resourceBuilder)); + Guard.Null(resourceBuilder, nameof(resourceBuilder)); + + this.resourceBuilder = resourceBuilder; return this; } @@ -163,10 +156,7 @@ internal TracerProviderBuilder SetResourceBuilder(ResourceBuilder resourceBuilde /// Returns for chaining. internal TracerProviderBuilder AddProcessor(BaseProcessor processor) { - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(processor, nameof(processor)); this.processors.Add(processor); diff --git a/src/OpenTelemetry/Trace/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry/Trace/TracerProviderBuilderExtensions.cs index 09bdedca5da..78509d53b44 100644 --- a/src/OpenTelemetry/Trace/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry/Trace/TracerProviderBuilderExtensions.cs @@ -100,7 +100,7 @@ public static TracerProvider Build(this TracerProviderBuilder tracerProviderBuil { if (tracerProviderBuilder is IDeferredTracerProviderBuilder) { - throw new NotSupportedException("DeferredTracerProviderBuilder requires a ServiceProvider to build."); + throw new NotSupportedException($"'{nameof(TracerProviderBuilder)}' requires a '{nameof(IServiceProvider)}' to build"); } if (tracerProviderBuilder is TracerProviderBuilderSdk tracerProviderBuilderSdk) diff --git a/src/OpenTelemetry/Trace/TracerProviderExtensions.cs b/src/OpenTelemetry/Trace/TracerProviderExtensions.cs index a1b2ef9415d..ed02b7f30ae 100644 --- a/src/OpenTelemetry/Trace/TracerProviderExtensions.cs +++ b/src/OpenTelemetry/Trace/TracerProviderExtensions.cs @@ -25,15 +25,8 @@ public static class TracerProviderExtensions { public static TracerProvider AddProcessor(this TracerProvider provider, BaseProcessor processor) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(provider, nameof(provider)); + Guard.Null(processor, nameof(processor)); if (provider is TracerProviderSdk tracerProviderSdk) { @@ -55,7 +48,7 @@ public static TracerProvider AddProcessor(this TracerProvider provider, BaseProc /// /// Returns true when force flush succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -63,15 +56,8 @@ public static TracerProvider AddProcessor(this TracerProvider provider, BaseProc /// public static bool ForceFlush(this TracerProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.Null(provider, nameof(provider)); + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (provider is TracerProviderSdk tracerProviderSdk) { @@ -101,7 +87,7 @@ public static bool ForceFlush(this TracerProvider provider, int timeoutMilliseco /// /// Returns true when shutdown succeeded; otherwise, false. /// - /// + /// /// Thrown when the timeoutMilliseconds is smaller than -1. /// /// @@ -110,15 +96,8 @@ public static bool ForceFlush(this TracerProvider provider, int timeoutMilliseco /// public static bool Shutdown(this TracerProvider provider, int timeoutMilliseconds = Timeout.Infinite) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (timeoutMilliseconds < 0 && timeoutMilliseconds != Timeout.Infinite) - { - throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds), timeoutMilliseconds, "timeoutMilliseconds should be non-negative or Timeout.Infinite."); - } + Guard.Null(provider, nameof(provider)); + Guard.InvalidTimeout(timeoutMilliseconds, nameof(timeoutMilliseconds)); if (provider is TracerProviderSdk tracerProviderSdk) { diff --git a/src/OpenTelemetry/Trace/TracerProviderSdk.cs b/src/OpenTelemetry/Trace/TracerProviderSdk.cs index 0af222ea5be..a9b58e5502f 100644 --- a/src/OpenTelemetry/Trace/TracerProviderSdk.cs +++ b/src/OpenTelemetry/Trace/TracerProviderSdk.cs @@ -286,10 +286,7 @@ Regex GetWildcardRegex(IEnumerable collection) internal TracerProviderSdk AddProcessor(BaseProcessor processor) { - if (processor == null) - { - throw new ArgumentNullException(nameof(processor)); - } + Guard.Null(processor, nameof(processor)); processor.SetParentProvider(this); diff --git a/test/OpenTelemetry.Exporter.Jaeger.Tests/Implementation/ThriftUdpClientTransportTests.cs b/test/OpenTelemetry.Exporter.Jaeger.Tests/Implementation/ThriftUdpClientTransportTests.cs index 01764860d3d..cb93cb2f5ee 100644 --- a/test/OpenTelemetry.Exporter.Jaeger.Tests/Implementation/ThriftUdpClientTransportTests.cs +++ b/test/OpenTelemetry.Exporter.Jaeger.Tests/Implementation/ThriftUdpClientTransportTests.cs @@ -114,7 +114,7 @@ public void Flush_ShouldThrowWhenClientDoes() var ex = Assert.Throws(() => transport.Flush()); - Assert.Equal("Cannot flush closed transport. message, yo", ex.Message); + Assert.Equal("Cannot flush closed transport", ex.Message); } [Fact] diff --git a/test/OpenTelemetry.Shims.OpenTracing.Tests/ScopeManagerShimTests.cs b/test/OpenTelemetry.Shims.OpenTracing.Tests/ScopeManagerShimTests.cs index 1a79e2f3a1d..8ac7f2fd2ee 100644 --- a/test/OpenTelemetry.Shims.OpenTracing.Tests/ScopeManagerShimTests.cs +++ b/test/OpenTelemetry.Shims.OpenTracing.Tests/ScopeManagerShimTests.cs @@ -78,7 +78,7 @@ public void Activate_SpanMustBeShim() var tracer = TracerProvider.Default.GetTracer(TracerName); var shim = new ScopeManagerShim(tracer); - Assert.Throws(() => shim.Activate(new Mock().Object, true)); + Assert.Throws(() => shim.Activate(new Mock().Object, true)); } [Fact] diff --git a/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanShimTests.cs b/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanShimTests.cs index eba243588f6..ad2d68c680b 100644 --- a/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanShimTests.cs +++ b/test/OpenTelemetry.Shims.OpenTracing.Tests/SpanShimTests.cs @@ -18,8 +18,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using global::OpenTracing.Tag; using OpenTelemetry.Trace; +using OpenTracing.Tag; using Xunit; namespace OpenTelemetry.Shims.OpenTracing.Tests @@ -102,7 +102,7 @@ public void GetBaggageItem() var shim = new SpanShim(tracer.StartSpan(SpanName)); // parameter validation - Assert.Throws(() => shim.GetBaggageItem(null)); + Assert.Throws(() => shim.GetBaggageItem(null)); // TODO - Method not implemented } @@ -225,7 +225,7 @@ public void SetTagBoolValue() Assert.Throws(() => shim.SetTag((string)null, true)); shim.SetTag("foo", true); - shim.SetTag(global::OpenTracing.Tag.Tags.Error.Key, true); + shim.SetTag(Tags.Error.Key, true); Assert.Equal("foo", shim.Span.Activity.TagObjects.First().Key); Assert.True((bool)shim.Span.Activity.TagObjects.First().Value); @@ -233,7 +233,7 @@ public void SetTagBoolValue() // A boolean tag named "error" is a special case that must be checked Assert.Equal(Status.Error, shim.Span.Activity.GetStatus()); - shim.SetTag(global::OpenTracing.Tag.Tags.Error.Key, false); + shim.SetTag(Tags.Error.Key, false); Assert.Equal(Status.Ok, shim.Span.Activity.GetStatus()); } @@ -276,7 +276,7 @@ public void SetTagBooleanTagValue() Assert.Throws(() => shim.SetTag((BooleanTag)null, true)); shim.SetTag(new BooleanTag("foo"), true); - shim.SetTag(new BooleanTag(global::OpenTracing.Tag.Tags.Error.Key), true); + shim.SetTag(new BooleanTag(Tags.Error.Key), true); Assert.Equal("foo", shim.Span.Activity.TagObjects.First().Key); Assert.True((bool)shim.Span.Activity.TagObjects.First().Value); @@ -284,7 +284,7 @@ public void SetTagBooleanTagValue() // A boolean tag named "error" is a special case that must be checked Assert.Equal(Status.Error, shim.Span.Activity.GetStatus()); - shim.SetTag(global::OpenTracing.Tag.Tags.Error.Key, false); + shim.SetTag(Tags.Error.Key, false); Assert.Equal(Status.Ok, shim.Span.Activity.GetStatus()); } diff --git a/test/OpenTelemetry.Shims.OpenTracing.Tests/TracerShimTests.cs b/test/OpenTelemetry.Shims.OpenTracing.Tests/TracerShimTests.cs index f24ccd922f0..f47bf6566a3 100644 --- a/test/OpenTelemetry.Shims.OpenTracing.Tests/TracerShimTests.cs +++ b/test/OpenTelemetry.Shims.OpenTracing.Tests/TracerShimTests.cs @@ -77,7 +77,7 @@ public void Inject_ArgumentValidation() var mockCarrier = new Mock(); Assert.Throws(() => shim.Inject(null, mockFormat.Object, mockCarrier.Object)); - Assert.Throws(() => shim.Inject(new Mock().Object, mockFormat.Object, mockCarrier.Object)); + Assert.Throws(() => shim.Inject(new Mock().Object, mockFormat.Object, mockCarrier.Object)); Assert.Throws(() => shim.Inject(spanContextShim, null, mockCarrier.Object)); Assert.Throws(() => shim.Inject(spanContextShim, mockFormat.Object, null)); } diff --git a/test/OpenTelemetry.Tests/BaggageTests.cs b/test/OpenTelemetry.Tests/BaggageTests.cs index db995df2066..180039779dc 100644 --- a/test/OpenTelemetry.Tests/BaggageTests.cs +++ b/test/OpenTelemetry.Tests/BaggageTests.cs @@ -60,7 +60,7 @@ public void SetAndGetTest() Assert.Null(Baggage.GetBaggage("NO_KEY")); Assert.Equal(V2, Baggage.Current.GetBaggage(K2)); - Assert.Throws(() => Baggage.GetBaggage(null)); + Assert.Throws(() => Baggage.GetBaggage(null)); } [Fact] diff --git a/test/OpenTelemetry.Tests/Context/RuntimeContextTest.cs b/test/OpenTelemetry.Tests/Context/RuntimeContextTest.cs index f3bcccf365e..d39578bdd58 100644 --- a/test/OpenTelemetry.Tests/Context/RuntimeContextTest.cs +++ b/test/OpenTelemetry.Tests/Context/RuntimeContextTest.cs @@ -58,7 +58,7 @@ public void GetSlotReturnsNullForNonExistingSlot() public void GetSlotReturnsNullWhenTypeNotMatchingExistingSlot() { RuntimeContext.RegisterSlot("testslot"); - Assert.Throws(() => RuntimeContext.GetSlot("testslot")); + Assert.Throws(() => RuntimeContext.GetSlot("testslot")); } [Fact] diff --git a/test/OpenTelemetry.Tests/Internal/GuardTest.cs b/test/OpenTelemetry.Tests/Internal/GuardTest.cs new file mode 100644 index 00000000000..8b1e666694b --- /dev/null +++ b/test/OpenTelemetry.Tests/Internal/GuardTest.cs @@ -0,0 +1,143 @@ +// +// 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; +using System.Threading; +using OpenTelemetry.Internal; +using Xunit; + +namespace OpenTelemetry.Tests.Internal +{ + public static class GuardTest + { + [Fact] + public static void NullTest() + { + // Valid + Guard.Null(1); + Guard.Null(1.0); + Guard.Null(new object()); + Guard.Null("hello"); + + // Invalid + var ex1 = Assert.Throws(() => Guard.Null(null, "null")); + Assert.Contains("Must not be null", ex1.Message); + } + + [Fact] + public static void NullOrEmptyTest() + { + // Valid + Guard.NullOrEmpty("a"); + Guard.NullOrEmpty(" "); + + // Invalid + var ex1 = Assert.Throws(() => Guard.NullOrEmpty(null)); + Assert.Contains("Must not be null or empty", ex1.Message); + + var ex2 = Assert.Throws(() => Guard.NullOrEmpty(string.Empty)); + Assert.Contains("Must not be null or empty", ex2.Message); + } + + [Fact] + public static void NullOrWhitespaceTest() + { + // Valid + Guard.NullOrWhitespace("a"); + + // Invalid + var ex1 = Assert.Throws(() => Guard.NullOrWhitespace(null)); + Assert.Contains("Must not be null or whitespace", ex1.Message); + + var ex2 = Assert.Throws(() => Guard.NullOrWhitespace(string.Empty)); + Assert.Contains("Must not be null or whitespace", ex2.Message); + + var ex3 = Assert.Throws(() => Guard.NullOrWhitespace(" \t\n\r")); + Assert.Contains("Must not be null or whitespace", ex3.Message); + } + + [Fact] + public static void InvalidTimeoutTest() + { + // Valid + Guard.InvalidTimeout(Timeout.Infinite); + Guard.InvalidTimeout(0); + Guard.InvalidTimeout(100); + + // Invalid + var ex1 = Assert.Throws(() => Guard.InvalidTimeout(-100)); + Assert.Contains("Must be non-negative or 'Timeout.Infinite'", ex1.Message); + } + + [Fact] + public static void RangeIntTest() + { + // Valid + Guard.Range(0); + Guard.Range(0, min: 0, max: 0); + Guard.Range(5, min: -10, max: 10); + Guard.Range(int.MinValue, min: int.MinValue, max: 10); + Guard.Range(int.MaxValue, min: 10, max: int.MaxValue); + + // Invalid + var ex1 = Assert.Throws(() => Guard.Range(-1, min: 0, max: 100, minName: "empty", maxName: "full")); + Assert.Contains("Must be in the range: [0: empty, 100: full]", ex1.Message); + + var ex2 = Assert.Throws(() => Guard.Range(-1, min: 0, max: 100, message: "error")); + Assert.Contains("error", ex2.Message); + } + + [Fact] + public static void RangeDoubleTest() + { + // Valid + Guard.Range(1.0, min: 1.0, max: 1.0); + Guard.Range(double.MinValue, min: double.MinValue, max: 10.0); + Guard.Range(double.MaxValue, min: 10.0, max: double.MaxValue); + + // Invalid + var ex3 = Assert.Throws(() => Guard.Range(-1.1, min: 0.1, max: 99.9, minName: "empty", maxName: "full")); + Assert.Contains("Must be in the range: [0.1: empty, 99.9: full]", ex3.Message); + + var ex4 = Assert.Throws(() => Guard.Range(-1.1, min: 0.0, max: 100.0)); + Assert.Contains("Must be in the range: [0, 100]", ex4.Message); + } + + [Fact] + public static void TypeTest() + { + // Valid + Guard.Type(0); + Guard.Type(new object()); + Guard.Type("hello"); + + // Invalid + var ex1 = Assert.Throws(() => Guard.Type(100)); + Assert.Equal("Cannot cast 'N/A' from 'Int32' to 'Double'", ex1.Message); + } + + [Fact] + public static void ZeroTest() + { + // Valid + Guard.Zero(1); + + // Invalid + var ex1 = Assert.Throws(() => Guard.Zero(0)); + Assert.Contains("Must not be zero", ex1.Message); + } + } +}