Skip to content

Commit 6b17f7b

Browse files
authored
Use [LoggerMessage] in Orleans.Core (#9352)
1 parent 2f24683 commit 6b17f7b

File tree

11 files changed

+484
-224
lines changed

11 files changed

+484
-224
lines changed

src/Orleans.Core/Configuration/OptionLogger/IOptionsLogger.cs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
using Microsoft.Extensions.Logging;
99

1010
namespace Orleans
11-
{
11+
{
1212
/// <summary>
1313
/// Logger for options on the client.
1414
/// </summary>
@@ -50,7 +50,7 @@ public Task OnStart(CancellationToken token)
5050
/// <summary>
5151
/// Base class for client and silo default options loggers.
5252
/// </summary>
53-
public abstract class OptionsLogger
53+
public abstract partial class OptionsLogger
5454
{
5555
private readonly ILogger logger;
5656
private readonly IServiceProvider services;
@@ -98,18 +98,30 @@ public void LogOption(IOptionFormatter formatter)
9898
{
9999
try
100100
{
101-
var stringBuiler = new StringBuilder();
102-
stringBuiler.AppendLine($"Configuration {formatter.Name}: ");
101+
var stringBuilder = new StringBuilder();
103102
foreach (var setting in formatter.Format())
104103
{
105-
stringBuiler.AppendLine($"{setting}");
104+
stringBuilder.AppendLine($"{setting}");
106105
}
107-
this.logger.LogInformation(stringBuiler.ToString());
108-
} catch(Exception ex)
106+
LogInformationOptions(logger, formatter.Name, stringBuilder.ToString());
107+
}
108+
catch(Exception ex)
109109
{
110-
this.logger.LogError(ex, $"An error occurred while logging options {formatter.Name}", formatter.Name);
110+
LogErrorOptions(logger, ex, formatter.Name);
111111
throw;
112112
}
113113
}
114+
115+
[LoggerMessage(
116+
Level = LogLevel.Information,
117+
Message = "Configuration {Name}:\n{Options}"
118+
)]
119+
private static partial void LogInformationOptions(ILogger logger, string name, string options);
120+
121+
[LoggerMessage(
122+
Level = LogLevel.Error,
123+
Message = "An error occurred while logging '{Name}' options."
124+
)]
125+
private static partial void LogErrorOptions(ILogger logger, Exception exception, string name);
114126
}
115127
}

src/Orleans.Core/Core/ClusterClient.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ namespace Orleans
1515
/// <summary>
1616
/// Client for communicating with clusters of Orleans silos.
1717
/// </summary>
18-
internal class ClusterClient : IInternalClusterClient, IHostedService
18+
internal partial class ClusterClient : IInternalClusterClient, IHostedService
1919
{
2020
private readonly OutsideRuntimeClient _runtimeClient;
2121
private readonly ILogger<ClusterClient> _logger;
@@ -69,14 +69,14 @@ public async Task StopAsync(CancellationToken cancellationToken)
6969
{
7070
try
7171
{
72-
_logger.LogInformation("Client shutting down");
72+
LogClientShuttingDown(_logger);
7373

7474
await _clusterClientLifecycle.OnStop(cancellationToken).ConfigureAwait(false);
7575
await _runtimeClient.StopAsync(cancellationToken).WaitAsync(cancellationToken);
7676
}
7777
finally
7878
{
79-
_logger.LogInformation("Client shutdown completed");
79+
LogClientShutdownCompleted(_logger);
8080
}
8181
}
8282

@@ -152,5 +152,17 @@ public object Cast(IAddressable grain, Type outputGrainInterfaceType)
152152
/// <inheritdoc />
153153
public IAddressable GetGrain(GrainId grainId, GrainInterfaceType interfaceType)
154154
=> _runtimeClient.InternalGrainFactory.GetGrain(grainId, interfaceType);
155+
156+
[LoggerMessage(
157+
Level = LogLevel.Information,
158+
Message = "Client shutting down."
159+
)]
160+
private static partial void LogClientShuttingDown(ILogger logger);
161+
162+
[LoggerMessage(
163+
Level = LogLevel.Information,
164+
Message = "Client shutdown completed."
165+
)]
166+
private static partial void LogClientShutdownCompleted(ILogger logger);
155167
}
156168
}

src/Orleans.Core/Lifecycle/LifecycleSubject.cs

