Enable nullable for main project (#1861)

* nullable

* nullable util

* nullable Tagging

* nullable logging

* nullable loading

* nullable configuration

* nullable CallTarget

* nullable calltarget-handlers-continuation

* nullable calltarget handlers

* fix tests

* leftovers

* cleanup #nullable enable

* update publicapi

* nullable AutoInstrumentation.Tests

* IntegrationsJsonGenerator

* dotnet format

* pr feedback

* pr feedback - plugin manager

* pr feedback StackExchangeRedisInitializer

* pr feedback - attributes names for instrument method

* PR feedback stack exchange Redis part 2

Co-authored-by: Paulo Janotti <pjanotti@splunk.com>
This commit is contained in:
Piotr Kiełkowicz 2022-12-21 21:45:28 +01:00 committed by GitHub
parent 07dbe0e28e
commit 46896a72ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
113 changed files with 531 additions and 1038 deletions

View File

@ -4,6 +4,6 @@
<PropertyGroup>
<IsPackable>false</IsPackable>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<LangVersion>10.0</LangVersion>
<LangVersion>11.0</LangVersion>
</PropertyGroup>
</Project>

View File

@ -6,13 +6,12 @@ OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.CallTargetRetur
OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.CallTargetReturn(T returnValue) -> void
OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.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<T>.ToString() -> string
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.ToString() -> string!
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string!
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(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<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(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<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(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<TIntegration, TTarget, TArg1, TArg2>(TTarget instance, TArg1 arg1, TArg2 arg2) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget, TArg1>(TTarget instance, TArg1 arg1) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance, object[] arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<TReturn>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget>(TTarget instance, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue<T>() -> T
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException<TIntegration, TTarget>(System.Exception exception) -> void
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance, object![]! arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<TReturn?>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget>(TTarget instance, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue<T>() -> T?
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException<TIntegration, TTarget>(System.Exception! exception) -> void
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState

View File

@ -6,13 +6,12 @@ OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.CallTargetRetur
OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.CallTargetReturn(T returnValue) -> void
OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.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<T>.ToString() -> string
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.ToString() -> string!
override OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.ToString() -> string!
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(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<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(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<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(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<TIntegration, TTarget, TArg1, TArg2>(TTarget instance, TArg1 arg1, TArg2 arg2) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget, TArg1>(TTarget instance, TArg1 arg1) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance, object[] arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<TReturn>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget>(TTarget instance, System.Exception exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue<T>() -> T
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException<TIntegration, TTarget>(System.Exception exception) -> void
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.BeginMethod<TIntegration, TTarget>(TTarget instance, object![]! arguments) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<TReturn?>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.EndMethod<TIntegration, TTarget>(TTarget instance, System.Exception! exception, OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState state) -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.GetDefaultValue<T>() -> T?
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetInvoker.LogException<TIntegration, TTarget>(System.Exception! exception) -> void
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetReturn<T>
static OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState.GetDefault() -> OpenTelemetry.AutoInstrumentation.CallTarget.CallTargetState

View File

@ -313,14 +313,14 @@ public static class CallTargetInvoker
/// <param name="state">CallTarget state</param>
/// <returns>CallTarget return structure</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static CallTargetReturn<TReturn> EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
public static CallTargetReturn<TReturn?> EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
{
if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled)
{
return EndMethodHandler<TIntegration, TTarget, TReturn>.Invoke(instance, returnValue, exception, state);
}
return new CallTargetReturn<TReturn>(returnValue);
return new CallTargetReturn<TReturn?>(returnValue);
}
/// <summary>
@ -341,5 +341,5 @@ public static class CallTargetInvoker
/// <typeparam name="T">Type to get the default value</typeparam>
/// <returns>Default value of T</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T GetDefaultValue<T>() => default;
public static T? GetDefaultValue<T>() => default;
}

View File

@ -25,10 +25,9 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget;
/// </summary>
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;
/// <summary>
/// Initializes a new instance of the <see cref="CallTargetState"/> struct.
@ -39,7 +38,6 @@ public readonly struct CallTargetState
_previousActivity = null;
_activity = activity;
_state = null;
_startTime = null;
}
/// <summary>
@ -47,12 +45,11 @@ public readonly struct CallTargetState
/// </summary>
/// <param name="activity">Activity instance</param>
/// <param name="state">Object state instance</param>
public CallTargetState(Activity activity, object state)
public CallTargetState(Activity? activity, object state)
{
_previousActivity = null;
_activity = activity;
_state = state;
_startTime = null;
}
/// <summary>
@ -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;
}
/// <summary>
/// Gets the CallTarget BeginMethod activity
/// </summary>
public Activity Activity => _activity;
public Activity? Activity => _activity;
/// <summary>
/// Gets the CallTarget BeginMethod state
/// </summary>
public object State => _state;
public object? State => _state;
/// <summary>
/// Gets the CallTarget state StartTime
/// </summary>
public DateTimeOffset? StartTime => _startTime;
internal Activity PreviousActivity => _previousActivity;
internal Activity? PreviousActivity => _previousActivity;
/// <summary>
/// Gets the default call target state (used by the native side to initialize the locals)

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget>
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), Array.Empty<Type>());
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), Array.Empty<Type>());
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1>
{
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));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2>
{
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));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -31,7 +31,7 @@ internal static class BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TA
{
try
{
DynamicMethod dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7), typeof(TArg8) });
DynamicMethod? dynMethod = IntegrationMapper.CreateBeginMethodDelegate(typeof(TIntegration), typeof(TTarget), new[] { typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5), typeof(TArg6), typeof(TArg7), typeof(TArg8) });
if (dynMethod != null)
{
_invokeDelegate = (InvokeDelegate)dynMethod.CreateDelegate(typeof(InvokeDelegate));

View File

@ -21,7 +21,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations;
internal class ContinuationGenerator<TTarget, TReturn>
{
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<TTarget, TReturn>
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static TTo FromTReturn<TTo>(TReturn returnValue)
protected static TTo FromTReturn<TTo>(TReturn? returnValue)
{
#if NET6_0_OR_GREATER
return Unsafe.As<TReturn, TTo>(ref returnValue);
return Unsafe.As<TReturn?, TTo>(ref returnValue);
#else
return ContinuationsHelper.Convert<TReturn, TTo>(returnValue);
return ContinuationsHelper.Convert<TReturn?, TTo>(returnValue);
#endif
}
}

View File

@ -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;

View File

@ -22,7 +22,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations;
internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn> : ContinuationGenerator<TTarget, TReturn>
{
private static readonly Func<TTarget, object, Exception, CallTargetState, object> _continuation;
private static readonly Func<TTarget, object?, Exception?, CallTargetState, object>? _continuation;
private static readonly bool _preserveContext;
static TaskContinuationGenerator()
@ -30,12 +30,12 @@ internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn> : Conti
var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(object));
if (result.Method != null)
{
_continuation = (Func<TTarget, object, Exception, CallTargetState, object>)result.Method.CreateDelegate(typeof(Func<TTarget, object, Exception, CallTargetState, object>));
_continuation = (Func<TTarget, object?, Exception?, CallTargetState, object>)result.Method.CreateDelegate(typeof(Func<TTarget, object?, Exception?, CallTargetState, object>));
_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<TIntegration, TTarget, TReturn> : 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<TIntegration, TTarget, TReturn> : 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)
{

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations;
internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult> : ContinuationGenerator<TTarget, TReturn>
{
private static readonly Func<TTarget, TResult, Exception, CallTargetState, TResult> _continuation;
private static readonly Func<TTarget, TResult?, Exception?, CallTargetState, TResult>? _continuation;
private static readonly bool _preserveContext;
static TaskContinuationGenerator()
@ -32,12 +32,12 @@ internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult
var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(TResult));
if (result.Method != null)
{
_continuation = (Func<TTarget, TResult, Exception, CallTargetState, TResult>)result.Method.CreateDelegate(typeof(Func<TTarget, TResult, Exception, CallTargetState, TResult>));
_continuation = (Func<TTarget, TResult?, Exception?, CallTargetState, TResult>)result.Method.CreateDelegate(typeof(Func<TTarget, TResult?, Exception?, CallTargetState, TResult>));
_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<TIntegration, TTarget, TReturn, TResult
return ToTReturn(ContinuationAction(previousTask, instance, state));
}
private static async Task<TResult> ContinuationAction(Task<TResult> previousTask, TTarget target, CallTargetState state)
private static async Task<TResult?> ContinuationAction(Task<TResult> 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<TIntegration, TTarget, TReturn, TResult
}
else if (previousTask.Status == TaskStatus.Faulted)
{
exception = previousTask.Exception.GetBaseException();
exception = previousTask.Exception!.GetBaseException();
}
else if (previousTask.Status == TaskStatus.Canceled)
{
@ -97,7 +97,7 @@ internal class TaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult
// *
// Calls the CallTarget integration continuation, exceptions here should never bubble up to the application
// *
continuationResult = _continuation(target, taskResult, exception, state);
continuationResult = _continuation!(target, taskResult, exception, state);
}
catch (Exception ex)
{

View File

@ -21,7 +21,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations;
#if NET6_0_OR_GREATER
internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn> : ContinuationGenerator<TTarget, TReturn>
{
private static readonly Func<TTarget, object, Exception, CallTargetState, object> _continuation;
private static readonly Func<TTarget, object?, Exception?, CallTargetState, object>? _continuation;
private static readonly bool _preserveContext;
static ValueTaskContinuationGenerator()
@ -29,12 +29,12 @@ internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn> :
var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(object));
if (result.Method != null)
{
_continuation = (Func<TTarget, object, Exception, CallTargetState, object>)result.Method.CreateDelegate(typeof(Func<TTarget, object, Exception, CallTargetState, object>));
_continuation = (Func<TTarget, object?, Exception?, CallTargetState, object>)result.Method.CreateDelegate(typeof(Func<TTarget, object?, Exception?, CallTargetState, object>));
_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<TIntegration, TTarget, TReturn> :
// *
// 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<TIntegration, TTarget, TReturn> :
// *
// 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)
{

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers.Continuations;
#if NET6_0_OR_GREATER
internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn, TResult> : ContinuationGenerator<TTarget, TReturn>
{
private static readonly Func<TTarget, TResult, Exception, CallTargetState, TResult> _continuation;
private static readonly Func<TTarget, TResult?, Exception?, CallTargetState, TResult>? _continuation;
private static readonly bool _preserveContext;
static ValueTaskContinuationGenerator()
@ -31,12 +31,12 @@ internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn, TR
var result = IntegrationMapper.CreateAsyncEndMethodDelegate(typeof(TIntegration), typeof(TTarget), typeof(TResult));
if (result.Method != null)
{
_continuation = (Func<TTarget, TResult, Exception, CallTargetState, TResult>)result.Method.CreateDelegate(typeof(Func<TTarget, TResult, Exception, CallTargetState, TResult>));
_continuation = (Func<TTarget, TResult?, Exception?, CallTargetState, TResult>)result.Method.CreateDelegate(typeof(Func<TTarget, TResult?, Exception?, CallTargetState, TResult>));
_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<TIntegration, TTarget, TReturn, TR
ValueTask<TResult> previousValueTask = FromTReturn<ValueTask<TResult>>(returnValue);
return ToTReturn(InnerSetValueTaskContinuation(instance, previousValueTask, state));
static async ValueTask<TResult> InnerSetValueTaskContinuation(TTarget instance, ValueTask<TResult> previousValueTask, CallTargetState state)
static async ValueTask<TResult?> InnerSetValueTaskContinuation(TTarget instance, ValueTask<TResult> previousValueTask, CallTargetState state)
{
TResult result = default;
TResult? result = default;
try
{
result = await previousValueTask.ConfigureAwait(_preserveContext);
@ -66,7 +66,7 @@ internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn, TR
// *
// Calls the CallTarget integration continuation, exceptions here should never bubble up to the application
// *
_continuation(instance, result, ex, state);
_continuation!(instance, result, ex, state);
}
catch (Exception contEx)
{
@ -81,7 +81,7 @@ internal class ValueTaskContinuationGenerator<TIntegration, TTarget, TReturn, TR
// *
// Calls the CallTarget integration continuation, exceptions here should never bubble up to the application
// *
return _continuation(instance, result, null, state);
return _continuation!(instance, result, null, state);
}
catch (Exception contEx)
{

View File

@ -28,7 +28,7 @@ internal static class EndMethodHandler<TIntegration, TTarget>
{
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));

View File

@ -27,15 +27,15 @@ namespace OpenTelemetry.AutoInstrumentation.CallTarget.Handlers;
internal static class EndMethodHandler<TIntegration, TTarget, TReturn>
{
private static readonly InvokeDelegate _invokeDelegate = null;
private static readonly ContinuationGenerator<TTarget, TReturn> _continuationGenerator = null;
private static readonly InvokeDelegate? _invokeDelegate;
private static readonly ContinuationGenerator<TTarget, TReturn>? _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<TIntegration, TTarget, TReturn>
if (typeof(Task).IsAssignableFrom(returnType))
{
// The type is a Task<>
_continuationGenerator = (ContinuationGenerator<TTarget, TReturn>)Activator.CreateInstance(typeof(TaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType)));
_continuationGenerator = (ContinuationGenerator<TTarget, TReturn>?)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<TTarget, TReturn>)Activator.CreateInstance(typeof(ValueTaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType)));
_continuationGenerator = (ContinuationGenerator<TTarget, TReturn>?)Activator.CreateInstance(typeof(ValueTaskContinuationGenerator<,,,>).MakeGenericType(typeof(TIntegration), typeof(TTarget), returnType, ContinuationsHelper.GetResultType(returnType)));
}
#endif
}
@ -79,10 +79,10 @@ internal static class EndMethodHandler<TIntegration, TTarget, TReturn>
}
}
internal delegate CallTargetReturn<TReturn> InvokeDelegate(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state);
internal delegate CallTargetReturn<TReturn?> InvokeDelegate(TTarget instance, TReturn? returnValue, Exception exception, CallTargetState state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static CallTargetReturn<TReturn> Invoke(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
internal static CallTargetReturn<TReturn?> Invoke(TTarget instance, TReturn? returnValue, Exception exception, CallTargetState state)
{
if (_continuationGenerator != null)
{
@ -95,10 +95,10 @@ internal static class EndMethodHandler<TIntegration, TTarget, TReturn>
if (_invokeDelegate != null)
{
CallTargetReturn<TReturn> returnWrap = _invokeDelegate(instance, returnValue, exception, state);
CallTargetReturn<TReturn?> returnWrap = _invokeDelegate(instance, returnValue, exception, state);
returnValue = returnWrap.GetReturnValue();
}
return new CallTargetReturn<TReturn>(returnValue);
return new CallTargetReturn<TReturn?>(returnValue);
}
}

View File

@ -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<T>(object value)
private static T? ConvertType<T>(object value)
{
var conversionType = typeof(T);
if (value is null || conversionType == typeof(object))
{
return (T)value;
return (T?)value;
}
Type valueType = value.GetType();

View File

@ -34,10 +34,10 @@ internal static class IntegrationOptions<TIntegration, TTarget>
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<TIntegration, TTarget>
}
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;

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration;
/// </summary>
internal class CompositeConfigurationSource : IConfigurationSource, IEnumerable<IConfigurationSource>
{
private readonly List<IConfigurationSource> _sources = new List<IConfigurationSource>();
private readonly List<IConfigurationSource> _sources = new();
/// <summary>
/// Adds a new configuration source to this instance.
@ -58,7 +58,7 @@ internal class CompositeConfigurationSource : IConfigurationSource, IEnumerable<
/// </summary>
/// <param name="key">The key that identifies the setting.</param>
/// <returns>The value of the setting, or <c>null</c> if not found.</returns>
public string GetString(string key)
public string? GetString(string key)
{
return _sources.Select(source => source.GetString(key))
.FirstOrDefault(value => !string.IsNullOrEmpty(value));

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration;
/// </summary>
internal class EnvironmentConfigurationSource : StringConfigurationSource
{
protected override string GetStringInternal(string key)
protected override string? GetStringInternal(string key)
{
try
{

View File

@ -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)

View File

@ -27,7 +27,7 @@ internal interface IConfigurationSource
/// </summary>
/// <param name="key">The key that identifies the setting.</param>
/// <returns>The value of the setting, or <c>null</c> if not found.</returns>
string GetString(string key);
string? GetString(string key);
/// <summary>
/// Gets the <see cref="int"/> value of

View File

@ -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;
}

View File

@ -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];
}

View File

@ -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));
}

View File

@ -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;
}
}

View File

@ -25,7 +25,7 @@ namespace OpenTelemetry.AutoInstrumentation.Configuration;
internal abstract class StringConfigurationSource : IConfigurationSource
{
/// <inheritdoc />
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
/// <inheritdoc />
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
/// <inheritdoc />
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);
}

