Skip to content

Commit 90db90c

Browse files
committed
chore: Use logging source generators
Signed-off-by: Austin Drenski <[email protected]>
1 parent a6062fe commit 90db90c

File tree

5 files changed

+38
-20
lines changed

5 files changed

+38
-20
lines changed

build/Common.props

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project>
22
<PropertyGroup>
3-
<LangVersion>7.3</LangVersion>
3+
<LangVersion>latest</LangVersion>
44
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
55
<EnableNETAnalyzers>true</EnableNETAnalyzers>
66
</PropertyGroup>
@@ -19,12 +19,13 @@
1919
Please sort alphabetically.
2020
Refer to https://docs.microsoft.com/nuget/concepts/package-versioning for semver syntax.
2121
-->
22-
<MicrosoftExtensionsLoggerVer>[2.0,)</MicrosoftExtensionsLoggerVer>
22+
<MicrosoftExtensionsLoggerVer>[8.0.0,)</MicrosoftExtensionsLoggerVer>
2323
<MicrosoftSourceLinkGitHubPkgVer>[1.0.0,2.0)</MicrosoftSourceLinkGitHubPkgVer>
2424
</PropertyGroup>
2525

2626
<ItemGroup>
2727
<PackageReference Include="System.Collections.Immutable" Version="[1.7.1,)" />
2828
<PackageReference Include="System.Threading.Channels" Version="[6.0.0,)" />
29+
<PackageReference Include="System.ValueTuple" Version="[4.5.0,)" Condition="'$(TargetFramework)' == 'net462'" />
2930
</ItemGroup>
3031
</Project>

src/OpenFeature/Api.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ public void RemoveHandler(ProviderEventTypes type, EventHandlerDelegate handler)
227227
/// <param name="logger">The logger to be used</param>
228228
public void SetLogger(ILogger logger)
229229
{
230-
this.EventExecutor.Logger = logger;
230+
this.EventExecutor.SetLogger(logger);
231231
}
232232
}
233233
}

src/OpenFeature/EventExecutor.cs

+10-5
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace OpenFeature
1313

1414
internal delegate Task ShutdownDelegate();
1515

16-
internal class EventExecutor
16+
internal sealed partial class EventExecutor
1717
{
1818
private readonly object _lockObj = new object();
1919
public readonly Channel<object> EventChannel = Channel.CreateBounded<object>(1);
@@ -27,16 +27,18 @@ internal class EventExecutor
2727
private readonly Dictionary<ProviderEventTypes, List<EventHandlerDelegate>> _apiHandlers = new Dictionary<ProviderEventTypes, List<EventHandlerDelegate>>();
2828
private readonly Dictionary<string, Dictionary<ProviderEventTypes, List<EventHandlerDelegate>>> _clientHandlers = new Dictionary<string, Dictionary<ProviderEventTypes, List<EventHandlerDelegate>>>();
2929

30-
internal ILogger Logger { get; set; }
30+
private ILogger _logger;
3131

3232
public EventExecutor()
3333
{
34-
this.Logger = new Logger<EventExecutor>(new NullLoggerFactory());
34+
this._logger = NullLogger<EventExecutor>.Instance;
3535
this._shutdownDelegate = this.SignalShutdownAsync;
3636
var eventProcessing = new Thread(this.ProcessEventAsync);
3737
eventProcessing.Start();
3838
}
3939

40+
internal void SetLogger(ILogger logger) => this._logger = logger;
41+
4042
internal void AddApiLevelHandler(ProviderEventTypes eventType, EventHandlerDelegate handler)
4143
{
4244
lock (this._lockObj)
@@ -218,7 +220,7 @@ private void EmitOnRegistration(FeatureProviderReference provider, ProviderEvent
218220
}
219221
catch (Exception exc)
220222
{
221-
this.Logger?.LogError("Error running handler: " + exc);
223+
this.ErrorRunningHandler(exc);
222224
}
223225
}
224226
}
@@ -323,7 +325,7 @@ private void InvokeEventHandler(EventHandlerDelegate eventHandler, Event e)
323325
}
324326
catch (Exception exc)
325327
{
326-
this.Logger?.LogError("Error running handler: " + exc);
328+
this.ErrorRunningHandler(exc);
327329
}
328330
}
329331

@@ -346,6 +348,9 @@ private async Task SignalShutdownAsync()
346348
// Wait for the processing loop to acknowledge the shutdown
347349
await this._shutdownSemaphore.WaitAsync().ConfigureAwait(false);
348350
}
351+
352+
[LoggerMessage(100, LogLevel.Error, "Error running handler")]
353+
partial void ErrorRunningHandler(Exception exception);
349354
}
350355

351356
internal class ShutdownSignal

src/OpenFeature/OpenFeatureClient.cs

