diff --git a/Directory.Build.props b/Directory.Build.props index a0a856b99..20abcafb9 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,6 +4,6 @@ false false - 10.0 + 11.0 diff --git a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Shipped.txt b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Shipped.txt index e69de29bb..7dc5c5811 100644 --- a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Shipped.txt +++ b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Unshipped.txt b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Unshipped.txt index 3301fb056..3b7010f05 100644 --- a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net462/PublicAPI.Unshipped.txt @@ -6,13 +6,12 @@ OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.CallTargetRetur OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.CallTargetReturn(T returnValue) -> void OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetReturnValue() -> T OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.Activity.get -> System.Diagnostics.Activity +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.Activity.get -> System.Diagnostics.Activity? OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState() -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity, object state) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity, object state, System.DateTimeOffset? startTime) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.StartTime.get -> System.DateTimeOffset? -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.State.get -> object +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity! activity) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity! activity, object! state, System.DateTimeOffset? startTime) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity? activity, object! state) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.State.get -> object? OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL.ExecuteAsyncIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.Logger.LoggingBuilderIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.MongoDB.MongoClientIntegration @@ -20,8 +19,8 @@ OpenTelemetry.AutoInstrumentation.Instrumentations.MySqlData.MySqlConnectionStri OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis.StackExchangeRedisIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis.StackExchangeRedisIntegrationAsync OpenTelemetry.AutoInstrumentation.Instrumentations.Validations.StrongNamedValidation -override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.ToString() -> string -override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string +override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.ToString() -> string! +override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string! static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState @@ -31,11 +30,11 @@ static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMetho static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, object[] arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, TReturn returnValue, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue() -> T -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException(System.Exception exception) -> void +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, object![]! arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, TReturn returnValue, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue() -> T? +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException(System.Exception! exception) -> void static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState \ No newline at end of file diff --git a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Shipped.txt b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Shipped.txt index e69de29bb..7dc5c5811 100644 --- a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Shipped.txt +++ b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Unshipped.txt b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Unshipped.txt index 3301fb056..3b7010f05 100644 --- a/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Unshipped.txt +++ b/src/OpenTelemetry.AutoInstrumentation/.publicApi/net6.0/PublicAPI.Unshipped.txt @@ -6,13 +6,12 @@ OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.CallTargetRetur OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.CallTargetReturn(T returnValue) -> void OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetReturnValue() -> T OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.Activity.get -> System.Diagnostics.Activity +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.Activity.get -> System.Diagnostics.Activity? OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState() -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity, object state) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity activity, object state, System.DateTimeOffset? startTime) -> void -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.StartTime.get -> System.DateTimeOffset? -OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.State.get -> object +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity! activity) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity! activity, object! state, System.DateTimeOffset? startTime) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.CallTargetState(System.Diagnostics.Activity? activity, object! state) -> void +OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.State.get -> object? OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL.ExecuteAsyncIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.Logger.LoggingBuilderIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.MongoDB.MongoClientIntegration @@ -20,8 +19,8 @@ OpenTelemetry.AutoInstrumentation.Instrumentations.MySqlData.MySqlConnectionStri OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis.StackExchangeRedisIntegration OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis.StackExchangeRedisIntegrationAsync OpenTelemetry.AutoInstrumentation.Instrumentations.Validations.StrongNamedValidation -override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.ToString() -> string -override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string +override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.ToString() -> string! +override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string! static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState @@ -31,11 +30,11 @@ static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMetho static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1, TArg2 arg2) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, TArg1 arg1) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, object[] arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, TReturn returnValue, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue() -> T -static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException(System.Exception exception) -> void +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod(TTarget instance, object![]! arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, TReturn returnValue, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod(TTarget instance, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue() -> T? +static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException(System.Exception! exception) -> void static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState \ No newline at end of file diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetInvoker.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetInvoker.cs index 4d7f1b808..10bf0c9ff 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetInvoker.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetInvoker.cs @@ -313,14 +313,14 @@ public static class CallTargetInvoker /// CallTarget state /// CallTarget return structure [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static CallTargetReturn EndMethod(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public static CallTargetReturn EndMethod(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { if (IntegrationOptions.IsIntegrationEnabled) { return EndMethodHandler.Invoke(instance, returnValue, exception, state); } - return new CallTargetReturn(returnValue); + return new CallTargetReturn(returnValue); } /// @@ -341,5 +341,5 @@ public static class CallTargetInvoker /// Type to get the default value /// Default value of T [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T GetDefaultValue() => default; + public static T? GetDefaultValue() => default; } diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetState.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetState.cs index cf2711328..21ca33b37 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetState.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/CallTargetState.cs @@ -25,10 +25,9 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget; /// public readonly struct CallTargetState { - private readonly Activity _previousActivity; - private readonly Activity _activity; - private readonly object _state; - private readonly DateTimeOffset? _startTime; + private readonly Activity? _previousActivity; + private readonly Activity? _activity; + private readonly object? _state; /// /// Initializes a new instance of the struct. @@ -39,7 +38,6 @@ public readonly struct CallTargetState _previousActivity = null; _activity = activity; _state = null; - _startTime = null; } /// @@ -47,12 +45,11 @@ public readonly struct CallTargetState /// /// Activity instance /// Object state instance - public CallTargetState(Activity activity, object state) + public CallTargetState(Activity? activity, object state) { _previousActivity = null; _activity = activity; _state = state; - _startTime = null; } /// @@ -66,33 +63,26 @@ public readonly struct CallTargetState _previousActivity = null; _activity = activity; _state = state; - _startTime = startTime; } - internal CallTargetState(Activity previousActivity, CallTargetState state) + internal CallTargetState(Activity? previousActivity, CallTargetState state) { _previousActivity = previousActivity; _activity = state._activity; _state = state._state; - _startTime = state._startTime; } /// /// Gets the CallTarget BeginMethod activity /// - public Activity Activity => _activity; + public Activity? Activity => _activity; /// /// Gets the CallTarget BeginMethod state /// - public object State => _state; + public object? State => _state; - /// - /// Gets the CallTarget state StartTime - /// - public DateTimeOffset? StartTime => _startTime; - - internal Activity PreviousActivity => _previousActivity; + internal Activity? PreviousActivity => _previousActivity; /// /// Gets the default call target state (used by the native side to initialize the locals) diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler.cs index 2039664d9..2ae035ceb 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler.cs @@ -31,7 +31,7 @@ internal static class BeginMethodHandler { try { - DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), Array.Empty()); + DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), Array.Empty()); if (dynMethod != null) { _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`1.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`1.cs index 3dc32b5a8..6fe82e8ad 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`1.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`1.cs @@ -31,7 +31,7 @@ internal static class BeginMethodHandler { try { - DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1) }); + DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1) }); if (dynMethod != null) { _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`2.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`2.cs index 42f35ecd1..5d462aae2 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`2.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`2.cs @@ -31,7 +31,7 @@ internal static class BeginMethodHandler { try { - DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2) }); + DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2) }); if (dynMethod != null) { _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`3.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`3.cs index 66bb95d98..c790d7186 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`3.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/BeginMethodHandler`3.cs @@ -31,7 +31,7 @@ internal static class BeginMethodHandler { - public virtual TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public virtual TReturn? SetContinuation(TTarget instance, TReturn? returnValue, Exception? exception, CallTargetState state) { return returnValue; } @@ -37,12 +37,12 @@ internal class ContinuationGenerator } [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected static TTo FromTReturn(TReturn returnValue) + protected static TTo FromTReturn(TReturn? returnValue) { #if NET6_0_OR_GREATER - return Unsafe.As(ref returnValue); + return Unsafe.As(ref returnValue); #else - return ContinuationsHelper.Convert(returnValue); + return ContinuationsHelper.Convert(returnValue); #endif } } diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ContinuationsHelper.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ContinuationsHelper.cs index 2d0b4cc41..4a76f3fd5 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ContinuationsHelper.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ContinuationsHelper.cs @@ -25,7 +25,7 @@ internal static class ContinuationsHelper [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Type GetResultType(Type parentType) { - Type currentType = parentType; + Type? currentType = parentType; while (currentType != null) { Type[] typeArguments = currentType.GenericTypeArguments ?? Type.EmptyTypes; diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs index 967527407..ceb8ed156 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator.cs @@ -22,7 +22,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations; internal class TaskContinuationGenerator : ContinuationGenerator { - private static readonly Func _continuation; + private static readonly Func? _continuation; private static readonly bool _preserveContext; static TaskContinuationGenerator() @@ -30,12 +30,12 @@ internal class TaskContinuationGenerator : Conti var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(object)); if (result.Method != null) { - _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); + _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); _preserveContext = result.PreserveContext; } } - public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public override TReturn? SetContinuation(TTarget instance, TReturn? returnValue, Exception? exception, CallTargetState state) { if (_continuation == null) { @@ -65,11 +65,11 @@ internal class TaskContinuationGenerator : Conti await new NoThrowAwaiter(previousTask, _preserveContext); } - Exception exception = null; + Exception? exception = null; if (previousTask.Status == TaskStatus.Faulted) { - exception = previousTask.Exception.GetBaseException(); + exception = previousTask.Exception!.GetBaseException(); } else if (previousTask.Status == TaskStatus.Canceled) { @@ -89,7 +89,7 @@ internal class TaskContinuationGenerator : Conti // * // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application // * - _continuation(target, null, exception, state); + _continuation!(target, null, exception, state); } catch (Exception ex) { diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs index aeb0b165d..ab4329262 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/TaskContinuationGenerator`1.cs @@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations; internal class TaskContinuationGenerator : ContinuationGenerator { - private static readonly Func _continuation; + private static readonly Func? _continuation; private static readonly bool _preserveContext; static TaskContinuationGenerator() @@ -32,12 +32,12 @@ internal class TaskContinuationGenerator)result.Method.CreateDelegate(typeof(Func)); + _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); _preserveContext = result.PreserveContext; } } - public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public override TReturn? SetContinuation(TTarget instance, TReturn? returnValue, Exception? exception, CallTargetState state) { if (_continuation == null) { @@ -60,16 +60,16 @@ internal class TaskContinuationGenerator ContinuationAction(Task previousTask, TTarget target, CallTargetState state) + private static async Task ContinuationAction(Task previousTask, TTarget target, CallTargetState state) { if (!previousTask.IsCompleted) { await new NoThrowAwaiter(previousTask, _preserveContext); } - TResult taskResult = default; - Exception exception = null; - TResult continuationResult = default; + TResult? taskResult = default; + Exception? exception = null; + TResult? continuationResult = default; if (previousTask.Status == TaskStatus.RanToCompletion) { @@ -77,7 +77,7 @@ internal class TaskContinuationGenerator : ContinuationGenerator { - private static readonly Func _continuation; + private static readonly Func? _continuation; private static readonly bool _preserveContext; static ValueTaskContinuationGenerator() @@ -29,12 +29,12 @@ internal class ValueTaskContinuationGenerator : var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(object)); if (result.Method != null) { - _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); + _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); _preserveContext = result.PreserveContext; } } - public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public override TReturn? SetContinuation(TTarget instance, TReturn? returnValue, Exception? exception, CallTargetState state) { if (_continuation is null) { @@ -64,7 +64,7 @@ internal class ValueTaskContinuationGenerator : // * // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application // * - _continuation(instance, default, ex, state); + _continuation!(instance, default, ex, state); } catch (Exception contEx) { @@ -79,7 +79,7 @@ internal class ValueTaskContinuationGenerator : // * // Calls the CallTarget integration continuation, exceptions here should never bubble up to the application // * - _continuation(instance, default, default, state); + _continuation!(instance, default, default, state); } catch (Exception contEx) { diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs index ab62b601e..8ff5e7614 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/Continuations/ValueTaskContinuationGenerator`1.cs @@ -23,7 +23,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations; #if NET6_0_OR_GREATER internal class ValueTaskContinuationGenerator : ContinuationGenerator { - private static readonly Func _continuation; + private static readonly Func? _continuation; private static readonly bool _preserveContext; static ValueTaskContinuationGenerator() @@ -31,12 +31,12 @@ internal class ValueTaskContinuationGenerator)result.Method.CreateDelegate(typeof(Func)); + _continuation = (Func)result.Method.CreateDelegate(typeof(Func)); _preserveContext = result.PreserveContext; } } - public override TReturn SetContinuation(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + public override TReturn? SetContinuation(TTarget instance, TReturn? returnValue, Exception? exception, CallTargetState state) { if (_continuation is null) { @@ -52,9 +52,9 @@ internal class ValueTaskContinuationGenerator previousValueTask = FromTReturn>(returnValue); return ToTReturn(InnerSetValueTaskContinuation(instance, previousValueTask, state)); - static async ValueTask InnerSetValueTaskContinuation(TTarget instance, ValueTask previousValueTask, CallTargetState state) + static async ValueTask InnerSetValueTaskContinuation(TTarget instance, ValueTask previousValueTask, CallTargetState state) { - TResult result = default; + TResult? result = default; try { result = await previousValueTask.ConfigureAwait(_preserveContext); @@ -66,7 +66,7 @@ internal class ValueTaskContinuationGenerator { try { - DynamicMethod dynMethod = IntegrationMapper.CreateEndMethodDelegate(typeof(TIntegration), typeof(TTarget)); + DynamicMethod? dynMethod = IntegrationMapper.CreateEndMethodDelegate(typeof(TIntegration), typeof(TTarget)); if (dynMethod != null) { _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/EndMethodHandler`1.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/EndMethodHandler`1.cs index e71ea5ad4..097fb7aac 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/EndMethodHandler`1.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/EndMethodHandler`1.cs @@ -27,15 +27,15 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers; internal static class EndMethodHandler { - private static readonly InvokeDelegate _invokeDelegate = null; - private static readonly ContinuationGenerator _continuationGenerator = null; + private static readonly InvokeDelegate? _invokeDelegate; + private static readonly ContinuationGenerator? _continuationGenerator; static EndMethodHandler() { Type returnType = typeof(TReturn); try { - DynamicMethod dynMethod = IntegrationMapper.CreateEndMethodDelegate(typeof(TIntegration), typeof(TTarget), returnType); + DynamicMethod? dynMethod = IntegrationMapper.CreateEndMethodDelegate(typeof(TIntegration), typeof(TTarget), returnType); if (dynMethod != null) { _invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate)); @@ -52,13 +52,13 @@ internal static class EndMethodHandler if (typeof(Task).IsAssignableFrom(returnType)) { // The type is a Task<> - _continuationGenerator = (ContinuationGenerator)Activator.CreateInstance(typeof(TaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType))); + _continuationGenerator = (ContinuationGenerator?)Activator.CreateInstance(typeof(TaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType))); } #if NET6_0_OR_GREATER else if (genericReturnType == typeof(ValueTask<>)) { // The type is a ValueTask<> - _continuationGenerator = (ContinuationGenerator)Activator.CreateInstance(typeof(ValueTaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType))); + _continuationGenerator = (ContinuationGenerator?)Activator.CreateInstance(typeof(ValueTaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType))); } #endif } @@ -79,10 +79,10 @@ internal static class EndMethodHandler } } - internal delegate CallTargetReturn InvokeDelegate(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state); + internal delegate CallTargetReturn InvokeDelegate(TTarget instance, TReturn? returnValue, Exception exception, CallTargetState state); [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static CallTargetReturn Invoke(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) + internal static CallTargetReturn Invoke(TTarget instance, TReturn? returnValue, Exception exception, CallTargetState state) { if (_continuationGenerator != null) { @@ -95,10 +95,10 @@ internal static class EndMethodHandler if (_invokeDelegate != null) { - CallTargetReturn returnWrap = _invokeDelegate(instance, returnValue, exception, state); + CallTargetReturn returnWrap = _invokeDelegate(instance, returnValue, exception, state); returnValue = returnWrap.GetReturnValue(); } - return new CallTargetReturn(returnValue); + return new CallTargetReturn(returnValue); } } diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationMapper.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationMapper.cs index 2163b09a7..9a34cd9c5 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationMapper.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationMapper.cs @@ -32,10 +32,10 @@ internal class IntegrationMapper private const string EndAsyncMethodName = "OnAsyncMethodEnd"; private static readonly ILogger Log = OtelLogging.GetLogger(); - private static readonly MethodInfo UnwrapReturnValueMethodInfo = typeof(IntegrationMapper).GetMethod(nameof(IntegrationMapper.UnwrapReturnValue), BindingFlags.NonPublic | BindingFlags.Static); - private static readonly MethodInfo ConvertTypeMethodInfo = typeof(IntegrationMapper).GetMethod(nameof(IntegrationMapper.ConvertType), BindingFlags.NonPublic | BindingFlags.Static); + private static readonly MethodInfo UnwrapReturnValueMethodInfo = typeof(IntegrationMapper).GetMethod(nameof(IntegrationMapper.UnwrapReturnValue), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ConvertTypeMethodInfo = typeof(IntegrationMapper).GetMethod(nameof(IntegrationMapper.ConvertType), BindingFlags.NonPublic | BindingFlags.Static)!; - internal static DynamicMethod CreateBeginMethodDelegate(Type integrationType, Type targetType, Type[] argumentsTypes) + internal static DynamicMethod? CreateBeginMethodDelegate(Type integrationType, Type targetType, Type[] argumentsTypes) { /* * OnMethodBegin signatures with 1 or more parameters with 1 or more generics: @@ -51,7 +51,7 @@ internal class IntegrationMapper */ Log.Debug($"Creating BeginMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); - MethodInfo onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onMethodBeginMethodInfo is null) { return null; @@ -86,13 +86,13 @@ internal class IntegrationMapper bool mustLoadInstance = onMethodBeginParameters.Length != argumentsTypes.Length; Type instanceGenericType = genericArgumentsTypes[0]; - Type instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); - Type instanceProxyType = null; + Type? instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); + Type? instanceProxyType = null; if (instanceGenericConstraint != null) { var result = DuckType.GetOrCreateProxyType(instanceGenericConstraint, targetType); instanceProxyType = result.ProxyType; - callGenericTypes.Add(instanceProxyType); + callGenericTypes.Add(instanceProxyType!); } else { @@ -100,7 +100,7 @@ internal class IntegrationMapper } DynamicMethod callMethod = new DynamicMethod( - $"{onMethodBeginMethodInfo.DeclaringType.Name}.{onMethodBeginMethodInfo.Name}", + $"{onMethodBeginMethodInfo.DeclaringType?.Name}.{onMethodBeginMethodInfo.Name}", typeof(CallTargetState), new Type[] { targetType }.Concat(argumentsTypes), onMethodBeginMethodInfo.Module, @@ -115,7 +115,7 @@ internal class IntegrationMapper if (instanceGenericConstraint != null) { - WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + WriteCreateNewProxyInstance(ilWriter, instanceProxyType!, targetType); } } @@ -124,8 +124,8 @@ internal class IntegrationMapper { Type sourceParameterType = argumentsTypes[mustLoadInstance ? i - 1 : i]; Type targetParameterType = onMethodBeginParameters[i].ParameterType; - Type targetParameterTypeConstraint = null; - Type parameterProxyType = null; + Type? targetParameterTypeConstraint = null; + Type? parameterProxyType = null; if (targetParameterType.IsGenericParameter) { @@ -139,7 +139,7 @@ internal class IntegrationMapper { var result = DuckType.GetOrCreateProxyType(targetParameterTypeConstraint, sourceParameterType); parameterProxyType = result.ProxyType; - callGenericTypes.Add(parameterProxyType); + callGenericTypes.Add(parameterProxyType!); } } else if (!targetParameterType.IsAssignableFrom(sourceParameterType) && (!(sourceParameterType.IsEnum && targetParameterType.IsEnum))) @@ -179,7 +179,7 @@ internal class IntegrationMapper */ Log.Debug($"Creating SlowBeginMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); - MethodInfo onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? onMethodBeginMethodInfo = integrationType.GetMethod(BeginMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onMethodBeginMethodInfo is null) { throw new NullReferenceException($"Couldn't find the method: {BeginMethodName} in type: {integrationType.FullName}"); @@ -202,13 +202,13 @@ internal class IntegrationMapper bool mustLoadInstance = onMethodBeginParameters[0].ParameterType.IsGenericParameter && onMethodBeginParameters[0].ParameterType.GenericParameterPosition == 0; Type instanceGenericType = genericArgumentsTypes[0]; - Type instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); - Type instanceProxyType = null; + Type? instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); + Type? instanceProxyType = null; if (instanceGenericConstraint != null) { var result = DuckType.GetOrCreateProxyType(instanceGenericConstraint, targetType); instanceProxyType = result.ProxyType; - callGenericTypes.Add(instanceProxyType); + callGenericTypes.Add(instanceProxyType!); } else { @@ -216,7 +216,7 @@ internal class IntegrationMapper } DynamicMethod callMethod = new DynamicMethod( - $"{onMethodBeginMethodInfo.DeclaringType.Name}.{onMethodBeginMethodInfo.Name}", + $"{onMethodBeginMethodInfo.DeclaringType?.Name}.{onMethodBeginMethodInfo.Name}", typeof(CallTargetState), new Type[] { targetType, typeof(object[]) }, onMethodBeginMethodInfo.Module, @@ -231,7 +231,7 @@ internal class IntegrationMapper if (instanceGenericConstraint != null) { - WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + WriteCreateNewProxyInstance(ilWriter, instanceProxyType!, targetType); } } @@ -239,7 +239,7 @@ internal class IntegrationMapper for (var i = mustLoadInstance ? 1 : 0; i < onMethodBeginParameters.Length; i++) { Type targetParameterType = onMethodBeginParameters[i].ParameterType; - Type targetParameterTypeConstraint = null; + Type? targetParameterTypeConstraint = null; if (targetParameterType.IsGenericParameter) { @@ -280,7 +280,7 @@ internal class IntegrationMapper return callMethod; } - internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type targetType) + internal static DynamicMethod? CreateEndMethodDelegate(Type integrationType, Type targetType) { /* * OnMethodEnd signatures with 2 or 3 parameters with 1 generics: @@ -290,7 +290,7 @@ internal class IntegrationMapper */ Log.Debug($"Creating EndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}]"); - MethodInfo onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onMethodEndMethodInfo is null) { return null; @@ -331,13 +331,13 @@ internal class IntegrationMapper bool mustLoadInstance = onMethodEndParameters.Length == 3; Type instanceGenericType = genericArgumentsTypes[0]; - Type instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); - Type instanceProxyType = null; + Type? instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); + Type? instanceProxyType = null; if (instanceGenericConstraint != null) { var result = DuckType.GetOrCreateProxyType(instanceGenericConstraint, targetType); instanceProxyType = result.ProxyType; - callGenericTypes.Add(instanceProxyType); + callGenericTypes.Add(instanceProxyType!); } else { @@ -345,7 +345,7 @@ internal class IntegrationMapper } DynamicMethod callMethod = new DynamicMethod( - $"{onMethodEndMethodInfo.DeclaringType.Name}.{onMethodEndMethodInfo.Name}", + $"{onMethodEndMethodInfo.DeclaringType?.Name}.{onMethodEndMethodInfo.Name}", typeof(CallTargetReturn), new Type[] { targetType, typeof(Exception), typeof(CallTargetState) }, onMethodEndMethodInfo.Module, @@ -360,7 +360,7 @@ internal class IntegrationMapper if (instanceGenericConstraint != null) { - WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + WriteCreateNewProxyInstance(ilWriter, instanceProxyType!, targetType); } } @@ -380,7 +380,7 @@ internal class IntegrationMapper return callMethod; } - internal static DynamicMethod CreateEndMethodDelegate(Type integrationType, Type targetType, Type returnType) + internal static DynamicMethod? CreateEndMethodDelegate(Type integrationType, Type targetType, Type returnType) { /* * OnMethodEnd signatures with 3 or 4 parameters with 1 or 2 generics: @@ -391,7 +391,7 @@ internal class IntegrationMapper */ Log.Debug($"Creating EndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}, ReturnType={returnType.FullName}]"); - MethodInfo onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? onMethodEndMethodInfo = integrationType.GetMethod(EndMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onMethodEndMethodInfo is null) { return null; @@ -432,13 +432,13 @@ internal class IntegrationMapper bool mustLoadInstance = onMethodEndParameters.Length == 4; Type instanceGenericType = genericArgumentsTypes[0]; - Type instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); - Type instanceProxyType = null; + Type? instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); + Type? instanceProxyType = null; if (instanceGenericConstraint != null) { var result = DuckType.GetOrCreateProxyType(instanceGenericConstraint, targetType); instanceProxyType = result.ProxyType; - callGenericTypes.Add(instanceProxyType); + callGenericTypes.Add(instanceProxyType!); } else { @@ -447,9 +447,9 @@ internal class IntegrationMapper int returnParameterIndex = onMethodEndParameters.Length == 4 ? 1 : 0; bool isAGenericReturnValue = onMethodEndParameters[returnParameterIndex].ParameterType.IsGenericParameter; - Type returnValueGenericType = null; - Type returnValueGenericConstraint = null; - Type returnValueProxyType = null; + Type? returnValueGenericType = null; + Type? returnValueGenericConstraint = null; + Type? returnValueProxyType = null; if (isAGenericReturnValue) { returnValueGenericType = genericArgumentsTypes[1]; @@ -458,7 +458,7 @@ internal class IntegrationMapper { var result = DuckType.GetOrCreateProxyType(returnValueGenericConstraint, returnType); returnValueProxyType = result.ProxyType; - callGenericTypes.Add(returnValueProxyType); + callGenericTypes.Add(returnValueProxyType!); } else { @@ -471,7 +471,7 @@ internal class IntegrationMapper } DynamicMethod callMethod = new DynamicMethod( - $"{onMethodEndMethodInfo.DeclaringType.Name}.{onMethodEndMethodInfo.Name}.{targetType.Name}.{returnType.Name}", + $"{onMethodEndMethodInfo.DeclaringType?.Name}.{onMethodEndMethodInfo.Name}.{targetType.Name}.{returnType.Name}", typeof(CallTargetReturn<>).MakeGenericType(returnType), new Type[] { targetType, returnType, typeof(Exception), typeof(CallTargetState) }, onMethodEndMethodInfo.Module, @@ -486,7 +486,7 @@ internal class IntegrationMapper if (instanceGenericConstraint != null) { - WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + WriteCreateNewProxyInstance(ilWriter, instanceProxyType!, targetType); } } @@ -534,7 +534,7 @@ internal class IntegrationMapper */ Log.Debug($"Creating AsyncEndMethod Dynamic Method for '{integrationType.FullName}' integration. [Target={targetType.FullName}, ReturnType={returnType.FullName}]"); - MethodInfo onAsyncMethodEndMethodInfo = integrationType.GetMethod(EndAsyncMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? onAsyncMethodEndMethodInfo = integrationType.GetMethod(EndAsyncMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (onAsyncMethodEndMethodInfo is null) { Log.Warning($"Couldn't find the method: {EndAsyncMethodName} in type: {integrationType.FullName}"); @@ -578,13 +578,13 @@ internal class IntegrationMapper bool mustLoadInstance = onAsyncMethodEndParameters.Length == 4; Type instanceGenericType = genericArgumentsTypes[0]; - Type instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); - Type instanceProxyType = null; + Type? instanceGenericConstraint = instanceGenericType.GetGenericParameterConstraints().FirstOrDefault(); + Type? instanceProxyType = null; if (instanceGenericConstraint != null) { var result = DuckType.GetOrCreateProxyType(instanceGenericConstraint, targetType); instanceProxyType = result.ProxyType; - callGenericTypes.Add(instanceProxyType); + callGenericTypes.Add(instanceProxyType!); } else { @@ -593,9 +593,9 @@ internal class IntegrationMapper int returnParameterIndex = onAsyncMethodEndParameters.Length == 4 ? 1 : 0; bool isAGenericReturnValue = onAsyncMethodEndParameters[returnParameterIndex].ParameterType.IsGenericParameter; - Type returnValueGenericType = null; - Type returnValueGenericConstraint = null; - Type returnValueProxyType = null; + Type? returnValueGenericType = null; + Type? returnValueGenericConstraint = null; + Type? returnValueProxyType = null; if (isAGenericReturnValue) { returnValueGenericType = genericArgumentsTypes[1]; @@ -604,7 +604,7 @@ internal class IntegrationMapper { var result = DuckType.GetOrCreateProxyType(returnValueGenericConstraint, returnType); returnValueProxyType = result.ProxyType; - callGenericTypes.Add(returnValueProxyType); + callGenericTypes.Add(returnValueProxyType!); } else { @@ -617,7 +617,7 @@ internal class IntegrationMapper } DynamicMethod callMethod = new DynamicMethod( - $"{onAsyncMethodEndMethodInfo.DeclaringType.Name}.{onAsyncMethodEndMethodInfo.Name}.{targetType.Name}.{returnType.Name}", + $"{onAsyncMethodEndMethodInfo.DeclaringType?.Name}.{onAsyncMethodEndMethodInfo.Name}.{targetType.Name}.{returnType.Name}", returnType, new Type[] { targetType, returnType, typeof(Exception), typeof(CallTargetState) }, onAsyncMethodEndMethodInfo.Module, @@ -632,7 +632,7 @@ internal class IntegrationMapper if (instanceGenericConstraint != null) { - WriteCreateNewProxyInstance(ilWriter, instanceProxyType, targetType); + WriteCreateNewProxyInstance(ilWriter, instanceProxyType!, targetType); } } @@ -748,12 +748,12 @@ internal class IntegrationMapper } } - private static T ConvertType(object value) + private static T? ConvertType(object value) { var conversionType = typeof(T); if (value is null || conversionType == typeof(object)) { - return (T)value; + return (T?)value; } Type valueType = value.GetType(); diff --git a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationOptions.cs b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationOptions.cs index 1184b667a..557491fec 100644 --- a/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationOptions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/CallTarget/Handlers/IntegrationOptions.cs @@ -34,10 +34,10 @@ internal static class IntegrationOptions internal static void DisableIntegration() => _disableIntegration = true; [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void LogException(Exception exception, string message = null) + internal static void LogException(Exception exception, string? message = null) { // ReSharper disable twice ExplicitCallerInfoArgument - Log.Error(exception, message ?? exception?.Message); + Log.Error(exception, message ?? exception.Message); if (exception is DuckTypeException) { Log.Warning($"DuckTypeException has been detected, the integration <{typeof(TIntegration)}, {typeof(TTarget)}> will be disabled."); @@ -50,7 +50,7 @@ internal static class IntegrationOptions } else if (exception is FileLoadException fileLoadException) { - if (fileLoadException.FileName.StartsWith("System.Diagnostics.DiagnosticSource") || fileLoadException.FileName.StartsWith("System.Runtime.CompilerServices.Unsafe")) + if (fileLoadException.FileName != null && (fileLoadException.FileName.StartsWith("System.Diagnostics.DiagnosticSource") || fileLoadException.FileName.StartsWith("System.Runtime.CompilerServices.Unsafe"))) { Log.Warning($"FileLoadException for '{fileLoadException.FileName}' has been detected, the integration <{typeof(TIntegration)}, {typeof(TTarget)}> will be disabled."); _disableIntegration = true; diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/CompositeConfigurationSource.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/CompositeConfigurationSource.cs index 98cb993de..7ed064329 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/CompositeConfigurationSource.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/CompositeConfigurationSource.cs @@ -26,7 +26,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration; /// internal class CompositeConfigurationSource : IConfigurationSource, IEnumerable { - private readonly List _sources = new List(); + private readonly List _sources = new(); /// /// Adds a new configuration source to this instance. @@ -58,7 +58,7 @@ internal class CompositeConfigurationSource : IConfigurationSource, IEnumerable< /// /// The key that identifies the setting. /// The value of the setting, or null if not found. - public string GetString(string key) + public string? GetString(string key) { return _sources.Select(source => source.GetString(key)) .FirstOrDefault(value => !string.IsNullOrEmpty(value)); diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationSource.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationSource.cs index 4446ace0c..0a616a17d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationSource.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationSource.cs @@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration; /// internal class EnvironmentConfigurationSource : StringConfigurationSource { - protected override string GetStringInternal(string key) + protected override string? GetStringInternal(string key) { try { diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationTracerHelper.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationTracerHelper.cs index 43c519ebd..b39284b88 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationTracerHelper.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/EnvironmentConfigurationTracerHelper.cs @@ -69,6 +69,11 @@ internal static class EnvironmentConfigurationTracerHelper private static TracerProviderBuilder SetSampler(this TracerProviderBuilder builder, TracerSettings settings) { + if (settings.TracesSampler == null) + { + return builder; + } + var sampler = TracerSamplerHelper.GetSampler(settings.TracesSampler, settings.TracesSamplerArguments); if (sampler == null) diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/IConfigurationSource.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/IConfigurationSource.cs index 745e03e60..81ce54908 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/IConfigurationSource.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/IConfigurationSource.cs @@ -27,7 +27,7 @@ internal interface IConfigurationSource /// /// The key that identifies the setting. /// The value of the setting, or null if not found. - string GetString(string key); + string? GetString(string key); /// /// Gets the value of diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/IntegrationInfo.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/IntegrationInfo.cs index f89bae24b..8343cd2c4 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/IntegrationInfo.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/IntegrationInfo.cs @@ -20,17 +20,12 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration; internal readonly struct IntegrationInfo { - public readonly string Name; + public readonly string? Name; public readonly int Id; public IntegrationInfo(string integrationName) { - if (integrationName == null) - { - throw new ArgumentNullException(nameof(integrationName)); - } - Name = integrationName; Id = 0; } diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/NameValueConfigurationSource.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/NameValueConfigurationSource.cs index 5d8a8b4db..d70718a37 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/NameValueConfigurationSource.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/NameValueConfigurationSource.cs @@ -36,7 +36,7 @@ internal class NameValueConfigurationSource : StringConfigurationSource _nameValueCollection = nameValueCollection; } - protected override string GetStringInternal(string key) + protected override string? GetStringInternal(string key) { return _nameValueCollection[key]; } diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/SdkSettings.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/SdkSettings.cs index 50c77a46c..2f8dd8f72 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/SdkSettings.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/SdkSettings.cs @@ -31,7 +31,7 @@ internal class SdkSettings : Settings if (!string.IsNullOrEmpty(propagators)) { - foreach (var propagator in propagators.Split(Constants.ConfigurationValues.Separator)) + foreach (var propagator in propagators!.Split(Constants.ConfigurationValues.Separator)) { Propagators.Add(ParsePropagator(propagator)); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/Settings.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/Settings.cs index 26efd8231..20b25c407 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/Settings.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/Settings.cs @@ -60,14 +60,14 @@ internal abstract class Settings try { - return (T)typeof(T) - .GetConstructor(new[] { typeof(IConfigurationSource) }) + return (T)typeof(T)! + .GetConstructor(new[] { typeof(IConfigurationSource) })! .Invoke(new object[] { configurationSource }); } catch (TargetInvocationException ex) { // Unwrap the more informative internal exception - throw ex.InnerException; + throw ex.InnerException ?? ex; } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/StringConfigurationSource.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/StringConfigurationSource.cs index 1f7edba16..3c54bd057 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/StringConfigurationSource.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/StringConfigurationSource.cs @@ -25,7 +25,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration; internal abstract class StringConfigurationSource : IConfigurationSource { /// - public virtual string GetString(string key) + public virtual string? GetString(string key) { var value = GetStringInternal(key); if (string.IsNullOrEmpty(value)) @@ -39,9 +39,9 @@ internal abstract class StringConfigurationSource : IConfigurationSource /// public virtual int? GetInt32(string key) { - string value = GetString(key); + var value = GetString(key); - return int.TryParse(value, out int result) + return int.TryParse(value, out var result) ? result : (int?)null; } @@ -49,9 +49,9 @@ internal abstract class StringConfigurationSource : IConfigurationSource /// public double? GetDouble(string key) { - string value = GetString(key); + var value = GetString(key); - return double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out double result) + return double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result) ? result : (double?)null; } @@ -60,8 +60,8 @@ internal abstract class StringConfigurationSource : IConfigurationSource public virtual bool? GetBool(string key) { var value = GetString(key); - return bool.TryParse(value, out bool result) ? result : null; + return bool.TryParse(value, out var result) ? result : null; } - protected abstract string GetStringInternal(string key); + protected abstract string? GetStringInternal(string key); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSamplerHelper.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSamplerHelper.cs index 152772585..19817c87d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSamplerHelper.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSamplerHelper.cs @@ -21,7 +21,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration; internal static class TracerSamplerHelper { - public static Sampler GetSampler(string tracerSampler, string tracerSamplerArguments) + public static Sampler? GetSampler(string tracerSampler, string? tracerSamplerArguments) { switch (tracerSampler) { @@ -42,7 +42,7 @@ internal static class TracerSamplerHelper return null; } - private static TraceIdRatioBasedSampler CreateTraceIdRatioBasedSampler(string arguments) + private static TraceIdRatioBasedSampler CreateTraceIdRatioBasedSampler(string? arguments) { const double defaultRatio = 1.0; diff --git a/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSettings.cs b/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSettings.cs index 21d20b2a1..1475fe407 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSettings.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Configuration/TracerSettings.cs @@ -111,12 +111,12 @@ internal class TracerSettings : Settings /// /// Gets sampler to be used for traces. /// - public string TracesSampler { get; } + public string? TracesSampler { get; } /// /// Gets a value to be used as the sampler argument. /// - public string TracesSamplerArguments { get; } + public string? TracesSamplerArguments { get; } private static TracesExporter ParseTracesExporter(IConfigurationSource source) { diff --git a/src/OpenTelemetry.AutoInstrumentation/Diagnostics/SdkSelfDiagnosticsEventListener.cs b/src/OpenTelemetry.AutoInstrumentation/Diagnostics/SdkSelfDiagnosticsEventListener.cs index 8dd34de7d..a3e1eb55c 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Diagnostics/SdkSelfDiagnosticsEventListener.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Diagnostics/SdkSelfDiagnosticsEventListener.cs @@ -34,23 +34,26 @@ internal class SdkSelfDiagnosticsEventListener : EventListener private readonly object lockObj = new(); private readonly EventLevel logLevel; private readonly ILogger log; - private readonly List eventSourcesBeforeConstructor = new(); + private readonly List? eventSourcesBeforeConstructor = new(); public SdkSelfDiagnosticsEventListener(EventLevel eventLevel, ILogger logger) { log = logger; logLevel = eventLevel; - List eventSources; + List? eventSources; lock (lockObj) { eventSources = this.eventSourcesBeforeConstructor; eventSourcesBeforeConstructor = null; } - foreach (var eventSource in eventSources) + if (eventSources != null) { - EnableEvents(eventSource, logLevel, EventKeywords.All); + foreach (var eventSource in eventSources) + { + EnableEvents(eventSource, logLevel, EventKeywords.All); + } } } @@ -88,24 +91,34 @@ internal class SdkSelfDiagnosticsEventListener : EventListener /// Data of the EventSource event. protected override void OnEventWritten(EventWrittenEventArgs eventData) { - var payloadArray = new object[eventData.Payload.Count]; - eventData.Payload.CopyTo(payloadArray, 0); + object[] payloadArray; + if (eventData.Payload != null) + { + payloadArray = new object[eventData.Payload.Count]; + eventData.Payload.CopyTo(payloadArray, 0); + } + else + { + payloadArray = Array.Empty(); + } + + var message = eventData.Message != null ? string.Format(eventData.Message ?? string.Empty, payloadArray) : string.Empty; switch (eventData.Level) { case EventLevel.Critical: case EventLevel.Error: - log.Error("EventSource={0}, Message={1}", eventData.EventSource.Name, string.Format(eventData.Message, payloadArray)); + log.Error("EventSource={0}, Message={1}", eventData.EventSource.Name, message); break; case EventLevel.Warning: - log.Warning("EventSource={0}, Message={1}", eventData.EventSource.Name, string.Format(eventData.Message, payloadArray)); + log.Warning("EventSource={0}, Message={1}", eventData.EventSource.Name, message); break; case EventLevel.LogAlways: case EventLevel.Informational: - log.Information("EventSource={0}, Message={1}", eventData.EventSource.Name, string.Format(eventData.Message, payloadArray)); + log.Information("EventSource={0}, Message={1}", eventData.EventSource.Name, message); break; case EventLevel.Verbose: - log.Debug("EventSource={0}, Message={1}", eventData.EventSource.Name, string.Format(eventData.Message, payloadArray)); + log.Debug("EventSource={0}, Message={1}", eventData.EventSource.Name, message); break; } } diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttribute.cs index e1e224f85..e0c753f02 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System.Reflection; namespace OpenTelemetry.AutoInstrumentation.DuckTyping; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttributeBase.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttributeBase.cs index b3065be36..c4230e93a 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttributeBase.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckAttributeBase.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Reflection; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckCopyAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckCopyAttribute.cs index ce5fb521b..a7af84950 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckCopyAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckCopyAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; namespace OpenTelemetry.AutoInstrumentation.DuckTyping; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckFieldAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckFieldAttribute.cs index 570ea6c61..850778971 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckFieldAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckFieldAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - namespace OpenTelemetry.AutoInstrumentation.DuckTyping; /// diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIgnoreAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIgnoreAttribute.cs index bc83f9798..f31264130 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIgnoreAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIgnoreAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; namespace OpenTelemetry.AutoInstrumentation.DuckTyping; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIncludeAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIncludeAttribute.cs index d570b801e..2e7970e56 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIncludeAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckIncludeAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; namespace OpenTelemetry.AutoInstrumentation.DuckTyping; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckReverseMethodAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckReverseMethodAttribute.cs index af78a55a4..f5311b34f 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckReverseMethodAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckReverseMethodAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - namespace OpenTelemetry.AutoInstrumentation.DuckTyping; /// diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Fields.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Fields.cs index 6d717f906..53fec66f8 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Fields.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Fields.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Reflection; using System.Reflection.Emit; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Methods.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Methods.cs index 7c8de5203..ad001c234 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Methods.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Methods.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Properties.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Properties.cs index 92a95b7fd..fc44ff7ba 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Properties.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Properties.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Statics.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Statics.cs index 72d8427c5..1359b207f 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Statics.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Statics.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Utilities.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Utilities.cs index 9f14b2fb9..b3a938c1d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Utilities.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.Utilities.cs @@ -14,7 +14,6 @@ // limitations under the License. // -#nullable enable using System; using System.Collections.Generic; using System.Reflection; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.cs index 0edda5d6d..e02301896 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckType.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeConstants.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeConstants.cs index 0e72cbd2f..50b7fd1ef 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeConstants.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeConstants.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - namespace OpenTelemetry.AutoInstrumentation.DuckTyping; internal static class DuckTypeConstants diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExceptions.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExceptions.cs index 7974a5f49..2e0ad4573 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExceptions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExceptions.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExtensions.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExtensions.cs index 9c84a983c..02f03df72 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExtensions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/DuckTypeExtensions.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IDuckType.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IDuckType.cs index 05d7dd15e..9db95f3e3 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IDuckType.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IDuckType.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.ComponentModel; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/ILHelpersExtensions.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/ILHelpersExtensions.cs index 03dae5b32..18dabf9d7 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/ILHelpersExtensions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/ILHelpersExtensions.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IgnoresAccessChecksToAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IgnoresAccessChecksToAttribute.cs index 82e4590ab..a0adca366 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IgnoresAccessChecksToAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/IgnoresAccessChecksToAttribute.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - // ReSharper disable once CheckNamespace namespace System.Runtime.CompilerServices; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/LazyILGenerator.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/LazyILGenerator.cs index 184fffbfb..c411dea3a 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/LazyILGenerator.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/LazyILGenerator.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; using System.Collections.Generic; using System.Reflection; diff --git a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/TypesTuple.cs b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/TypesTuple.cs index 275a90be6..042acbe87 100644 --- a/src/OpenTelemetry.AutoInstrumentation/DuckTyping/TypesTuple.cs +++ b/src/OpenTelemetry.AutoInstrumentation/DuckTyping/TypesTuple.cs @@ -14,8 +14,6 @@ // limitations under the License. // -#nullable enable - using System; namespace OpenTelemetry.AutoInstrumentation.DuckTyping; diff --git a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetCore.cs b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetCore.cs index 7adb5319a..10b9bb926 100644 --- a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetCore.cs +++ b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetCore.cs @@ -23,7 +23,7 @@ namespace OpenTelemetry.AutoInstrumentation; internal partial class FrameworkDescription { - private static FrameworkDescription _instance = null; + private static FrameworkDescription? _instance; public static FrameworkDescription Instance { @@ -85,7 +85,7 @@ internal partial class FrameworkDescription private static string GetNetCoreOrNetFrameworkVersion() { - string productVersion = null; + string? productVersion = null; if (Environment.Version.Major == 3 || Environment.Version.Major >= 5) { diff --git a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetFramework.cs b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetFramework.cs index 6a120b7f2..99133fe2c 100644 --- a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetFramework.cs +++ b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.NetFramework.cs @@ -23,11 +23,26 @@ namespace OpenTelemetry.AutoInstrumentation; internal partial class FrameworkDescription { - private static FrameworkDescription _instance = null; + private static readonly Tuple[] DotNetFrameworkVersionMapping = + { + // known min value for each framework version + Tuple.Create(528040, "4.8"), + Tuple.Create(461808, "4.7.2"), + Tuple.Create(461308, "4.7.1"), + Tuple.Create(460798, "4.7"), + Tuple.Create(394802, "4.6.2"), + Tuple.Create(394254, "4.6.1"), + Tuple.Create(393295, "4.6"), + Tuple.Create(379893, "4.5.2"), + Tuple.Create(378675, "4.5.1"), + Tuple.Create(378389, "4.5"), + }; + + private static FrameworkDescription? _instance; public static FrameworkDescription Instance { - get { return _instance ?? (_instance = Create()); } + get { return _instance ??= Create(); } } public static FrameworkDescription Create() @@ -57,11 +72,11 @@ internal partial class FrameworkDescription private static string GetNetFrameworkVersion() { - string productVersion = null; + string? productVersion = null; try { - object registryValue; + object? registryValue; using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)) using (var subKey = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) diff --git a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.cs b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.cs index 6d273e2e1..f25b1cce9 100644 --- a/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.cs +++ b/src/OpenTelemetry.AutoInstrumentation/FrameworkDescription.cs @@ -26,21 +26,6 @@ internal partial class FrameworkDescription private static readonly Assembly RootAssembly = typeof(object).Assembly; - private static readonly Tuple[] DotNetFrameworkVersionMapping = - { - // known min value for each framework version - Tuple.Create(528040, "4.8"), - Tuple.Create(461808, "4.7.2"), - Tuple.Create(461308, "4.7.1"), - Tuple.Create(460798, "4.7"), - Tuple.Create(394802, "4.6.2"), - Tuple.Create(394254, "4.6.1"), - Tuple.Create(393295, "4.6"), - Tuple.Create(379893, "4.5.2"), - Tuple.Create(378675, "4.5.1"), - Tuple.Create(378389, "4.5"), - }; - private FrameworkDescription( string name, string productVersion, @@ -73,14 +58,14 @@ internal partial class FrameworkDescription return $"{Name} {ProductVersion} {ProcessArchitecture} on {OSPlatform} {OSArchitecture}"; } - private static string GetVersionFromAssemblyAttributes() + private static string? GetVersionFromAssemblyAttributes() { - string productVersion = null; + string? productVersion = null; try { // if we fail to extract version from assembly path, fall back to the [AssemblyInformationalVersion], - var informationalVersionAttribute = (AssemblyInformationalVersionAttribute)RootAssembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)); + var informationalVersionAttribute = RootAssembly.GetCustomAttribute(); // split remove the commit hash from pre-release versions productVersion = informationalVersionAttribute?.InformationalVersion?.Split('+')[0]; @@ -95,7 +80,7 @@ internal partial class FrameworkDescription try { // and if that fails, try [AssemblyFileVersion] - var fileVersionAttribute = (AssemblyFileVersionAttribute)RootAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)); + var fileVersionAttribute = RootAssembly.GetCustomAttribute(); productVersion = fileVersionAttribute?.Version; } catch (Exception e) diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentation.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentation.cs index c59293065..8bc54e9fb 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentation.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentation.cs @@ -40,11 +40,11 @@ internal static class Instrumentation private static int _initialized; private static int _isExiting; - private static SdkSelfDiagnosticsEventListener _sdkEventListener; + private static SdkSelfDiagnosticsEventListener? _sdkEventListener; - private static TracerProvider _tracerProvider; - private static MeterProvider _meterProvider; - private static PluginManager _pluginManager; + private static TracerProvider? _tracerProvider; + private static MeterProvider? _meterProvider; + private static PluginManager? _pluginManager; /// /// Gets a value indicating whether OpenTelemetry's profiler is attached to the current process. @@ -67,7 +67,7 @@ internal static class Instrumentation } } - internal static PluginManager PluginManager => _pluginManager; + internal static PluginManager? PluginManager => _pluginManager; internal static ILifespanManager LifespanManager => LazyInstrumentationLoader.LifespanManager; @@ -152,7 +152,7 @@ internal static class Instrumentation } } - private static void OnExit(object sender, EventArgs e) + private static void OnExit(object? sender, EventArgs e) { if (Interlocked.Exchange(ref _isExiting, value: 1) != 0) { @@ -167,7 +167,7 @@ internal static class Instrumentation #endif _tracerProvider?.Dispose(); _meterProvider?.Dispose(); - _sdkEventListener.Dispose(); + _sdkEventListener?.Dispose(); Logger.Information("OpenTelemetry Automatic Instrumentation exit."); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/ExecuteAsyncIntegration.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/ExecuteAsyncIntegration.cs index 1dfcc3686..3f4032d97 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/ExecuteAsyncIntegration.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/ExecuteAsyncIntegration.cs @@ -15,7 +15,6 @@ // using System; -using System.Diagnostics; using OpenTelemetry.AutoInstrumentation.CallTarget; using OpenTelemetry.AutoInstrumentation.Util; @@ -25,15 +24,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL; /// GraphQL.Execution.ExecutionStrategy calltarget instrumentation /// [GraphQLExecuteAsync( - AssemblyName = GraphQLCommon.GraphQLAssembly, - TypeName = "GraphQL.Execution.ExecutionStrategy", - MinimumVersion = GraphQLCommon.Major2Minor3, - MaximumVersion = GraphQLCommon.Major2)] + assemblyName: GraphQLCommon.GraphQLAssembly, + typeName: "GraphQL.Execution.ExecutionStrategy", + minimumVersion: GraphQLCommon.Major2Minor3, + maximumVersion: GraphQLCommon.Major2)] [GraphQLExecuteAsync( - AssemblyName = GraphQLCommon.GraphQLAssembly, - TypeName = "GraphQL.Execution.SubscriptionExecutionStrategy", - MinimumVersion = GraphQLCommon.Major2Minor3, - MaximumVersion = GraphQLCommon.Major2)] + assemblyName: GraphQLCommon.GraphQLAssembly, + typeName: "GraphQL.Execution.SubscriptionExecutionStrategy", + minimumVersion: GraphQLCommon.Major2Minor3, + maximumVersion: GraphQLCommon.Major2)] public static class ExecuteAsyncIntegration { /// @@ -60,9 +59,9 @@ public static class ExecuteAsyncIntegration /// Exception instance in case the original code threw an exception. /// Calltarget state value /// A response value, in an async scenario will be T of Task of T - internal static TExecutionResult OnAsyncMethodEnd(TTarget instance, TExecutionResult executionResult, Exception exception, CallTargetState state) + internal static TExecutionResult OnAsyncMethodEnd(TTarget instance, TExecutionResult executionResult, Exception? exception, CallTargetState state) { - Activity activity = state.Activity; + var activity = state.Activity; if (activity is null) { return executionResult; @@ -72,7 +71,7 @@ public static class ExecuteAsyncIntegration { if (exception != null) { - activity?.SetException(exception); + activity.SetException(exception); } else if (state.State is IExecutionContext context) { diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLCommon.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLCommon.cs index 290b1654d..411c59c61 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLCommon.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLCommon.cs @@ -35,9 +35,9 @@ internal class GraphQLCommon private static readonly ILogger Log = OtelLogging.GetLogger(); - internal static Activity CreateActivityFromExecuteAsync(IExecutionContext executionContext) + internal static Activity? CreateActivityFromExecuteAsync(IExecutionContext executionContext) { - Activity activity = null; + Activity? activity = null; InstrumentationOptions options = Instrumentation.TracerSettings.Value.InstrumentationOptions; try @@ -73,18 +73,15 @@ internal class GraphQLCommon internal static void RecordExecutionErrorsIfPresent(Activity activity, IExecutionErrors executionErrors) { - var errorCount = executionErrors?.Count ?? 0; + var errorCount = executionErrors.Count; if (errorCount > 0) { for (int i = 0; i < errorCount; i++) { - Exception ex = executionErrors[i].InnerException; + var ex = executionErrors[i].InnerException; - if (ex != null) - { - activity.SetException(ex); - } + activity.SetException(ex); } } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLExecuteAsyncAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLExecuteAsyncAttribute.cs index 2bb5c34b6..6e1390d3b 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLExecuteAsyncAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLExecuteAsyncAttribute.cs @@ -18,12 +18,17 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL; internal class GraphQLExecuteAsyncAttribute : InstrumentMethodAttribute { - public GraphQLExecuteAsyncAttribute() + public GraphQLExecuteAsyncAttribute(string assemblyName, string typeName, string minimumVersion, string maximumVersion) + : base( + assemblyName: assemblyName, + typeName: typeName, + methodName: "ExecuteAsync", + returnTypeName: "System.Threading.Tasks.Task`1[GraphQL.ExecutionResult]", + parameterTypeNames: new[] { "GraphQL.Execution.ExecutionContext" }, + minimumVersion: minimumVersion, + maximumVersion: maximumVersion, + integrationName: GraphQLCommon.IntegrationName, + type: InstrumentationType.Trace) { - IntegrationName = GraphQLCommon.IntegrationName; - MethodName = "ExecuteAsync"; - ReturnTypeName = "System.Threading.Tasks.Task`1[GraphQL.ExecutionResult]"; - ParameterTypeNames = new[] { "GraphQL.Execution.ExecutionContext" }; - Type = InstrumentationType.Trace; } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLTags.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLTags.cs index 477076706..a21ee317e 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLTags.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/GraphQL/GraphQLTags.cs @@ -21,17 +21,17 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL; internal class GraphQLTags : InstrumentationTags { - protected static readonly IProperty[] GraphQLTagsProperties = + protected static readonly IProperty[] GraphQLTagsProperties = InstrumentationTagsProperties.Concat( - new Property(Tags.GraphQL.Document, t => t.Document, (t, v) => t.Document = v), - new Property(Tags.GraphQL.OperationName, t => t.OperationName, (t, v) => t.OperationName = v), - new Property(Tags.GraphQL.OperationType, t => t.OperationType, (t, v) => t.OperationType = v)); + new Property(Tags.GraphQL.Document, t => t.Document), + new Property(Tags.GraphQL.OperationName, t => t.OperationName), + new Property(Tags.GraphQL.OperationType, t => t.OperationType)); - public string Document { get; set; } + public string? Document { get; set; } - public string OperationName { get; set; } + public string? OperationName { get; set; } - public string OperationType { get; set; } + public string? OperationType { get; set; } - protected override IProperty[] GetAdditionalTags() => GraphQLTagsProperties; + protected override IProperty[] GetAdditionalTags() => GraphQLTagsProperties; } diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/InstrumentMethodAttribute.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/InstrumentMethodAttribute.cs index a42aca916..9922067f4 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/InstrumentMethodAttribute.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/InstrumentMethodAttribute.cs @@ -25,76 +25,68 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] internal class InstrumentMethodAttribute : Attribute { - /// - /// Gets or sets the name of the assembly that contains the target method to be intercepted. - /// Required if is not set. - /// - public string AssemblyName + public InstrumentMethodAttribute(string assemblyName, string typeName, string methodName, string returnTypeName, string[] parameterTypeNames, string minimumVersion, string maximumVersion, string integrationName, InstrumentationType type) { - get + AssemblyName = assemblyName; + TypeName = typeName; + MethodName = methodName; + ReturnTypeName = returnTypeName; + ParameterTypeNames = parameterTypeNames; + VersionRange = new IntegrationVersionRange { - switch (AssemblyNames?.Length ?? 0) - { - case 0: - return null; - case 1: - return AssemblyNames[0]; - default: - throw new NotSupportedException("Multiple assemblies are not supported using this property. Use AssemblyNames property instead."); - } - } - set => AssemblyNames = new[] { value }; + MinimumVersion = minimumVersion, + MaximumVersion = maximumVersion + }; + IntegrationName = integrationName; + Type = type; } /// - /// Gets or sets the name of the assemblies that contain the target method to be intercepted. - /// Required if is not set. + /// Gets the name of the assembly that contains the target method to be intercepted. /// - public string[] AssemblyNames { get; set; } + public string AssemblyName { get; } /// - /// Gets or sets the name of the type that contains the target method to be intercepted. + /// Gets the name of the type that contains the target method to be intercepted. /// Required. /// - public string TypeName { get; set; } + public string TypeName { get; } /// - /// Gets or sets the name of the target method to be intercepted. + /// Gets the name of the target method to be intercepted. /// If null, default to the name of the decorated method. /// - public string MethodName { get; set; } + public string MethodName { get; } /// - /// Gets or sets the return type name + /// Gets the return type name /// - public string ReturnTypeName { get; set; } + public string ReturnTypeName { get; } /// - /// Gets or sets the parameters type array for the target method to be intercepted. + /// Gets the parameters type array for the target method to be intercepted. /// - public string[] ParameterTypeNames { get; set; } + public string[] ParameterTypeNames { get; } /// /// Gets the target version range for . /// - public IntegrationVersionRange VersionRange { get; } = new(); + public IntegrationVersionRange VersionRange { get; } /// - /// Gets or sets the target minimum version. + /// Gets the target minimum version. /// public string MinimumVersion { get => VersionRange.MinimumVersion; - set => VersionRange.MinimumVersion = value; } /// - /// Gets or sets the target maximum version. + /// Gets the target maximum version. /// public string MaximumVersion { get => VersionRange.MaximumVersion; - set => VersionRange.MaximumVersion = value; } /// diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/Logger/LoggingBuilderIntegration.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/Logger/LoggingBuilderIntegration.cs index 5a1e40a76..641886a35 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/Logger/LoggingBuilderIntegration.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/Logger/LoggingBuilderIntegration.cs @@ -23,15 +23,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.Logger; /// Microsoft.Extensions.Logging.LoggingBuilder calltarget instrumentation /// [InstrumentMethod( - AssemblyName = "Microsoft.Extensions.Logging", - TypeName = "Microsoft.Extensions.Logging.LoggingBuilder", - MethodName = ".ctor", - ReturnTypeName = ClrNames.Void, - ParameterTypeNames = new[] { "Microsoft.Extensions.DependencyInjection.IServiceCollection" }, - MinimumVersion = "3.1.0", - MaximumVersion = "7.*.*", - IntegrationName = "ILogger", - Type = InstrumentationType.Log)] + assemblyName: "Microsoft.Extensions.Logging", + typeName: "Microsoft.Extensions.Logging.LoggingBuilder", + methodName: ".ctor", + returnTypeName: ClrNames.Void, + parameterTypeNames: new[] { "Microsoft.Extensions.DependencyInjection.IServiceCollection" }, + minimumVersion: "3.1.0", + maximumVersion: "7.*.*", + integrationName: "ILogger", + type: InstrumentationType.Log)] public static class LoggingBuilderIntegration { /// diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MongoDb/MongoClientIntegration.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MongoDb/MongoClientIntegration.cs index 16ab1af7e..de0b74bd6 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MongoDb/MongoClientIntegration.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MongoDb/MongoClientIntegration.cs @@ -29,19 +29,19 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.MongoDB; /// MongoDB.Driver.MongoClient calltarget instrumentation /// [InstrumentMethod( - AssemblyName = "MongoDB.Driver", - TypeName = "MongoDB.Driver.MongoClient", - MethodName = ".ctor", - ReturnTypeName = ClrNames.Void, - ParameterTypeNames = new[] { "MongoDB.Driver.MongoClientSettings" }, - MinimumVersion = "2.13.3", - MaximumVersion = "2.65535.65535", - IntegrationName = "MongoDB", - Type = InstrumentationType.Trace)] + assemblyName: "MongoDB.Driver", + typeName: "MongoDB.Driver.MongoClient", + methodName: ".ctor", + returnTypeName: ClrNames.Void, + parameterTypeNames: new[] { "MongoDB.Driver.MongoClientSettings" }, + minimumVersion: "2.13.3", + maximumVersion: "2.65535.65535", + integrationName: "MongoDB", + type: InstrumentationType.Trace)] public static class MongoClientIntegration { #if NET6_0_OR_GREATER - private static Delegate _setActivityListener; + private static Delegate? _setActivityListener; #endif /// @@ -53,6 +53,7 @@ public static class MongoClientIntegration /// The source of the original GraphQL query /// Calltarget state value internal static CallTargetState OnMethodBegin(TTarget instance, TMongoClientSettings settings) + where TMongoClientSettings : notnull { // Additional deps doesn't support .NET FX // TODO: Find another way how to ship & load "MongoDB.Driver.Core.Extensions.DiagnosticSources" @@ -74,9 +75,9 @@ public static class MongoClientIntegration #if NET6_0_OR_GREATER private static object GetInstrumentationOptions() { - Type optionsType = Type.GetType("MongoDB.Driver.Core.Extensions.DiagnosticSources.InstrumentationOptions, MongoDB.Driver.Core.Extensions.DiagnosticSources"); + Type optionsType = Type.GetType("MongoDB.Driver.Core.Extensions.DiagnosticSources.InstrumentationOptions, MongoDB.Driver.Core.Extensions.DiagnosticSources")!; - var options = Activator.CreateInstance(optionsType); + var options = Activator.CreateInstance(optionsType)!; var publicProperty = BindingFlags.Public | BindingFlags.Instance; var shouldStartActivityLambda = GetShouldStartActivityExpression(); @@ -90,11 +91,11 @@ public static class MongoClientIntegration { Expression> shouldStartActivity = (string cmdName) => !Regex.IsMatch(cmdName, "isMaster|buildInfo|explain|killCursors", RegexOptions.Compiled); - Type eventType = Type.GetType("MongoDB.Driver.Core.Events.CommandStartedEvent, MongoDB.Driver.Core"); + Type eventType = Type.GetType("MongoDB.Driver.Core.Events.CommandStartedEvent, MongoDB.Driver.Core")!; Type lambdaType = typeof(Func<,>).MakeGenericType(eventType, typeof(bool)); var commandStartedEventParam = Expression.Parameter(eventType); - var commandNameProperty = eventType.GetProperty("CommandName"); + var commandNameProperty = eventType.GetProperty("CommandName")!; var invokeExpression = Expression.Invoke(shouldStartActivity, Expression.MakeMemberAccess(commandStartedEventParam, commandNameProperty)); var shouldStartActivityLambda = Expression.Lambda(lambdaType, invokeExpression, commandStartedEventParam); @@ -103,15 +104,15 @@ public static class MongoClientIntegration private static LambdaExpression GetClusterConfiguratorExpression() { - Type eventSubscriberInterface = Type.GetType("MongoDB.Driver.Core.Events.IEventSubscriber, MongoDB.Driver.Core"); - Type clusterBuilderType = Type.GetType("MongoDB.Driver.Core.Configuration.ClusterBuilder, MongoDB.Driver.Core"); - Type listenerType = Type.GetType("MongoDB.Driver.Core.Extensions.DiagnosticSources.DiagnosticsActivityEventSubscriber, MongoDB.Driver.Core.Extensions.DiagnosticSources"); + Type eventSubscriberInterface = Type.GetType("MongoDB.Driver.Core.Events.IEventSubscriber, MongoDB.Driver.Core")!; + Type clusterBuilderType = Type.GetType("MongoDB.Driver.Core.Configuration.ClusterBuilder, MongoDB.Driver.Core")!; + Type listenerType = Type.GetType("MongoDB.Driver.Core.Extensions.DiagnosticSources.DiagnosticsActivityEventSubscriber, MongoDB.Driver.Core.Extensions.DiagnosticSources")!; var options = GetInstrumentationOptions(); var listener = Activator.CreateInstance(listenerType, options); var mi = clusterBuilderType.GetMethods() - .FirstOrDefault(x => + .First(x => x.Name == "Subscribe" && x.GetParameters().All(p => p.ParameterType == eventSubscriberInterface)); diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MySqlData/MySqlConnectionStringBuilderIntegration.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MySqlData/MySqlConnectionStringBuilderIntegration.cs index 712aacd5d..b19d05864 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MySqlData/MySqlConnectionStringBuilderIntegration.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/MySqlData/MySqlConnectionStringBuilderIntegration.cs @@ -23,14 +23,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.MySqlData; /// MySql.Data.MySqlClient.MySqlConnectionStringBuilder calltarget instrumentation /// [InstrumentMethod( - AssemblyName = "MySql.Data", - TypeName = "MySql.Data.MySqlClient.MySqlConnectionStringBuilder", - MethodName = "get_Logging", - ReturnTypeName = ClrNames.Bool, - ParameterTypeNames = new string[0], - MinimumVersion = "8.0.31", - MaximumVersion = "8.65535.65535", - IntegrationName = "MySqlData")] + assemblyName: "MySql.Data", + typeName: "MySql.Data.MySqlClient.MySqlConnectionStringBuilder", + methodName: "get_Logging", + returnTypeName: ClrNames.Bool, + parameterTypeNames: new string[0], + minimumVersion: "8.0.31", + maximumVersion: "8.65535.65535", + integrationName: "MySqlData", + type: InstrumentationType.Trace)] public static class MySqlConnectionStringBuilderIntegration { #if !NETFRAMEWORK diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisInitializer.cs index 48d6758cb..53ab2e173 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisInitializer.cs @@ -25,19 +25,16 @@ internal static class StackExchangeRedisInitializer { public static void Initialize(object connection) { - if (connection != null && Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.StackExchangeRedis)) - { - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentation, OpenTelemetry.Instrumentation.StackExchangeRedis"); - var optionsInstrumentationType = Type.GetType("OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions, OpenTelemetry.Instrumentation.StackExchangeRedis"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentation, OpenTelemetry.Instrumentation.StackExchangeRedis")!; + var optionsInstrumentationType = Type.GetType("OpenTelemetry.Instrumentation.StackExchangeRedis.StackExchangeRedisCallsInstrumentationOptions, OpenTelemetry.Instrumentation.StackExchangeRedis")!; - var options = Activator.CreateInstance(optionsInstrumentationType); + var options = Activator.CreateInstance(optionsInstrumentationType)!; - Instrumentation.PluginManager.ConfigureTracesOptions(options); + Instrumentation.PluginManager?.ConfigureTracesOptions(options); - var instrumentation = Activator.CreateInstance(instrumentationType, connection, options); + var instrumentation = Activator.CreateInstance(instrumentationType, connection, options)!; - Instrumentation.LifespanManager.Track(instrumentation); - } + Instrumentation.LifespanManager.Track(instrumentation); } } #endif diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegration.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegration.cs index 8a5f3e13b..b3011ad30 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegration.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegration.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.AutoInstrumentation.CallTarget; +using OpenTelemetry.AutoInstrumentation.Configuration; namespace OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis; @@ -23,45 +24,45 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis; /// StackExchange.Redis.ConnectionMultiplexer calltarget instrumentation /// [InstrumentMethod(// releases 2.0.495 - 2.1.39 - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplMethodName, - ReturnTypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { ClrNames.Object, StackExchangeRedisConstants.TextWriterTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplMethodName, + returnTypeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + parameterTypeNames: new[] { ClrNames.Object, StackExchangeRedisConstants.TextWriterTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] [InstrumentMethod(// releases 2.1.50 - 2.5.43 - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplMethodName, - ReturnTypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplMethodName, + returnTypeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + parameterTypeNames: new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] [InstrumentMethod(// releases 2.5.61 - 2.6.48 - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplMethodName, - ReturnTypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplMethodName, + returnTypeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + parameterTypeNames: new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] [InstrumentMethod(// releases 2.6.66+ - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplMethodName, - ReturnTypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName, StackExchangeRedisConstants.EndPointCollectionTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplMethodName, + returnTypeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + parameterTypeNames: new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName, StackExchangeRedisConstants.EndPointCollectionTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] public static class StackExchangeRedisIntegration { /// @@ -76,7 +77,10 @@ public static class StackExchangeRedisIntegration internal static CallTargetReturn OnMethodEnd(TReturn returnValue, Exception exception, CallTargetState state) { #if NET6_0_OR_GREATER - StackExchangeRedisInitializer.Initialize(returnValue); + if (returnValue != null && Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.StackExchangeRedis)) + { + StackExchangeRedisInitializer.Initialize(returnValue); + } #endif return new CallTargetReturn(returnValue); diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegrationAsync.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegrationAsync.cs index 67c9afe31..c1e0b5aae 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegrationAsync.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StackExchangeRedis/StackExchangeRedisIntegrationAsync.cs @@ -16,6 +16,7 @@ using System; using OpenTelemetry.AutoInstrumentation.CallTarget; +using OpenTelemetry.AutoInstrumentation.Configuration; namespace OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis; @@ -23,35 +24,35 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.StackExchangeRedis; /// StackExchange.Redis.ConnectionMultiplexer calltarget instrumentation /// [InstrumentMethod(// releases 2.0.495 - 2.1.39 - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplAsyncMethodName, - ReturnTypeName = StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { ClrNames.Object, StackExchangeRedisConstants.TextWriterTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplAsyncMethodName, + returnTypeName: StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, + parameterTypeNames: new[] { ClrNames.Object, StackExchangeRedisConstants.TextWriterTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] [InstrumentMethod(// releases 2.1.50 - 2.5.43 - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplAsyncMethodName, - ReturnTypeName = StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplAsyncMethodName, + returnTypeName: StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, + parameterTypeNames: new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] [InstrumentMethod(// releases 2.5.61+ - AssemblyName = StackExchangeRedisConstants.AssemblyName, - TypeName = StackExchangeRedisConstants.ConnectionMultiplexerTypeName, - MethodName = StackExchangeRedisConstants.ConnectImplAsyncMethodName, - ReturnTypeName = StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, - ParameterTypeNames = new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName }, - MinimumVersion = StackExchangeRedisConstants.MinimumVersion, - MaximumVersion = StackExchangeRedisConstants.MaximumVersion, - IntegrationName = StackExchangeRedisConstants.IntegrationName, - Type = InstrumentationType.Trace)] + assemblyName: StackExchangeRedisConstants.AssemblyName, + typeName: StackExchangeRedisConstants.ConnectionMultiplexerTypeName, + methodName: StackExchangeRedisConstants.ConnectImplAsyncMethodName, + returnTypeName: StackExchangeRedisConstants.TaskConnectionMultiplexerTypeName, + parameterTypeNames: new[] { StackExchangeRedisConstants.ConfigurationOptionsTypeName, StackExchangeRedisConstants.TextWriterTypeName, StackExchangeRedisConstants.NullableServerTypeTypeName }, + minimumVersion: StackExchangeRedisConstants.MinimumVersion, + maximumVersion: StackExchangeRedisConstants.MaximumVersion, + integrationName: StackExchangeRedisConstants.IntegrationName, + type: InstrumentationType.Trace)] public static class StackExchangeRedisIntegrationAsync { /// @@ -67,7 +68,10 @@ public static class StackExchangeRedisIntegrationAsync internal static TReturn OnAsyncMethodEnd(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { #if NET6_0_OR_GREATER - StackExchangeRedisInitializer.Initialize(returnValue); + if (returnValue != null && Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.StackExchangeRedis)) + { + StackExchangeRedisInitializer.Initialize(returnValue); + } #endif return returnValue; diff --git a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StrongNamedValidation/StrongNamedValidation.cs b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StrongNamedValidation/StrongNamedValidation.cs index 9d0f599c1..5256df316 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StrongNamedValidation/StrongNamedValidation.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Instrumentations/StrongNamedValidation/StrongNamedValidation.cs @@ -26,15 +26,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.Validations; /// is added we can remove this instrumentation. /// [InstrumentMethod( - AssemblyName = "TestLibrary.InstrumentationTarget", - TypeName = "TestLibrary.InstrumentationTarget.Command", - MethodName = "Execute", - ReturnTypeName = ClrNames.Void, - ParameterTypeNames = new string[0], - MinimumVersion = "1.0.0", - MaximumVersion = "1.65535.65535", - IntegrationName = "StrongNamedValidation", - Type = InstrumentationType.Trace)] + assemblyName: "TestLibrary.InstrumentationTarget", + typeName: "TestLibrary.InstrumentationTarget.Command", + methodName: "Execute", + returnTypeName: ClrNames.Void, + parameterTypeNames: new string[0], + minimumVersion: "1.0.0", + maximumVersion: "1.65535.65535", + integrationName: "StrongNamedValidation", + type: InstrumentationType.Trace)] public static class StrongNamedValidation { private static readonly ActivitySource ValidationActivitySource = new ActivitySource("TestApplication.StrongNamedValidation"); diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreInitializer.cs index 5efd7ee46..e1b7c5e74 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreInitializer.cs @@ -32,14 +32,14 @@ internal class AspNetCoreInitializer : InstrumentationInitializer public override void Initialize(ILifespanManager lifespanManager) { - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentation, OpenTelemetry.Instrumentation.AspNetCore"); - var httpInListenerType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.Implementation.HttpInListener, OpenTelemetry.Instrumentation.AspNetCore"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentation, OpenTelemetry.Instrumentation.AspNetCore")!; + var httpInListenerType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.Implementation.HttpInListener, OpenTelemetry.Instrumentation.AspNetCore")!; var options = new OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreInstrumentationOptions(); _pluginManager.ConfigureTracesOptions(options); var httpInListener = Activator.CreateInstance(httpInListenerType, args: options); - var instrumentation = Activator.CreateInstance(instrumentationType, args: httpInListener); + var instrumentation = Activator.CreateInstance(instrumentationType, args: httpInListener)!; lifespanManager.Track(instrumentation); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreMetricsInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreMetricsInitializer.cs index be9db9ccd..748d4c5bd 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreMetricsInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/AspNetCoreMetricsInitializer.cs @@ -31,14 +31,13 @@ internal class AspNetCoreMetricsInitializer : InstrumentationInitializer public override void Initialize(ILifespanManager lifespanManager) { - var optionsType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreMetricsInstrumentationOptions, OpenTelemetry.Instrumentation.AspNetCore"); - var metricsType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreMetrics, OpenTelemetry.Instrumentation.AspNetCore"); + var metricsType = Type.GetType("OpenTelemetry.Instrumentation.AspNetCore.AspNetCoreMetrics, OpenTelemetry.Instrumentation.AspNetCore")!; var aspNetCoreMetricsInstrumentationOptions = new AspNetCoreMetricsInstrumentationOptions(); - Instrumentation.PluginManager.ConfigureMetricsOptions(aspNetCoreMetricsInstrumentationOptions); + Instrumentation.PluginManager?.ConfigureMetricsOptions(aspNetCoreMetricsInstrumentationOptions); - var constructor = metricsType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, new[] { typeof(AspNetCoreMetricsInstrumentationOptions) }); + var constructor = metricsType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, new[] { typeof(AspNetCoreMetricsInstrumentationOptions) })!; var aspNetCoreMetrics = constructor.Invoke(new[] { aspNetCoreMetricsInstrumentationOptions }); lifespanManager.Track(aspNetCoreMetrics); diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/GrpcClientInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/GrpcClientInitializer.cs index 53d27cfe2..7a5e4bcfe 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/GrpcClientInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/GrpcClientInitializer.cs @@ -32,14 +32,16 @@ internal class GrpcClientInitializer : InstrumentationInitializer public override void Initialize(ILifespanManager lifespanManager) { - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentation, OpenTelemetry.Instrumentation.GrpcNetClient"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentation, OpenTelemetry.Instrumentation.GrpcNetClient")!; - var options = new OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions(); - options.SuppressDownstreamInstrumentation = !Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.HttpClient); + var options = new OpenTelemetry.Instrumentation.GrpcNetClient.GrpcClientInstrumentationOptions + { + SuppressDownstreamInstrumentation = !Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.HttpClient) + }; _pluginManager.ConfigureTracesOptions(options); - var instrumentation = Activator.CreateInstance(instrumentationType, options); + var instrumentation = Activator.CreateInstance(instrumentationType, options)!; lifespanManager.Track(instrumentation); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientInitializer.cs index a0f65a0ec..d509de97b 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientInitializer.cs @@ -50,12 +50,12 @@ internal class HttpClientInitializer _pluginManager.ConfigureTracesOptions(options); #if NETFRAMEWORK - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.Implementation.HttpWebRequestActivitySource, OpenTelemetry.Instrumentation.Http"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.Implementation.HttpWebRequestActivitySource, OpenTelemetry.Instrumentation.Http")!; instrumentationType.GetField("Options", BindingFlags.NonPublic | BindingFlags.Static)?.SetValue(null, options); #else - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.HttpClientInstrumentation, OpenTelemetry.Instrumentation.Http"); - var instrumentation = Activator.CreateInstance(instrumentationType, options); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.HttpClientInstrumentation, OpenTelemetry.Instrumentation.Http")!; + var instrumentation = Activator.CreateInstance(instrumentationType, options)!; lifespanManager.Track(instrumentation); #endif diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientMetricsInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientMetricsInitializer.cs index 8e0efb823..6f70bbeae 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientMetricsInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/HttpClientMetricsInitializer.cs @@ -40,8 +40,8 @@ internal class HttpClientMetricsInitializer return; } - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.HttpClientMetrics, OpenTelemetry.Instrumentation.Http"); - var instrumentation = Activator.CreateInstance(instrumentationType); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Http.HttpClientMetrics, OpenTelemetry.Instrumentation.Http")!; + var instrumentation = Activator.CreateInstance(instrumentationType)!; lifespanManager.Track(instrumentation); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/MySqlDataInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/MySqlDataInitializer.cs index b1b4e8c8f..314f46fbc 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/MySqlDataInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/MySqlDataInitializer.cs @@ -33,12 +33,12 @@ internal class MySqlDataInitializer : InstrumentationInitializer public override void Initialize(ILifespanManager lifespanManager) { - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.MySqlData.MySqlDataInstrumentation, OpenTelemetry.Instrumentation.MySqlData"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.MySqlData.MySqlDataInstrumentation, OpenTelemetry.Instrumentation.MySqlData")!; var options = new OpenTelemetry.Instrumentation.MySqlData.MySqlDataInstrumentationOptions(); _pluginManager.ConfigureTracesOptions(options); - var instrumentation = Activator.CreateInstance(instrumentationType, options); + var instrumentation = Activator.CreateInstance(instrumentationType, options)!; lifespanManager.Track(instrumentation); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/SqlClientInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/SqlClientInitializer.cs index c429d9d91..3beb9832b 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/SqlClientInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/SqlClientInitializer.cs @@ -44,12 +44,12 @@ internal class SqlClientInitializer return; } - var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.SqlClient.SqlClientInstrumentation, OpenTelemetry.Instrumentation.SqlClient"); + var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.SqlClient.SqlClientInstrumentation, OpenTelemetry.Instrumentation.SqlClient")!; var options = new OpenTelemetry.Instrumentation.SqlClient.SqlClientInstrumentationOptions(); _pluginManager.ConfigureTracesOptions(options); - var instrumentation = Activator.CreateInstance(instrumentationType, options); + var instrumentation = Activator.CreateInstance(instrumentationType, options)!; lifespanManager.Track(instrumentation); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/WcfInitializer.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/WcfInitializer.cs index bcf3ee452..65fd8479c 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/WcfInitializer.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/Initializers/WcfInitializer.cs @@ -42,6 +42,6 @@ internal class WcfInitializer : InstrumentationInitializer var instrumentationType = Type.GetType("OpenTelemetry.Instrumentation.Wcf.WcfInstrumentationActivitySource, OpenTelemetry.Instrumentation.Wcf"); - instrumentationType.GetProperty("Options")?.SetValue(null, options); + instrumentationType?.GetProperty("Options")?.SetValue(null, options); } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Loading/LazyInstrumentationLoader.cs b/src/OpenTelemetry.AutoInstrumentation/Loading/LazyInstrumentationLoader.cs index d7262fdcd..d3bd79a4d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Loading/LazyInstrumentationLoader.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Loading/LazyInstrumentationLoader.cs @@ -81,7 +81,7 @@ internal class LazyInstrumentationLoader : IDisposable #endif } - private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) + private void CurrentDomain_AssemblyLoad(object? sender, AssemblyLoadEventArgs args) { var assemblyName = GetAssemblyName(args.LoadedAssembly); @@ -116,9 +116,9 @@ internal class LazyInstrumentationLoader : IDisposable } } - private string GetAssemblyName(Assembly assembly) + private string? GetAssemblyName(Assembly assembly) { - return assembly.FullName.Split(new[] { ',' }, count: 2)[0]; + return assembly.FullName?.Split(new[] { ',' }, count: 2)[0]; } } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Logger/LogBuilderExtensions.cs b/src/OpenTelemetry.AutoInstrumentation/Logger/LogBuilderExtensions.cs index 8ab331898..b59671e42 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Logger/LogBuilderExtensions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Logger/LogBuilderExtensions.cs @@ -31,7 +31,7 @@ internal static class LogBuilderExtensions { try { - if (!(builder?.Services is ServiceCollection services)) + if (!(builder.Services is ServiceCollection services)) { return builder; } @@ -52,11 +52,14 @@ internal static class LogBuilderExtensions options.IncludeFormattedMessage = settings.IncludeFormattedMessage; - pluginManager.ConfigureLogsOptions(options); + pluginManager?.ConfigureLogsOptions(options); if (settings.ConsoleExporterEnabled) { - options.AddConsoleExporter(pluginManager.ConfigureLogsOptions); + if (pluginManager != null) + { + options.AddConsoleExporter(pluginManager.ConfigureLogsOptions); + } } switch (settings.LogExporter) @@ -69,7 +72,7 @@ internal static class LogBuilderExtensions otlpOptions.Protocol = settings.OtlpExportProtocol.Value; } - pluginManager.ConfigureLogsOptions(otlpOptions); + pluginManager?.ConfigureLogsOptions(otlpOptions); }); break; case LogExporter.None: diff --git a/src/OpenTelemetry.AutoInstrumentation/Logging/CustomLogger.cs b/src/OpenTelemetry.AutoInstrumentation/Logging/CustomLogger.cs index 642508810..21eb4169a 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Logging/CustomLogger.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Logging/CustomLogger.cs @@ -156,34 +156,34 @@ internal class CustomLogger : ILogger public void Error(Exception exception, string messageTemplate, object[] args, [CallerLineNumber] int sourceLine = 0, [CallerFilePath] string sourceFile = "") => Write(LogLevel.Error, exception, messageTemplate, args, sourceLine, sourceFile); - private void Write(LogLevel level, Exception exception, string messageTemplate, T property, int sourceLine, string sourceFile) + private void Write(LogLevel level, Exception? exception, string messageTemplate, T property, int sourceLine, string sourceFile) { if (IsEnabled(level)) { // Avoid boxing + array allocation if disabled - WriteImpl(level, exception, messageTemplate, new object[] { property }, sourceLine, sourceFile); + WriteImpl(level, exception, messageTemplate, new object?[] { property }, sourceLine, sourceFile); } } - private void Write(LogLevel level, Exception exception, string messageTemplate, T0 property0, T1 property1, int sourceLine, string sourceFile) + private void Write(LogLevel level, Exception? exception, string messageTemplate, T0 property0, T1 property1, int sourceLine, string sourceFile) { if (IsEnabled(level)) { // Avoid boxing + array allocation if disabled - WriteImpl(level, exception, messageTemplate, new object[] { property0, property1 }, sourceLine, sourceFile); + WriteImpl(level, exception, messageTemplate, new object?[] { property0, property1 }, sourceLine, sourceFile); } } - private void Write(LogLevel level, Exception exception, string messageTemplate, T0 property0, T1 property1, T2 property2, int sourceLine, string sourceFile) + private void Write(LogLevel level, Exception? exception, string messageTemplate, T0 property0, T1 property1, T2 property2, int sourceLine, string sourceFile) { if (IsEnabled(level)) { // Avoid boxing + array allocation if disabled - WriteImpl(level, exception, messageTemplate, new object[] { property0, property1, property2 }, sourceLine, sourceFile); + WriteImpl(level, exception, messageTemplate, new object?[] { property0, property1, property2 }, sourceLine, sourceFile); } } - private void Write(LogLevel level, Exception exception, string messageTemplate, object[] args, int sourceLine, string sourceFile) + private void Write(LogLevel level, Exception? exception, string messageTemplate, object[] args, int sourceLine, string sourceFile) { if (IsEnabled(level)) { @@ -192,7 +192,7 @@ internal class CustomLogger : ILogger } } - private void WriteImpl(LogLevel level, Exception exception, string messageTemplate, object[] args, int sourceLine, string sourceFile) + private void WriteImpl(LogLevel level, Exception? exception, string messageTemplate, object?[] args, int sourceLine, string sourceFile) { try { diff --git a/src/OpenTelemetry.AutoInstrumentation/Logging/OtelLogging.cs b/src/OpenTelemetry.AutoInstrumentation/Logging/OtelLogging.cs index b160fedf6..fa91fca6d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Logging/OtelLogging.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Logging/OtelLogging.cs @@ -32,7 +32,7 @@ internal static class OtelLogging static OtelLogging() { - ISink sink = null; + ISink? sink = null; try { var logDirectory = GetLogDirectory(); @@ -74,9 +74,9 @@ internal static class OtelLogging } } - private static string GetLogDirectory() + private static string? GetLogDirectory() { - string logDirectory; + string? logDirectory; try { @@ -113,7 +113,7 @@ internal static class OtelLogging return logDirectory; } - private static string CreateDirectoryIfMissing(string pathToCreate) + private static string? CreateDirectoryIfMissing(string pathToCreate) { try { diff --git a/src/OpenTelemetry.AutoInstrumentation/OpenTelemetry.AutoInstrumentation.csproj b/src/OpenTelemetry.AutoInstrumentation/OpenTelemetry.AutoInstrumentation.csproj index bb99335e8..9f40ae8a2 100644 --- a/src/OpenTelemetry.AutoInstrumentation/OpenTelemetry.AutoInstrumentation.csproj +++ b/src/OpenTelemetry.AutoInstrumentation/OpenTelemetry.AutoInstrumentation.csproj @@ -4,7 +4,6 @@ 0.5.1 - disable diff --git a/src/OpenTelemetry.AutoInstrumentation/Plugins/PluginManager.cs b/src/OpenTelemetry.AutoInstrumentation/Plugins/PluginManager.cs index b59bc0169..924c3e503 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Plugins/PluginManager.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Plugins/PluginManager.cs @@ -32,8 +32,8 @@ internal class PluginManager foreach (var assemblyQualifiedName in settings.Plugins) { - var type = Type.GetType(assemblyQualifiedName, throwOnError: true); - var instance = Activator.CreateInstance(type); + var type = Type.GetType(assemblyQualifiedName, throwOnError: true)!; + var instance = Activator.CreateInstance(type)!; plugins.Add((type, instance)); } @@ -64,11 +64,13 @@ internal class PluginManager } public void ConfigureMetricsOptions(T options) + where T : notnull { ConfigureOptions(options, "ConfigureMetricsOptions"); } public void ConfigureTracesOptions(T options) + where T : notnull { ConfigureOptions(options, "ConfigureTracesOptions"); } @@ -79,11 +81,13 @@ internal class PluginManager } public void ConfigureLogsOptions(T options) + where T : notnull { ConfigureOptions(options, "ConfigureLogsOptions"); } private void ConfigureOptions(T options, string methodName) + where T : notnull { ConfigureOptions(typeof(T), options, methodName); } @@ -95,19 +99,20 @@ internal class PluginManager var mi = plugin.Type.GetMethod(methodName, new[] { type }); if (mi is not null) { - mi.Invoke(plugin.Instance, new object[] { options }); + mi.Invoke(plugin.Instance, new[] { options }); } } } private T ConfigureBuilder(T builder, string methodName) + where T : notnull { foreach (var plugin in _plugins) { var mi = plugin.Type.GetMethod(methodName, new[] { typeof(T) }); if (mi is not null) { - builder = (T)mi.Invoke(plugin.Instance, new object[] { builder }); + mi.Invoke(plugin.Instance, new object[] { builder }); } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/IProperty.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/IProperty.cs index 512d1b7b2..cc48eb57c 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/IProperty.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/IProperty.cs @@ -18,13 +18,11 @@ using System; namespace OpenTelemetry.AutoInstrumentation.Tagging; -internal interface IProperty +internal interface IProperty { bool IsReadOnly { get; } string Key { get; } Func Getter { get; } - - Action Setter { get; } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/ITags.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/ITags.cs index dce6e89dc..eca414738 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/ITags.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/ITags.cs @@ -21,8 +21,4 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging; internal interface ITags { List> GetAllTags(); - - string GetTag(string key); - - void SetTag(string key, string value); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/InstrumentationTags.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/InstrumentationTags.cs index b1d485bf1..1e9e0e107 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/InstrumentationTags.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/InstrumentationTags.cs @@ -18,9 +18,9 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging; internal abstract class InstrumentationTags : TagsList { - protected static readonly IProperty[] InstrumentationTagsProperties = + protected static readonly IProperty[] InstrumentationTagsProperties = { }; - protected override IProperty[] GetAdditionalTags() => InstrumentationTagsProperties; + protected override IProperty[] GetAdditionalTags() => InstrumentationTagsProperties; } diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/Property.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/Property.cs index 74ade1a53..3c9c524d7 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/Property.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/Property.cs @@ -20,11 +20,10 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging; internal class Property : IProperty { - public Property(string key, Func getter, Action setter) + public Property(string key, Func getter) { Key = key; Getter = tags => getter((TTags)tags); - Setter = (tags, value) => setter((TTags)tags, value); } public virtual bool IsReadOnly => false; @@ -32,6 +31,4 @@ internal class Property : IProperty public string Key { get; } public Func Getter { get; } - - public Action Setter { get; } } diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/ReadOnlyProperty.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/ReadOnlyProperty.cs deleted file mode 100644 index 326e76a2a..000000000 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/ReadOnlyProperty.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; - -namespace OpenTelemetry.AutoInstrumentation.Tagging; - -internal class ReadOnlyProperty : Property -{ - public ReadOnlyProperty(string key, Func getter) - : base(key, getter, (_, _) => { }) - { - } - - public override bool IsReadOnly => true; -} diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/Tags.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/Tags.cs index 446748855..0a4118265 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/Tags.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/Tags.cs @@ -26,11 +26,6 @@ internal static class Tags /// public const string OutHost = "out.host"; - /// - /// The port of a outgoing server connection. - /// - public const string OutPort = "out.port"; - /// /// GraphQL specific tags /// diff --git a/src/OpenTelemetry.AutoInstrumentation/Tagging/TagsList.cs b/src/OpenTelemetry.AutoInstrumentation/Tagging/TagsList.cs index 943a2d660..469b0a7b2 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Tagging/TagsList.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Tagging/TagsList.cs @@ -17,30 +17,17 @@ using System; using System.Collections.Generic; using System.Text; -using System.Threading; namespace OpenTelemetry.AutoInstrumentation.Tagging; internal abstract class TagsList : ITags { - private List> _tags; - public List> GetAllTags() { - var customTags = GetCustomTags(); var additionalTags = GetAdditionalTags(); var allTags = new List>( - customTags?.Count ?? 0 + additionalTags?.Length ?? 0); - if (customTags != null) - { - lock (customTags) - { - allTags.AddRange(customTags); - } - } - if (additionalTags != null) { lock (additionalTags) @@ -60,100 +47,10 @@ internal abstract class TagsList : ITags return allTags; } - public string GetTag(string key) - { - foreach (var property in GetAdditionalTags()) - { - if (property.Key == key) - { - return property.Getter(this); - } - } - - var tags = GetCustomTags(); - - if (tags == null) - { - return null; - } - - lock (tags) - { - for (int i = 0; i < tags.Count; i++) - { - if (tags[i].Key == key) - { - return tags[i].Value; - } - } - } - - return null; - } - - public void SetTag(string key, string value) - { - foreach (var property in GetAdditionalTags()) - { - if (property.Key == key) - { - property.Setter(this, value); - return; - } - } - - var tags = GetCustomTags(); - - if (tags == null) - { - var newTags = new List>(); - tags = Interlocked.CompareExchange(ref _tags, newTags, null) ?? newTags; - } - - lock (tags) - { - for (int i = 0; i < tags.Count; i++) - { - if (tags[i].Key == key) - { - if (value == null) - { - tags.RemoveAt(i); - } - else - { - tags[i] = new KeyValuePair(key, value); - } - - return; - } - } - - // If we get there, the tag wasn't in the collection - if (value != null) - { - tags.Add(new KeyValuePair(key, value)); - } - } - } - public override string ToString() { var sb = new StringBuilder(); - var tags = GetCustomTags(); - - if (tags != null) - { - lock (tags) - { - foreach (var pair in tags) - { - sb.Append($"{pair.Key} (tag):{pair.Value},"); - } - } - } - foreach (var property in GetAdditionalTags()) { var value = property.Getter(this); @@ -167,7 +64,5 @@ internal abstract class TagsList : ITags return sb.ToString(); } - protected virtual IProperty[] GetAdditionalTags() => Array.Empty>(); - - protected virtual IList> GetCustomTags() => Volatile.Read(ref _tags); + protected virtual IProperty[] GetAdditionalTags() => Array.Empty>(); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/ActivityHelper.cs b/src/OpenTelemetry.AutoInstrumentation/Util/ActivityHelper.cs index 4a8c78d57..03fa9ea3d 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Util/ActivityHelper.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Util/ActivityHelper.cs @@ -31,7 +31,7 @@ internal static class ActivityHelper /// /// The activity to include exception info. /// The exception. - public static void SetException(this Activity activity, Exception exception) + public static void SetException(this Activity? activity, Exception? exception) { if (activity == null) { @@ -48,7 +48,7 @@ internal static class ActivityHelper activity.RecordException(exception); } - public static Activity StartActivityWithTags(this ActivitySource activitySource, string operationName, ActivityKind kind, ITags tags) + public static Activity? StartActivityWithTags(this ActivitySource? activitySource, string operationName, ActivityKind kind, ITags tags) { if (activitySource == null) { @@ -58,7 +58,7 @@ internal static class ActivityHelper var activity = activitySource.StartActivity(operationName, kind); - if (activity == null || tags == null) + if (activity == null) { return activity; } diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/ConfigurationSourceExtensions.cs b/src/OpenTelemetry.AutoInstrumentation/Util/ConfigurationSourceExtensions.cs index fafaa1a6b..3df612e60 100644 --- a/src/OpenTelemetry.AutoInstrumentation/Util/ConfigurationSourceExtensions.cs +++ b/src/OpenTelemetry.AutoInstrumentation/Util/ConfigurationSourceExtensions.cs @@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.Util; internal static class ConfigurationSourceExtensions { public static IList ParseEnabledEnumList(this IConfigurationSource source, string enabledConfiguration, string disabledConfiguration, string error) - where TEnum : struct, IConvertible + where TEnum : struct, Enum, IConvertible { var instrumentations = new Dictionary(); var enabledInstrumentations = source.GetString(enabledConfiguration); @@ -52,7 +52,7 @@ internal static class ConfigurationSourceExtensions instrumentations = Enum.GetValues(typeof(TEnum)) .Cast() .ToDictionary( - key => Enum.GetName(typeof(TEnum), key), + key => Enum.GetName(typeof(TEnum), key)!, val => val); } diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/DomainMetadata.cs b/src/OpenTelemetry.AutoInstrumentation/Util/DomainMetadata.cs deleted file mode 100644 index 49d184c92..000000000 --- a/src/OpenTelemetry.AutoInstrumentation/Util/DomainMetadata.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; - -namespace OpenTelemetry.AutoInstrumentation.Util; - -/// -/// Dedicated helper class for consistently referencing Process and AppDomain information. -/// -internal static class DomainMetadata -{ - private const string UnknownName = "unknown"; - private static bool _initialized; - private static string _currentProcessName; - private static string _currentProcessMachineName; - private static int _currentProcessId; - private static bool _processDataUnavailable; - private static bool _domainDataPoisoned; - private static bool? _isAppInsightsAppDomain; - - static DomainMetadata() - { - TrySetProcess(); - } - - public static string ProcessName - { - get - { - return !_processDataUnavailable ? _currentProcessName : UnknownName; - } - } - - public static string MachineName - { - get - { - return !_processDataUnavailable ? _currentProcessMachineName : UnknownName; - } - } - - public static int ProcessId - { - get - { - return !_processDataUnavailable ? _currentProcessId : -1; - } - } - - public static string AppDomainName - { - get - { - try - { - return !_domainDataPoisoned ? AppDomain.CurrentDomain.FriendlyName : UnknownName; - } - catch - { - _domainDataPoisoned = true; - return UnknownName; - } - } - } - - public static int AppDomainId - { - get - { - try - { - return !_domainDataPoisoned ? AppDomain.CurrentDomain.Id : -1; - } - catch - { - _domainDataPoisoned = true; - return -1; - } - } - } - - public static bool ShouldAvoidAppDomain() - { - if (_isAppInsightsAppDomain == null) - { - _isAppInsightsAppDomain = AppDomainName.IndexOf("ApplicationInsights", StringComparison.OrdinalIgnoreCase) >= 0; - } - - return _isAppInsightsAppDomain.Value; - } - - private static void TrySetProcess() - { - try - { - if (!_processDataUnavailable && !_initialized) - { - _initialized = true; - ProcessHelpers.GetCurrentProcessInformation(out _currentProcessName, out _currentProcessMachineName, out _currentProcessId); - } - } - catch - { - _processDataUnavailable = true; - } - } -} diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/Interception.cs b/src/OpenTelemetry.AutoInstrumentation/Util/Interception.cs deleted file mode 100644 index 22920ea6a..000000000 --- a/src/OpenTelemetry.AutoInstrumentation/Util/Interception.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System; -using System.Diagnostics; - -namespace OpenTelemetry.AutoInstrumentation.Util; - -/// -/// Convenience properties and methods for integration definitions. -/// -internal static class Interception -{ - internal const Type[] NullTypeArray = null; - internal static readonly object[] NoArgObjects = Array.Empty(); - internal static readonly Type[] NoArgTypes = Type.EmptyTypes; - internal static readonly Type VoidType = typeof(void); - - internal static Type[] ParamsToTypes(params object[] objectsToCheck) - { - var types = new Type[objectsToCheck.Length]; - - for (var i = 0; i < objectsToCheck.Length; i++) - { - types[i] = objectsToCheck[i]?.GetType(); - } - - return types; - } - - internal static string MethodKey( - Type owningType, - Type returnType, - Type[] genericTypes, - Type[] parameterTypes) - { - var key = $"{owningType?.AssemblyQualifiedName}_m_r{returnType?.AssemblyQualifiedName}"; - - for (ushort i = 0; i < (genericTypes?.Length ?? 0); i++) - { - Debug.Assert(genericTypes != null, nameof(genericTypes) + " != null"); - key = string.Concat(key, $"_g{genericTypes[i].AssemblyQualifiedName}"); - } - - for (ushort i = 0; i < (parameterTypes?.Length ?? 0); i++) - { - Debug.Assert(parameterTypes != null, nameof(parameterTypes) + " != null"); - key = string.Concat(key, $"_p{parameterTypes[i].AssemblyQualifiedName}"); - } - - return key; - } -} diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/ProcessHelpers.cs b/src/OpenTelemetry.AutoInstrumentation/Util/ProcessHelpers.cs deleted file mode 100644 index 86863bbb1..000000000 --- a/src/OpenTelemetry.AutoInstrumentation/Util/ProcessHelpers.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace OpenTelemetry.AutoInstrumentation.Util; - -internal static class ProcessHelpers -{ - /// - /// Wrapper around and its property accesses - /// - /// On .NET Framework the class is guarded by a - /// LinkDemand for FullTrust, so partial trust callers will throw an exception. - /// This exception is thrown when the caller method is being JIT compiled, NOT - /// when Process.GetCurrentProcess is called, so this wrapper method allows - /// us to catch the exception. - /// - /// The name of the current process - /// The machine name of the current process - /// The ID of the current process - [MethodImpl(MethodImplOptions.NoInlining)] - public static void GetCurrentProcessInformation(out string processName, out string machineName, out int processId) - { - using (var currentProcess = Process.GetCurrentProcess()) - { - processName = currentProcess.ProcessName; - machineName = currentProcess.MachineName; - processId = currentProcess.Id; - } - } -} diff --git a/src/OpenTelemetry.AutoInstrumentation/Util/PropertyFetcher.cs b/src/OpenTelemetry.AutoInstrumentation/Util/PropertyFetcher.cs deleted file mode 100644 index d04fc5dca..000000000 --- a/src/OpenTelemetry.AutoInstrumentation/Util/PropertyFetcher.cs +++ /dev/null @@ -1,127 +0,0 @@ -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// From https://github.com/dotnet/runtime/blob/master/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs - -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace OpenTelemetry.AutoInstrumentation.Util; - -internal class PropertyFetcher -{ - private readonly string _propertyName; - private Type _expectedType; - private object _fetchForExpectedType; - - /// - /// Initializes a new instance of the class. - /// - /// The name of the property that this instance will fetch. - public PropertyFetcher(string propertyName) - { - _propertyName = propertyName; - } - - /// - /// Gets the value of the property on the specified object. - /// - /// Type of the result. - /// The object that contains the property. - /// The value of the property on the specified object. - public T Fetch(object obj) - { - return Fetch(obj, obj.GetType()); - } - - /// - /// Gets the value of the property on the specified object. - /// - /// Type of the result. - /// The object that contains the property. - /// Type of the object - /// The value of the property on the specified object. - public T Fetch(object obj, Type objType) - { - if (objType != _expectedType) - { - var propertyInfo = objType.GetProperty(_propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase); - _fetchForExpectedType = PropertyFetch.FetcherForProperty(propertyInfo); - _expectedType = objType; - } - - return ((PropertyFetch)_fetchForExpectedType).Fetch(obj); - } - - /// - /// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how - /// to efficiently fetch that property from a .NET object (See Fetch method). - /// It hides some slightly complex generic code. - /// - /// Return type of the property. - private class PropertyFetch - { - private readonly Func _propertyFetch; - - private PropertyFetch() - { - _propertyFetch = _ => default; - } - - private PropertyFetch(PropertyInfo propertyInfo) - { - // Generate lambda: arg => (T)((TObject)arg).get_property(); - var param = Expression.Parameter(typeof(object), "arg"); // arg => - var cast = Expression.Convert(param, propertyInfo.DeclaringType); // (TObject)arg - var propertyFetch = Expression.Property(cast, propertyInfo); // get_property() - var castResult = Expression.Convert(propertyFetch, typeof(T)); // (T)result - - // Generate the actual lambda - var lambda = Expression.Lambda(typeof(Func), castResult, param); - - // Compile it for faster access - _propertyFetch = (Func)lambda.Compile(); - } - - /// - /// Create a property fetcher from a .NET Reflection class that - /// represents a property of a particular type. - /// - /// The property that this instance will fetch. - /// The new property fetcher. - public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo) - { - if (propertyInfo == null) - { - // returns null on any fetch. - return new PropertyFetch(); - } - - return new PropertyFetch(propertyInfo); - } - - /// - /// Gets the value of the property on the specified object. - /// - /// The object that contains the property. - /// The value of the property on the specified object. - public T Fetch(object obj) - { - return _propertyFetch(obj); - } - } -} diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/PluginManagerTests.cs b/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/PluginManagerTests.cs index fd5d2e96a..9be9db1b3 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/PluginManagerTests.cs +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/PluginManagerTests.cs @@ -23,7 +23,6 @@ using Microsoft.Extensions.Logging; using Moq; using OpenTelemetry.AutoInstrumentation.Configuration; using OpenTelemetry.AutoInstrumentation.Plugins; -using OpenTelemetry.Exporter; using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; @@ -59,10 +58,23 @@ public class PluginManagerTests } } + [Fact] + public void MissingDefaultConstructor() + { + var pluginAssemblyQualifiedName = typeof(PluginWithoutDefaultConstructor).AssemblyQualifiedName!; + var settings = GetSettings(pluginAssemblyQualifiedName); + var createAction = () => new PluginManager(settings); + + using (new AssertionScope()) + { + createAction.Should().Throw(); + } + } + [Fact] public void PluginTypeMissingMethodDoesNotThrow() { - var pluginAssemblyQualifiedName = GetType().AssemblyQualifiedName; + var pluginAssemblyQualifiedName = GetType().AssemblyQualifiedName!; var settings = GetSettings(pluginAssemblyQualifiedName); var pluginManager = new PluginManager(settings); @@ -79,7 +91,7 @@ public class PluginManagerTests [Fact] public void PluginTypeMissingDefaultConstructor() { - var pluginAssemblyQualifiedName = typeof(MockPluginMissingDefaultConstructor).AssemblyQualifiedName; + var pluginAssemblyQualifiedName = typeof(MockPluginMissingDefaultConstructor).AssemblyQualifiedName!; var settings = GetSettings(pluginAssemblyQualifiedName); var createAction = () => new PluginManager(settings); @@ -92,7 +104,7 @@ public class PluginManagerTests [Fact] public void InvokeProviderPluginSuccess() { - var pluginAssemblyQualifiedName = typeof(MockPlugin).AssemblyQualifiedName; + var pluginAssemblyQualifiedName = typeof(MockPlugin).AssemblyQualifiedName!; var settings = GetSettings(pluginAssemblyQualifiedName); var pluginManager = new PluginManager(settings); @@ -118,7 +130,7 @@ public class PluginManagerTests [Fact] public void ConfigureLogsOptionsSuccess() { - var pluginAssemblyQualifiedName = typeof(MockPlugin).AssemblyQualifiedName; + var pluginAssemblyQualifiedName = typeof(MockPlugin).AssemblyQualifiedName!; var settings = GetSettings(pluginAssemblyQualifiedName); var pluginManager = new PluginManager(settings); @@ -173,6 +185,23 @@ public class PluginManagerTests } } + public class PluginWithoutDefaultConstructor + { + private readonly string _dummyParameter; + + public PluginWithoutDefaultConstructor(string dummyParameter) + { + _dummyParameter = dummyParameter; + } + + public TracerProviderBuilder ConfigureTracerProvider(TracerProviderBuilder builder) + { + builder.AddSource(_dummyParameter); + + return builder; + } + } + public class MockPluginMissingDefaultConstructor : MockPlugin { public MockPluginMissingDefaultConstructor(string ignored) diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/TracerSamplerHelperTests.cs b/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/TracerSamplerHelperTests.cs index fb6b81f0e..2d3158fd7 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/TracerSamplerHelperTests.cs +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/Configuration/TracerSamplerHelperTests.cs @@ -38,7 +38,8 @@ public class TracerSamplerHelperTests { var sampler = TracerSamplerHelper.GetSampler(tracesSampler, tracerSamplerArguments); - sampler.Description.Should().Be(expectedDescription); + sampler.Should().NotBeNull(); + sampler!.Description.Should().Be(expectedDescription); } [Theory] diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/Loading/LazyInstrumentationLoaderTests.cs b/test/OpenTelemetry.AutoInstrumentation.Tests/Loading/LazyInstrumentationLoaderTests.cs index 0b93e3925..a9b8f3648 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/Loading/LazyInstrumentationLoaderTests.cs +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/Loading/LazyInstrumentationLoaderTests.cs @@ -48,7 +48,7 @@ public class LazyInstrumentationLoaderTests { var assemblyName = new AssemblyName(DummyInitializer.DummyAssemblyName); var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); - assemblyBuilder.DefineDynamicModule(assemblyName.Name); + assemblyBuilder.DefineDynamicModule(assemblyName.Name!); } private class DummyInitializer : InstrumentationInitializer, IDisposable diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/OpenTelemetry.AutoInstrumentation.Tests.csproj b/test/OpenTelemetry.AutoInstrumentation.Tests/OpenTelemetry.AutoInstrumentation.Tests.csproj index 8c76299f1..a5df10287 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/OpenTelemetry.AutoInstrumentation.Tests.csproj +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/OpenTelemetry.AutoInstrumentation.Tests.csproj @@ -2,7 +2,6 @@ true - disable diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ActivityHelperTests.cs b/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ActivityHelperTests.cs index b6aaea5a1..11ef797a6 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ActivityHelperTests.cs +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ActivityHelperTests.cs @@ -32,7 +32,7 @@ public class ActivityHelperTests [Fact] public void SetException_NotThrow_WhenActivityIsNull() { - const Activity activity = null; + const Activity? activity = null; var action = () => activity.SetException(new Exception()); @@ -72,9 +72,9 @@ public class ActivityHelperTests [Fact] public void StartActivityWithTags_ReturnsNull_WhenActivitySourceIsNull() { - const ActivitySource activitySource = null; + const ActivitySource? activitySource = null; - using var activity = activitySource.StartActivityWithTags("test-operation", ActivityKind.Internal, null); + using var activity = activitySource.StartActivityWithTags("test-operation", ActivityKind.Internal, Mock.Of()); activity.Should().BeNull(); } @@ -84,7 +84,7 @@ public class ActivityHelperTests { using var activitySource = new ActivitySource("test-source"); - using var activity = activitySource.StartActivityWithTags("test-operation", ActivityKind.Internal, null); + using var activity = activitySource.StartActivityWithTags("test-operation", ActivityKind.Internal, Mock.Of()); using (new AssertionScope()) { @@ -101,17 +101,20 @@ public class ActivityHelperTests [InlineData(ActivityKind.Consumer)] public void StartActivityWithTags_ReturnsActivity_WhenThereIsActivityListener(ActivityKind kind) { + var tagsMock = new Mock(); + tagsMock.Setup(x => x.GetAllTags()).Returns(new List>()); + using var activitySource = new ActivitySource("test-source"); using var listener = CreateActivityListener(activitySource); - using var activity = activitySource.StartActivityWithTags("test-operation", kind, null); + using var activity = activitySource.StartActivityWithTags("test-operation", kind, tagsMock.Object); using (new AssertionScope()) { activitySource.HasListeners().Should().BeTrue(); activity.Should().NotBeNull(); - activity.Kind.Should().Be(kind); + activity?.Kind.Should().Be(kind); } } @@ -139,7 +142,7 @@ public class ActivityHelperTests { activitySource.HasListeners().Should().BeTrue(); activity.Should().NotBeNull(); - activity.Tags.Should().BeEquivalentTo(tags); + activity?.Tags.Should().BeEquivalentTo(tags); } } diff --git a/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ConfigurationSourceExtensionsTests.cs b/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ConfigurationSourceExtensionsTests.cs index 256379c55..2b2a24bc2 100644 --- a/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ConfigurationSourceExtensionsTests.cs +++ b/test/OpenTelemetry.AutoInstrumentation.Tests/Util/ConfigurationSourceExtensionsTests.cs @@ -161,7 +161,7 @@ public class ConfigurationSourceExtensionsTests private class DummyStringConfigurationSource : StringConfigurationSource { - protected override string GetStringInternal(string key) + protected override string? GetStringInternal(string key) { if (key == "TEST_NULL_VALUE") { diff --git a/tools/IntegrationsJsonGenerator/Integration.cs b/tools/IntegrationsJsonGenerator/Integration.cs index 6cd28bedd..2949725f5 100644 --- a/tools/IntegrationsJsonGenerator/Integration.cs +++ b/tools/IntegrationsJsonGenerator/Integration.cs @@ -20,11 +20,11 @@ using System.Text.Json.Serialization; internal class Integration { [JsonPropertyName("name")] - public string Name { get; set; } + required public string Name { get; init; } [JsonPropertyName("type")] - public string Type { get; set; } + required public string Type { get; init; } [JsonPropertyName("method_replacements")] - public IList MethodReplacements { get; set; } + required public IList MethodReplacements { get; init; } } diff --git a/tools/IntegrationsJsonGenerator/IntegrationsJsonGenerator.csproj b/tools/IntegrationsJsonGenerator/IntegrationsJsonGenerator.csproj index 3fa33cc01..b14069964 100644 --- a/tools/IntegrationsJsonGenerator/IntegrationsJsonGenerator.csproj +++ b/tools/IntegrationsJsonGenerator/IntegrationsJsonGenerator.csproj @@ -3,7 +3,6 @@ Exe net7.0 - disable diff --git a/tools/IntegrationsJsonGenerator/Program.cs b/tools/IntegrationsJsonGenerator/Program.cs index d81965ff6..405bcb444 100644 --- a/tools/IntegrationsJsonGenerator/Program.cs +++ b/tools/IntegrationsJsonGenerator/Program.cs @@ -41,7 +41,7 @@ foreach (var typeInfo in autoInstrumentationLib.GetTypes()) foreach (var attribute in typeInfo.GetCustomAttributes() .Where(a => assemblyInstrumentMethodAttributes.Contains(a.GetType().FullName))) { - var integration = ConvertToIntegration(typeInfo.FullName, attribute); + var integration = ConvertToIntegration(typeInfo.FullName!, attribute); if (!integrations.ContainsKey(integration.IntegrationName)) { @@ -92,7 +92,7 @@ bool InheritsFrom(Type type, string baseType) (string IntegartionType, string IntegrationName, MethodReplacement MethodReplacement) ConvertToIntegration(string wrapperTypeName, Attribute attribute) { var integrationName = GetPropertyValue("IntegrationName", attribute); - var integrationType = GetPropertyValue("Type", attribute).ToString(); + var integrationType = GetPropertyValue("Type", attribute).ToString()!; var methodReplacement = new MethodReplacement { @@ -141,14 +141,14 @@ bool InheritsFrom(Type type, string baseType) T GetPropertyValue(string propertyName, Attribute attribute) { var type = attribute.GetType(); - var getMethod = type.GetProperty(propertyName).GetGetMethod(); + var getMethod = type.GetProperty(propertyName)!.GetGetMethod()!; if (!getMethod.ReturnType.IsAssignableTo(typeof(T))) { throw new ArgumentException($"Property {propertyName} is not assignable to {typeof(T)}"); } - var value = getMethod.Invoke(attribute, Array.Empty()); + var value = getMethod.Invoke(attribute, Array.Empty())!; return (T)value; } @@ -162,7 +162,7 @@ void UpdateIntegrationFile(string filePath, Integration[] productionIntegrations JsonSerializer.Serialize(fileStream, productionIntegrations1, jsonSerializerOptions); } -static string GetSourceFilePathName([CallerFilePath] string callerFilePath = null) +static string GetSourceFilePathName([CallerFilePath] string? callerFilePath = null) => callerFilePath ?? string.Empty; static Integration AppendMockIntegrations(Integration testIntegration) diff --git a/tools/IntegrationsJsonGenerator/Target.cs b/tools/IntegrationsJsonGenerator/Target.cs index e4c834b63..ca7794a59 100644 --- a/tools/IntegrationsJsonGenerator/Target.cs +++ b/tools/IntegrationsJsonGenerator/Target.cs @@ -19,16 +19,16 @@ using System.Text.Json.Serialization; internal class Target { [JsonPropertyName("assembly")] - public string Assembly { get; set; } + public string? Assembly { get; set; } [JsonPropertyName("type")] - public string Type { get; set; } + public string? Type { get; set; } [JsonPropertyName("method")] - public string Method { get; set; } + public string? Method { get; set; } [JsonPropertyName("signature_types")] - public string[] SignatureTypes { get; set; } + public string[]? SignatureTypes { get; set; } [JsonPropertyName("minimum_major")] public int MinimumMajor { get; set; } diff --git a/tools/IntegrationsJsonGenerator/Wrapper.cs b/tools/IntegrationsJsonGenerator/Wrapper.cs index f713ffcbe..afd0c1ce5 100644 --- a/tools/IntegrationsJsonGenerator/Wrapper.cs +++ b/tools/IntegrationsJsonGenerator/Wrapper.cs @@ -22,7 +22,7 @@ internal class Wrapper public string Assembly { get; set; } = "OpenTelemetry.AutoInstrumentation"; [JsonPropertyName("type")] - public string Type { get; set; } + public string? Type { get; set; } [JsonPropertyName("action")] public string Action { get; set; } = "CallTargetModification";