View File

@ -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;

View File

@ -111,12 +111,12 @@ internal class TracerSettings : Settings
/// <summary>
/// Gets sampler to be used for traces.
/// </summary>
public string TracesSampler { get; }
public string? TracesSampler { get; }
/// <summary>
/// Gets a value to be used as the sampler argument.
/// </summary>
public string TracesSamplerArguments { get; }
public string? TracesSamplerArguments { get; }
private static TracesExporter ParseTracesExporter(IConfigurationSource source)
{

View File

@ -34,25 +34,28 @@ internal class SdkSelfDiagnosticsEventListener : EventListener
private readonly object lockObj = new();
private readonly EventLevel logLevel;
private readonly ILogger log;
private readonly List<EventSource> eventSourcesBeforeConstructor = new();
private readonly List<EventSource>? eventSourcesBeforeConstructor = new();
public SdkSelfDiagnosticsEventListener(EventLevel eventLevel, ILogger logger)
{
log = logger;
logLevel = eventLevel;
List<EventSource> eventSources;
List<EventSource>? eventSources;
lock (lockObj)
{
eventSources = this.eventSourcesBeforeConstructor;
eventSourcesBeforeConstructor = null;
}
if (eventSources != null)
{
foreach (var eventSource in eventSources)
{
EnableEvents(eventSource, logLevel, EventKeywords.All);
}
}
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
@ -88,24 +91,34 @@ internal class SdkSelfDiagnosticsEventListener : EventListener
/// <param name="eventData">Data of the EventSource event.</param>
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
var payloadArray = new object[eventData.Payload.Count];
object[] payloadArray;
if (eventData.Payload != null)
{
payloadArray = new object[eventData.Payload.Count];
eventData.Payload.CopyTo(payloadArray, 0);
}
else
{
payloadArray = Array.Empty<object>();
}
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;
}
}

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System.Reflection;
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Reflection;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;
/// <summary>

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;
/// <summary>

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Reflection;
using System.Reflection.Emit;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