Lines changed: 40 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ namespace Orleans
2121
/// <item><description>OnStop stops all stages regardless of errors even if canceled.</description></item>
2222
/// </list>
2323
/// </remarks>
24-
public abstract class LifecycleSubject : ILifecycleSubject
24+
public abstract partial class LifecycleSubject : ILifecycleSubject
2525
{
2626
private readonly List<OrderedObserver> subscribers = [];
2727
protected readonly ILogger Logger;
@@ -86,14 +86,7 @@ protected static ImmutableDictionary<int, string> GetStageNames(Type type)
8686
/// <param name="elapsed">The period of time which elapsed before <see cref="OnStart"/> completed once it was initiated.</param>
8787
protected virtual void PerfMeasureOnStart(int stage, TimeSpan elapsed)
8888
{
89-
if (this.Logger.IsEnabled(LogLevel.Trace))
90-
{
91-
this.Logger.LogTrace(
92-
(int)ErrorCode.SiloStartPerfMeasure,
93-
"Starting lifecycle stage '{Stage}' took '{Elapsed}'.",
94-
GetStageName(stage),
95-
elapsed);
96-
}
89+
LogLifecycleStageStarted(Logger, GetStageName(stage), elapsed);
9790
}
9891

9992
/// <inheritdoc />
@@ -123,11 +116,7 @@ public virtual async Task OnStart(CancellationToken cancellationToken = default)
123116
}
124117
catch (Exception ex) when (ex is not OrleansLifecycleCanceledException)
125118
{
126-
this.Logger.LogError(
127-
(int)ErrorCode.LifecycleStartFailure,
128-
ex,
129-
"Lifecycle start canceled due to errors at stage '{Stage}'.",
130-
_highStage is { } highStage ? GetStageName(highStage) : "Unknown");
119+
LogErrorLifecycleStartFailure(Logger, ex, _highStage is { } highStage ? GetStageName(highStage) : "Unknown");
131120
throw;
132121
}
133122

@@ -157,14 +146,7 @@ protected virtual void OnStartStageCompleted(int stage) { }
157146
/// <param name="elapsed">The period of time which elapsed before <see cref="OnStop"/> completed once it was initiated.</param>
158147
protected virtual void PerfMeasureOnStop(int stage, TimeSpan elapsed)
159148
{
160-
if (this.Logger.IsEnabled(LogLevel.Trace))
161-
{
162-
this.Logger.LogTrace(
163-
(int)ErrorCode.SiloStartPerfMeasure,
164-
"Stopping lifecycle stage '{Stage}' took '{Elapsed}'.",
165-
GetStageName(stage),
166-
elapsed);
167-
}
149+
LogLifecycleStageStopped(Logger, GetStageName(stage), elapsed);
168150
}
169151

170152
/// <inheritdoc />
@@ -181,7 +163,7 @@ public virtual async Task OnStop(CancellationToken cancellationToken = default)
181163
{
182164
if (cancellationToken.IsCancellationRequested && !loggedCancellation)
183165
{
184-
this.Logger.LogWarning("Lifecycle stop operations canceled at stage '{Stage}' by request.", GetStageName(observerGroup.Key));
166+
LogWarningLifecycleStopCanceled(Logger, GetStageName(observerGroup.Key));
185167
loggedCancellation = true;
186168
}
187169

@@ -196,11 +178,7 @@ public virtual async Task OnStop(CancellationToken cancellationToken = default)
196178
}
197179
catch (Exception ex)
198180
{
199-
this.Logger.LogWarning(
200-
(int)ErrorCode.LifecycleStopFailure,
201-
ex,
202-
"Stopping lifecycle encountered an error at stage '{Stage}'. Continuing to stop.",
203-
_highStage is { } highStage ? GetStageName(highStage) : "Unknown");
181+
LogWarningLifecycleStopFailure(Logger, ex, _highStage is { } highStage ? GetStageName(highStage) : "Unknown");
204182
}
205183

206184
this.OnStopStageCompleted(stage);
@@ -264,5 +242,39 @@ public OrderedObserver(int stage, ILifecycleObserver observer)
264242
/// <inheritdoc />
265243
public void Dispose() => Observer = null;
266244
}
245+
246+
[LoggerMessage(
247+
EventId = (int)ErrorCode.LifecycleStartFailure,
248+
Level = LogLevel.Error,
249+
Message = "Lifecycle start canceled due to errors at stage '{Stage}'."
250+
)]
251+
private static partial void LogErrorLifecycleStartFailure(ILogger logger, Exception ex, string stage);
252+
253+
[LoggerMessage(
254+
EventId = (int)ErrorCode.LifecycleStopFailure,
255+
Level = LogLevel.Warning,
256+
Message = "Stopping lifecycle encountered an error at stage '{Stage}'. Continuing to stop."
257+
)]
258+
private static partial void LogWarningLifecycleStopFailure(ILogger logger, Exception ex, string stage);
259+
260+
[LoggerMessage(
261+
Level = LogLevel.Warning,
262+
Message = "Lifecycle stop operations canceled at stage '{Stage}' by request."
263+
)]
264+
private static partial void LogWarningLifecycleStopCanceled(ILogger logger, string stage);
265+
266+
[LoggerMessage(
267+
EventId = (int)ErrorCode.SiloStartPerfMeasure,
268+
Level = LogLevel.Trace,
269+
Message = "Starting lifecycle stage '{Stage}' took '{Elapsed}'."
270+
)]
271+
private static partial void LogLifecycleStageStarted(ILogger logger, string stage, TimeSpan elapsed);
272+
273+
[LoggerMessage(
274+
EventId = (int)ErrorCode.SiloStartPerfMeasure,
275+
Level = LogLevel.Trace,
276+
Message = "Stopping lifecycle stage '{Stage}' took '{Elapsed}'."
277+
)]
278+
private static partial void LogLifecycleStageStopped(ILogger logger, string stage, TimeSpan elapsed);
267279
}
268280
}