+22-9
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ namespace OpenFeature
1515
/// <summary>
1616
///
1717
/// </summary>
18-
public sealed class FeatureClient : IFeatureClient
18+
public sealed partial class FeatureClient : IFeatureClient
1919
{
2020
private readonly ClientMetadata _metadata;
2121
private readonly ConcurrentStack<Hook> _hooks = new ConcurrentStack<Hook>();
@@ -76,7 +76,7 @@ public void SetContext(EvaluationContext context)
7676
public FeatureClient(string name, string version, ILogger logger = null, EvaluationContext context = null)
7777
{
7878
this._metadata = new ClientMetadata(name, version);
79-
this._logger = logger ?? new Logger<Api>(new NullLoggerFactory());
79+
this._logger = logger ?? NullLogger<Api>.Instance;
8080
this._evaluationContext = context ?? EvaluationContext.Empty;
8181
}
8282

@@ -233,15 +233,14 @@ private async Task<FlagEvaluationDetails<T>> EvaluateFlag<T>(
233233
}
234234
catch (FeatureProviderException ex)
235235
{
236-
this._logger.LogError(ex, "Error while evaluating flag {FlagKey}. Error {ErrorType}", flagKey,
237-
ex.ErrorType.GetDescription());
236+
this.FlagEvaluationErrorWithDescription(flagKey, ex.ErrorType.GetDescription(), ex);
238237
evaluation = new FlagEvaluationDetails<T>(flagKey, defaultValue, ex.ErrorType, Reason.Error,
239238
string.Empty, ex.Message);
240239
await this.TriggerErrorHooks(allHooksReversed, hookContext, ex, options).ConfigureAwait(false);
241240
}
242241
catch (Exception ex)
243242
{
244-
this._logger.LogError(ex, "Error while evaluating flag {FlagKey}", flagKey);
243+
this.FlagEvaluationError(flagKey, ex);
245244
var errorCode = ex is InvalidCastException ? ErrorType.TypeMismatch : ErrorType.General;
246245
evaluation = new FlagEvaluationDetails<T>(flagKey, defaultValue, errorCode, Reason.Error, string.Empty);
247246
await this.TriggerErrorHooks(allHooksReversed, hookContext, ex, options).ConfigureAwait(false);
@@ -270,8 +269,7 @@ private async Task<HookContext<T>> TriggerBeforeHooks<T>(IReadOnlyList<Hook> hoo
270269
}
271270
else
272271
{
273-
this._logger.LogDebug("Hook {HookName} returned null, nothing to merge back into context",
274-
hook.GetType().Name);
272+
this.HookReturnedNull(hook.GetType().Name);
275273
}
276274
}
277275

@@ -298,7 +296,7 @@ private async Task TriggerErrorHooks<T>(IReadOnlyList<Hook> hooks, HookContext<T
298296
}
299297
catch (Exception e)
300298
{
301-
this._logger.LogError(e, "Error while executing Error hook {0}", hook.GetType().Name);
299+
this.ErrorHookError(hook.GetType().Name, e);
302300
}
303301
}
304302
}
@@ -314,9 +312,24 @@ private async Task TriggerFinallyHooks<T>(IReadOnlyList<Hook> hooks, HookContext
314312
}
315313
catch (Exception e)
316314
{
317-
this._logger.LogError(e, "Error while executing Finally hook {0}", hook.GetType().Name);
315+
this.FinallyHookError(hook.GetType().Name, e);
318316
}
319317
}
320318
}
319+
320+
[LoggerMessage(100, LogLevel.Debug, "Hook {HookName} returned null, nothing to merge back into context")]
321+
partial void HookReturnedNull(string hookName);
322+
323+
[LoggerMessage(101, LogLevel.Error, "Error while evaluating flag {FlagKey}")]
324+
partial void FlagEvaluationError(string flagKey, Exception exception);
325+
326+
[LoggerMessage(102, LogLevel.Error, "Error while evaluating flag {FlagKey}: {ErrorType}")]
327+
partial void FlagEvaluationErrorWithDescription(string flagKey, string errorType, Exception exception);
328+
329+
[LoggerMessage(103, LogLevel.Error, "Error while executing Error hook {HookName}")]
330+
partial void ErrorHookError(string hookName, Exception exception);
331+
332+
[LoggerMessage(104, LogLevel.Error, "Error while executing Finally hook {HookName}")]
333+
partial void FinallyHookError(string hookName, Exception exception);
321334
}
322335
}

test/OpenFeature.Tests/OpenFeatureClientTests.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using AutoFixture;
77
using FluentAssertions;
88
using Microsoft.Extensions.Logging;
9-
using Microsoft.Extensions.Logging.Internal;
109
using NSubstitute;
1110
using NSubstitute.ExceptionExtensions;
1211
using OpenFeature.Constant;
@@ -183,9 +182,9 @@ public async Task OpenFeatureClient_Should_Return_DefaultValue_When_Type_Mismatc
183182
mockedLogger.Received(1).Log(
184183
LogLevel.Error,
185184
Arg.Any<EventId>(),
186-
Arg.Is<FormattedLogValues>(t => string.Equals($"Error while evaluating flag {flagName}", t.ToString(), StringComparison.InvariantCultureIgnoreCase)),
185+
Arg.Is<string>(t => string.Equals($"Error while evaluating flag {flagName}", t.ToString(), StringComparison.InvariantCultureIgnoreCase)),
187186
Arg.Any<Exception>(),
188-
Arg.Any<Func<object, Exception, string>>());
187+
Arg.Any<Func<string, Exception, string>>());
189188
}
190189

191190
[Fact]

0 commit comments

Comments
 (0)