View File

@ -14,7 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Reflection;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.ComponentModel;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;
internal static class DuckTypeConstants

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.ComponentModel;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
// ReSharper disable once CheckNamespace
namespace System.Runtime.CompilerServices;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Reflection;

View File

@ -14,8 +14,6 @@
// limitations under the License.
// </copyright>
#nullable enable
using System;
namespace OpenTelemetry.AutoInstrumentation.DuckTyping;

View File

@ -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)
{

View File

@ -23,11 +23,26 @@ namespace OpenTelemetry.AutoInstrumentation;
internal partial class FrameworkDescription
{
private static FrameworkDescription _instance = null;
private static readonly Tuple<int, string>[] 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\"))

View File

@ -26,21 +26,6 @@ internal partial class FrameworkDescription
private static readonly Assembly RootAssembly = typeof(object).Assembly;
private static readonly Tuple<int, string>[] 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<AssemblyInformationalVersionAttribute>();
// 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<AssemblyFileVersionAttribute>();
productVersion = fileVersionAttribute?.Version;
}
catch (Exception e)

View File

@ -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;
/// <summary>
/// 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.");
}

View File

@ -15,7 +15,6 @@
// </copyright>
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
/// </summary>
[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
{
/// <summary>
@ -60,9 +59,9 @@ public static class ExecuteAsyncIntegration
/// <param name="exception">Exception instance in case the original code threw an exception.</param>
/// <param name="state">Calltarget state value</param>
/// <returns>A response value, in an async scenario will be T of Task of T</returns>
internal static TExecutionResult OnAsyncMethodEnd<TTarget, TExecutionResult>(TTarget instance, TExecutionResult executionResult, Exception exception, CallTargetState state)
internal static TExecutionResult OnAsyncMethodEnd<TTarget, TExecutionResult>(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)
{

View File

@ -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,21 +73,18 @@ 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);
}
}
}
}
private static string GetOperation(string operationName, string operationType)
{

View File

@ -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;
}
}