src/Orleans.Core/Manifest/ClientClusterManifestProvider.cs

Lines changed: 43 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace Orleans.Runtime
1919
/// <summary>
2020
/// <see cref="IClusterManifestProvider"/> implementation for external clients.
2121
/// </summary>
22-
internal class ClientClusterManifestProvider : IClusterManifestProvider, IAsyncDisposable, IDisposable
22+
internal partial class ClientClusterManifestProvider : IClusterManifestProvider, IAsyncDisposable, IDisposable
2323
{
2424
private readonly TaskCompletionSource<bool> _initialized = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
2525
private readonly ILogger<ClientClusterManifestProvider> _logger;
@@ -90,11 +90,11 @@ public async Task StopAsync(CancellationToken cancellationToken)
9090
}
9191
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
9292
{
93-
_logger.LogInformation("Graceful shutdown of cluster manifest provider was canceled.");
93+
LogGracefulShutdownCanceled(_logger);
9494
}
9595
catch (Exception exception)
9696
{
97-
_logger.LogError(exception, "Error stopping cluster manifest provider.");
97+
LogStoppingClusterManifestProvider(_logger, exception);
9898
}
9999
}
100100

@@ -173,10 +173,7 @@ private async Task RunAsync()
173173

174174
_initialized.TrySetResult(true);
175175

176-
if (_logger.IsEnabled(LogLevel.Debug))
177-
{
178-
_logger.LogDebug("Refreshed cluster manifest");
179-
}
176+
LogRefreshedClusterManifest(_logger);
180177

181178
await Task.Delay(_typeManagementOptions.TypeMapRefreshInterval, _shutdownCts.Token);
182179
}
@@ -186,7 +183,7 @@ private async Task RunAsync()
186183
}
187184
catch (Exception exception)
188185
{
189-
_logger.LogWarning(exception, "Error trying to get cluster manifest from gateway {Gateway}", gateway);
186+
LogErrorTryingToGetClusterManifest(_logger, exception, gateway);
190187
await Task.Delay(StandardExtensions.Min(_typeManagementOptions.TypeMapRefreshInterval, TimeSpan.FromSeconds(5)), _shutdownCts.Token).SuppressThrowing();
191188

192189
// Reset the gateway so that another will be selected on the next iteration.
@@ -198,10 +195,7 @@ private async Task RunAsync()
198195
{
199196
_initialized.TrySetResult(false);
200197

201-
if (_logger.IsEnabled(LogLevel.Debug))
202-
{
203-
_logger.LogDebug("Stopped refreshing cluster manifest");
204-
}
198+
LogStoppedRefreshingClusterManifest(_logger);
205199
}
206200
}
207201

@@ -215,7 +209,7 @@ private async Task RunAsync()
215209
}
216210
catch (Exception exception)
217211
{
218-
_logger.LogWarning(exception, "Failed to fetch cluster manifest update from {Provider}.", provider);
212+
LogFailedToFetchClusterManifestUpdate(_logger, exception, provider);
219213

220214
// If the provider does not support the new API, fall back to the old one.
221215
var manifest = await provider.GetClusterManifest();
@@ -244,5 +238,41 @@ public void Dispose()
244238
{
245239
_shutdownCts.Cancel();
246240
}
241+
242+
[LoggerMessage(
243+
Level = LogLevel.Information,
244+
Message = "Graceful shutdown of cluster manifest provider was canceled."
245+
)]
246+
private static partial void LogGracefulShutdownCanceled(ILogger logger);
247+
248+
[LoggerMessage(
249+
Level = LogLevel.Error,
250+
Message = "Error stopping cluster manifest provider."
251+
)]
252+
private static partial void LogStoppingClusterManifestProvider(ILogger logger, Exception exception);
253+
254+
[LoggerMessage(
255+
Level = LogLevel.Debug,
256+
Message = "Refreshed cluster manifest."
257+
)]
258+
private static partial void LogRefreshedClusterManifest(ILogger logger);
259+
260+
[LoggerMessage(
261+
Level = LogLevel.Warning,
262+
Message = "Error trying to get cluster manifest from gateway '{Gateway}'."
263+
)]
264+
private static partial void LogErrorTryingToGetClusterManifest(ILogger logger, Exception exception, SiloAddress gateway);
265+
266+
[LoggerMessage(
267+
Level = LogLevel.Debug,
268+
Message = "Stopped refreshing cluster manifest."
269+
)]
270+
private static partial void LogStoppedRefreshingClusterManifest(ILogger logger);
271+
272+
[LoggerMessage(
273+
Level = LogLevel.Warning,
274+
Message = "Failed to fetch cluster manifest update from '{Provider}'."
275+
)]
276+
private static partial void LogFailedToFetchClusterManifestUpdate(ILogger logger, Exception exception, IClusterManifestSystemTarget provider);
247277
}
248278
}

0 commit comments

Comments
 (0)