View File

@ -21,17 +21,17 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.GraphQL;
internal class GraphQLTags : InstrumentationTags
{
protected static readonly IProperty<string>[] GraphQLTagsProperties =
protected static readonly IProperty<string?>[] GraphQLTagsProperties =
InstrumentationTagsProperties.Concat(
new Property<GraphQLTags, string>(Tags.GraphQL.Document, t => t.Document, (t, v) => t.Document = v),
new Property<GraphQLTags, string>(Tags.GraphQL.OperationName, t => t.OperationName, (t, v) => t.OperationName = v),
new Property<GraphQLTags, string>(Tags.GraphQL.OperationType, t => t.OperationType, (t, v) => t.OperationType = v));
new Property<GraphQLTags, string?>(Tags.GraphQL.Document, t => t.Document),
new Property<GraphQLTags, string?>(Tags.GraphQL.OperationName, t => t.OperationName),
new Property<GraphQLTags, string?>(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<string>[] GetAdditionalTags() => GraphQLTagsProperties;
protected override IProperty<string?>[] GetAdditionalTags() => GraphQLTagsProperties;
}

View File

@ -25,76 +25,68 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
internal class InstrumentMethodAttribute : Attribute
{
/// <summary>
/// Gets or sets the name of the assembly that contains the target method to be intercepted.
/// Required if <see cref="AssemblyNames"/> is not set.
/// </summary>
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;
}
/// <summary>
/// Gets or sets the name of the assemblies that contain the target method to be intercepted.
/// Required if <see cref="AssemblyName"/> is not set.
/// Gets the name of the assembly that contains the target method to be intercepted.
/// </summary>
public string[] AssemblyNames { get; set; }
public string AssemblyName { get; }
/// <summary>
/// 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.
/// </summary>
public string TypeName { get; set; }
public string TypeName { get; }
/// <summary>
/// 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.
/// </summary>
public string MethodName { get; set; }
public string MethodName { get; }
/// <summary>
/// Gets or sets the return type name
/// Gets the return type name
/// </summary>
public string ReturnTypeName { get; set; }
public string ReturnTypeName { get; }
/// <summary>
/// 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.
/// </summary>
public string[] ParameterTypeNames { get; set; }
public string[] ParameterTypeNames { get; }
/// <summary>
/// Gets the target version range for <see cref="AssemblyName"/>.
/// </summary>
public IntegrationVersionRange VersionRange { get; } = new();
public IntegrationVersionRange VersionRange { get; }
/// <summary>
/// Gets or sets the target minimum version.
/// Gets the target minimum version.
/// </summary>
public string MinimumVersion
{
get => VersionRange.MinimumVersion;
set => VersionRange.MinimumVersion = value;
}
/// <summary>
/// Gets or sets the target maximum version.
/// Gets the target maximum version.
/// </summary>
public string MaximumVersion
{
get => VersionRange.MaximumVersion;
set => VersionRange.MaximumVersion = value;
}
/// <summary>

View File

@ -23,15 +23,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.Logger;
/// Microsoft.Extensions.Logging.LoggingBuilder calltarget instrumentation
/// </summary>
[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
{
/// <summary>

View File

@ -29,19 +29,19 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.MongoDB;
/// MongoDB.Driver.MongoClient calltarget instrumentation
/// </summary>
[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
/// <summary>
@ -53,6 +53,7 @@ public static class MongoClientIntegration
/// <param name="settings">The source of the original GraphQL query</param>
/// <returns>Calltarget state value</returns>
internal static CallTargetState OnMethodBegin<TTarget, TMongoClientSettings>(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<Func<string, bool>> 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));

View File

@ -23,14 +23,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.MySqlData;
/// MySql.Data.MySqlClient.MySqlConnectionStringBuilder calltarget instrumentation
/// </summary>
[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

View File

@ -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);
}
}
}
#endif

View File

@ -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
/// </summary>
[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
{
/// <summary>
@ -76,7 +77,10 @@ public static class StackExchangeRedisIntegration
internal static CallTargetReturn<TReturn> OnMethodEnd<TTarget, TReturn>(TReturn returnValue, Exception exception, CallTargetState state)
{
#if NET6_0_OR_GREATER
if (returnValue != null && Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.StackExchangeRedis))
{
StackExchangeRedisInitializer.Initialize(returnValue);
}
#endif
return new CallTargetReturn<TReturn>(returnValue);

View File

@ -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
/// </summary>
[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
{
/// <summary>
@ -67,7 +68,10 @@ public static class StackExchangeRedisIntegrationAsync
internal static TReturn OnAsyncMethodEnd<TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
{
#if NET6_0_OR_GREATER
if (returnValue != null && Instrumentation.TracerSettings.Value.EnabledInstrumentations.Contains(TracerInstrumentation.StackExchangeRedis))
{
StackExchangeRedisInitializer.Initialize(returnValue);
}
#endif
return returnValue;

View File

@ -26,15 +26,15 @@ namespace OpenTelemetry.AutoInstrumentation.Instrumentations.Validations;
/// is added we can remove this instrumentation.
/// </summary>
[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");

View File

@ -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);
}

View File

@ -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);

View File

@ -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);
}

View File

@ -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

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -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];
}
}
}

View File

@ -31,7 +31,7 @@ internal static class LogBuilderExtensions
{
try
{
if (!(builder?.Services is ServiceCollection services))
if (!(builder.Services is ServiceCollection services))
{
return builder;
}
@ -52,12 +52,15 @@ internal static class LogBuilderExtensions
options.IncludeFormattedMessage = settings.IncludeFormattedMessage;
pluginManager.ConfigureLogsOptions(options);
pluginManager?.ConfigureLogsOptions(options);
if (settings.ConsoleExporterEnabled)
{
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:

View File

@ -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<T>(LogLevel level, Exception exception, string messageTemplate, T property, int sourceLine, string sourceFile)
private void Write<T>(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<T0, T1>(LogLevel level, Exception exception, string messageTemplate, T0 property0, T1 property1, int sourceLine, string sourceFile)
private void Write<T0, T1>(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<T0, T1, T2>(LogLevel level, Exception exception, string messageTemplate, T0 property0, T1 property1, T2 property2, int sourceLine, string sourceFile)
private void Write<T0, T1, T2>(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
{

View File

@ -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
{

View File

@ -4,7 +4,6 @@
<PropertyGroup>
<Version>0.5.1</Version>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>

View File

@ -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>(T options)
where T : notnull
{
ConfigureOptions(options, "ConfigureMetricsOptions");
}
public void ConfigureTracesOptions<T>(T options)
where T : notnull
{
ConfigureOptions(options, "ConfigureTracesOptions");
}
@ -79,11 +81,13 @@ internal class PluginManager
}
public void ConfigureLogsOptions<T>(T options)
where T : notnull
{
ConfigureOptions(options, "ConfigureLogsOptions");
}
private void ConfigureOptions<T>(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>(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 });
}
}

View File

@ -18,13 +18,11 @@ using System;
namespace OpenTelemetry.AutoInstrumentation.Tagging;
internal interface IProperty<TResult>
internal interface IProperty<out TResult>
{
bool IsReadOnly { get; }
string Key { get; }
Func<ITags, TResult> Getter { get; }
Action<ITags, TResult> Setter { get; }
}

View File

@ -21,8 +21,4 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging;
internal interface ITags
{
List<KeyValuePair<string, string>> GetAllTags();
string GetTag(string key);
void SetTag(string key, string value);
}

View File

@ -18,9 +18,9 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging;
internal abstract class InstrumentationTags : TagsList
{
protected static readonly IProperty<string>[] InstrumentationTagsProperties =
protected static readonly IProperty<string?>[] InstrumentationTagsProperties =
{
};
protected override IProperty<string>[] GetAdditionalTags() => InstrumentationTagsProperties;
protected override IProperty<string?>[] GetAdditionalTags() => InstrumentationTagsProperties;
}

View File

@ -20,11 +20,10 @@ namespace OpenTelemetry.AutoInstrumentation.Tagging;
internal class Property<TTags, TResult> : IProperty<TResult>
{
public Property(string key, Func<TTags, TResult> getter, Action<TTags, TResult> setter)
public Property(string key, Func<TTags, TResult> 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<TTags, TResult> : IProperty<TResult>
public string Key { get; }
public Func<ITags, TResult> Getter { get; }
public Action<ITags, TResult> Setter { get; }
}

View File

@ -1,29 +0,0 @@
// <copyright file="ReadOnlyProperty.cs" company="OpenTelemetry Authors">
// 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.
// </copyright>
using System;
namespace OpenTelemetry.AutoInstrumentation.Tagging;
internal class ReadOnlyProperty<TTags, TResult> : Property<TTags, TResult>
{
public ReadOnlyProperty(string key, Func<TTags, TResult> getter)
: base(key, getter, (_, _) => { })
{
}
public override bool IsReadOnly => true;
}

View File

@ -26,11 +26,6 @@ internal static class Tags
/// </summary>
public const string OutHost = "out.host";
/// <summary>
/// The port of a outgoing server connection.
/// </summary>
public const string OutPort = "out.port";
/// <summary>
/// GraphQL specific tags
/// </summary>

View File

@ -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<KeyValuePair<string, string>> _tags;
public List<KeyValuePair<string, string>> GetAllTags()
{
var customTags = GetCustomTags();
var additionalTags = GetAdditionalTags();
var allTags = new List<KeyValuePair<string, string>>(
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<KeyValuePair<string, string>>();
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<string, string>(key, value);
}
return;
}
}
// If we get there, the tag wasn't in the collection
if (value != null)
{
tags.Add(new KeyValuePair<string, string>(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<string>[] GetAdditionalTags() => Array.Empty<IProperty<string>>();
protected virtual IList<KeyValuePair<string, string>> GetCustomTags() => Volatile.Read(ref _tags);
protected virtual IProperty<string?>[] GetAdditionalTags() => Array.Empty<IProperty<string?>>();
}

View File

@ -31,7 +31,7 @@ internal static class ActivityHelper
/// </summary>
/// <param name="activity">The activity to include exception info.</param>
/// <param name="exception">The exception.</param>
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;
}

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.AutoInstrumentation.Util;
internal static class ConfigurationSourceExtensions
{
public static IList<TEnum> ParseEnabledEnumList<TEnum>(this IConfigurationSource source, string enabledConfiguration, string disabledConfiguration, string error)
where TEnum : struct, IConvertible
where TEnum : struct, Enum, IConvertible
{
var instrumentations = new Dictionary<string, TEnum>();
var enabledInstrumentations = source.GetString(enabledConfiguration);
@ -52,7 +52,7 @@ internal static class ConfigurationSourceExtensions
instrumentations = Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.ToDictionary(
key => Enum.GetName(typeof(TEnum), key),
key => Enum.GetName(typeof(TEnum), key)!,
val => val);
}

View File

@ -1,121 +0,0 @@
// <copyright file="DomainMetadata.cs" company="OpenTelemetry Authors">
// 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.
// </copyright>
using System;
namespace OpenTelemetry.AutoInstrumentation.Util;
/// <summary>
/// Dedicated helper class for consistently referencing Process and AppDomain information.
/// </summary>
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;
}
}
}

View File

@ -1,66 +0,0 @@
// <copyright file="Interception.cs" company="OpenTelemetry Authors">
// 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.
// </copyright>
using System;
using System.Diagnostics;
namespace OpenTelemetry.AutoInstrumentation.Util;
/// <summary>
/// Convenience properties and methods for integration definitions.
/// </summary>
internal static class Interception
{
internal const Type[] NullTypeArray = null;
internal static readonly object[] NoArgObjects = Array.Empty<object>();
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;
}
}

Some files were not shown because too many files have changed in this diff Show More