Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use LoggerMessageGenerator in Orleans.Core #9352

Merged
merged 7 commits into from
Mar 21, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
chore: use Use LoggerMessageGenerator for core Orleans.Core
Meir017 authored and ReubenBond committed Mar 21, 2025
commit 5ecfe03df72054d247d6312d506d524ce2f06dc6
34 changes: 23 additions & 11 deletions src/Orleans.Core/Lifecycle/LifecycleSubject.cs
Original file line number Diff line number Diff line change
@@ -116,11 +116,7 @@ public virtual async Task OnStart(CancellationToken cancellationToken = default)
}
catch (Exception ex) when (ex is not OrleansLifecycleCanceledException)
{
this.Logger.LogError(
(int)ErrorCode.LifecycleStartFailure,
ex,
"Lifecycle start canceled due to errors at stage '{Stage}'.",
_highStage is { } highStage ? GetStageName(highStage) : "Unknown");
LogErrorLifecycleStartFailure(Logger, ex, _highStage is { } highStage ? GetStageName(highStage) : "Unknown");
throw;
}

@@ -167,7 +163,7 @@ public virtual async Task OnStop(CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested && !loggedCancellation)
{
this.Logger.LogWarning("Lifecycle stop operations canceled at stage '{Stage}' by request.", GetStageName(observerGroup.Key));
LogWarningLifecycleStopCanceled(Logger, GetStageName(observerGroup.Key));
loggedCancellation = true;
}

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

this.OnStopStageCompleted(stage);
@@ -251,6 +243,26 @@ public OrderedObserver(int stage, ILifecycleObserver observer)
public void Dispose() => Observer = null;
}

[LoggerMessage(
EventId = (int)ErrorCode.LifecycleStartFailure,
Level = LogLevel.Error,
Message = "Lifecycle start canceled due to errors at stage '{Stage}'."
)]
private static partial void LogErrorLifecycleStartFailure(ILogger logger, Exception ex, string stage);

[LoggerMessage(
EventId = (int)ErrorCode.LifecycleStopFailure,
Level = LogLevel.Warning,
Message = "Stopping lifecycle encountered an error at stage '{Stage}'. Continuing to stop."
)]
private static partial void LogWarningLifecycleStopFailure(ILogger logger, Exception ex, string stage);

[LoggerMessage(
Level = LogLevel.Warning,
Message = "Lifecycle stop operations canceled at stage '{Stage}' by request."
)]
private static partial void LogWarningLifecycleStopCanceled(ILogger logger, string stage);

[LoggerMessage(
EventId = (int)ErrorCode.SiloStartPerfMeasure,
Level = LogLevel.Trace,
70 changes: 51 additions & 19 deletions src/Orleans.Core/Messaging/ClientMessageCenter.cs
Original file line number Diff line number Diff line change
@@ -85,7 +85,7 @@ public ClientMessageCenter(
numMessages = 0;
this.grainBuckets = new WeakReference<ClientOutboundConnection>[clientMessagingOptions.Value.ClientSenderBuckets];
logger = loggerFactory.CreateLogger<ClientMessageCenter>();
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Proxy grain client constructed");
LogDebugProxyGrainClientConstructed();
ClientInstruments.RegisterConnectedGatewayCountObserve(() => connectionManager.ConnectionCount);
}

@@ -94,7 +94,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
await EstablishInitialConnection(cancellationToken);

Running = true;
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Proxy grain client started");
LogDebugProxyGrainClientStarted();
}

private async Task EstablishInitialConnection(CancellationToken cancellationToken)
@@ -169,7 +169,7 @@ public void SendMessage(Message msg)
{
if (!Running)
{
LogErrorProxyClientMsgCtrNotRunning(logger, msg);
LogErrorProxyClientMsgCtrNotRunning(msg);
return;
}

@@ -180,7 +180,7 @@ public void SendMessage(Message msg)
if (connection is null) return;

connection.Send(msg);
LogTraceProxyClientQueueRequest(logger, msg, connection.RemoteEndPoint);
LogTraceProxyClientQueueRequest(msg, connection.RemoteEndPoint);
}
else
{
@@ -197,7 +197,7 @@ async Task SendAsync(ValueTask<Connection> task, Message message)

connection.Send(message);

LogTraceProxyClientQueueRequest(logger, message, connection.RemoteEndPoint);
LogTraceProxyClientQueueRequest(message, connection.RemoteEndPoint);
}
catch (Exception exception)
{
@@ -248,11 +248,7 @@ private ValueTask<Connection> GetGatewayConnection(Message msg)
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
logger.LogWarning(
(int)ErrorCode.ProxyClient_CannotSend,
"Unable to send message {Message}; Gateway manager state is {GatewayManager}",
msg,
gatewayManager);
LogWarningProxyClientCannotSend(msg, gatewayManager);
return new ValueTask<Connection>(default(Connection));
}

@@ -286,11 +282,7 @@ private ValueTask<Connection> GetGatewayConnection(Message msg)
if (addr == null)
{
RejectMessage(msg, "No gateways available");
logger.LogWarning(
(int)ErrorCode.ProxyClient_CannotSend_NoGateway,
"Unable to send message {Message}; Gateway manager state is {GatewayManager}",
msg,
gatewayManager);
LogWarningProxyClientCannotSendNoGateway(msg, gatewayManager);
return new ValueTask<Connection>(default(Connection));
}

@@ -373,11 +365,11 @@ public void RejectMessage(Message msg, string reason, Exception exc = null)

if (msg.Direction != Message.Directions.Request)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug((int)ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {Message}. Reason = {Reason}", msg, reason);
if (logger.IsEnabled(LogLevel.Debug)) LogDebugProxyClientDroppingMsg(msg, reason);
}
else
{
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug((int)ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {Message}. Reason = {Reason}", msg, reason);
if (logger.IsEnabled(LogLevel.Debug)) LogDebugProxyClientRejectingMsg(msg, reason);
MessagingInstruments.OnRejectedMessage(msg);
var error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason, exc);
DispatchLocalMessage(error);
@@ -411,13 +403,53 @@ public void Dispose()
Level = LogLevel.Error,
Message = "Ignoring {Message} because the Client message center is not running"
)]
private static partial void LogErrorProxyClientMsgCtrNotRunning(ILogger logger, Message message);
private partial void LogErrorProxyClientMsgCtrNotRunning(Message message);

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_QueueRequest,
Level = LogLevel.Trace,
Message = "Sending message {Message} via gateway {Gateway}"
)]
private static partial void LogTraceProxyClientQueueRequest(ILogger logger, Message message, EndPoint gateway);
private partial void LogTraceProxyClientQueueRequest(Message message, EndPoint gateway);

[LoggerMessage(
Level = LogLevel.Debug,
Message = "Proxy grain client constructed"
)]
private partial void LogDebugProxyGrainClientConstructed();

[LoggerMessage(
Level = LogLevel.Debug,
Message = "Proxy grain client started"
)]
private partial void LogDebugProxyGrainClientStarted();

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_CannotSend,
Level = LogLevel.Warning,
Message = "Unable to send message {Message}; Gateway manager state is {GatewayManager}"
)]
private partial void LogWarningProxyClientCannotSend(Message message, GatewayManager gatewayManager);

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_CannotSend_NoGateway,
Level = LogLevel.Warning,
Message = "Unable to send message {Message}; Gateway manager state is {GatewayManager}"
)]
private partial void LogWarningProxyClientCannotSendNoGateway(Message message, GatewayManager gatewayManager);

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_DroppingMsg,
Level = LogLevel.Debug,
Message = "Dropping message: {Message}. Reason = {Reason}"
)]
private partial void LogDebugProxyClientDroppingMsg(Message message, string reason);

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_RejectingMsg,
Level = LogLevel.Debug,
Message = "Rejecting message: {Message}. Reason = {Reason}"
)]
private partial void LogDebugProxyClientRejectingMsg(Message message, string reason);
}
}
52 changes: 38 additions & 14 deletions src/Orleans.Core/Messaging/GatewayManager.cs
Original file line number Diff line number Diff line change
@@ -68,16 +68,12 @@ public async Task StartAsync(CancellationToken cancellationToken)
{
// this situation can occur if the client starts faster than the silos.
var providerName = this.gatewayListProvider.GetType().FullName;
this.logger.LogWarning((int)ErrorCode.GatewayManager_NoGateways, "Could not find any gateway in '{GatewayListProviderName}'. Orleans client cannot initialize until at least one gateway becomes available.", providerName);
LogWarningNoGateways(this.logger, providerName);
var message = $"Could not find any gateway in '{providerName}'. Orleans client cannot initialize until at least one gateway becomes available.";
throw new SiloUnavailableException(message);
}

this.logger.LogInformation(
(int)ErrorCode.GatewayManager_FoundKnownGateways,
"Found {GatewayCount} gateways: {Gateways}",
knownGateways.Count,
Utils.EnumerableToString(knownGateways));
LogInformationFoundKnownGateways(this.logger, knownGateways.Count, new(knownGateways));

this.roundRobinCounter = this.gatewayOptions.PreferredGatewayIndex >= 0 ? this.gatewayOptions.PreferredGatewayIndex : Random.Shared.Next(knownGateways.Count);
var newGateways = new List<SiloAddress>();
@@ -194,7 +190,7 @@ public List<SiloAddress> GetLiveGateways()
{
if (cachedLiveGateways.Count == 0 && knownGateways.Count > 0)
{
this.logger.LogWarning("All known gateways have been marked dead locally. Expediting gateway refresh and resetting all gateways to live status.");
LogWarningAllGatewaysMarkedDead(this.logger);

cachedLiveGateways = knownGateways;
cachedLiveGatewaysSet = new HashSet<SiloAddress>(knownGateways);
@@ -267,7 +263,7 @@ private async Task RefreshGatewaySnapshot()
}
catch (Exception exc)
{
LogErrorRefreshingGateways(logger, exc);
LogErrorRefreshingGateways(this.logger, exc);
}
}

@@ -368,10 +364,7 @@ private async Task CloseEvictedGatewayConnections(List<SiloAddress> liveGateways

if (!isLiveGateway)
{
if (logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Closing connection to {Endpoint} because it has been marked as dead", address);
}
LogInformationClosingConnection(this.logger, address);

await this.connectionManager.CloseAsync(address);
}
@@ -383,21 +376,52 @@ public void Dispose()
this.gatewayRefreshTimer.Dispose();
}

[LoggerMessage(
EventId = (int)ErrorCode.GatewayManager_NoGateways,
Level = LogLevel.Warning,
Message = "Could not find any gateway in '{GatewayListProviderName}'. Orleans client cannot initialize until at least one gateway becomes available."
)]
private static partial void LogWarningNoGateways(ILogger logger, string gatewayListProviderName);

private record struct UrisLogValue(IList<Uri> Uris)
{
public override string ToString() => Utils.EnumerableToString(Uris);
}

[LoggerMessage(
EventId = (int)ErrorCode.GatewayManager_FoundKnownGateways,
Level = LogLevel.Information,
Message = "Found {GatewayCount} gateways: {Gateways}"
)]
private static partial void LogInformationFoundKnownGateways(ILogger logger, int gatewayCount, UrisLogValue gateways);

[LoggerMessage(
Level = LogLevel.Warning,
Message = "All known gateways have been marked dead locally. Expediting gateway refresh and resetting all gateways to live status."
)]
private static partial void LogWarningAllGatewaysMarkedDead(ILogger logger);

[LoggerMessage(
EventId = (int)ErrorCode.ProxyClient_GetGateways,
Level = LogLevel.Error,
Message = "Error refreshing gateways."
)]
private static partial void LogErrorRefreshingGateways(ILogger logger, Exception exc);

[LoggerMessage(
Level = LogLevel.Information,
Message = "Closing connection to {Endpoint} because it has been marked as dead"
)]
private static partial void LogInformationClosingConnection(ILogger logger, SiloAddress endpoint);

[LoggerMessage(
EventId = (int)ErrorCode.GatewayManager_AllGatewaysDead,
Level = LogLevel.Warning,
Message = "All gateways have previously been marked as dead. Clearing the list of dead gateways to expedite reconnection."
)]
private static partial void LogWarningAllGatewaysDead(ILogger logger);

private readonly struct SiloAddresses(List<SiloAddress> addresses)
private readonly struct SiloAddressesLogValue(List<SiloAddress> addresses)
{
public override string ToString() => Utils.EnumerableToString(addresses);
}
@@ -407,6 +431,6 @@ private readonly struct SiloAddresses(List<SiloAddress> addresses)
Level = LogLevel.Debug,
Message = "Refreshed the live gateway list. Found {KnownGatewayCount} gateways from gateway list provider: {KnownGateways}. Picked only known live out of them. Now has {LiveGatewayCount} live gateways: {LiveGateways}. Previous refresh time was = {PreviousRefreshTime}"
)]
private static partial void LogDebugRefreshedLiveGatewayList(ILogger logger, int knownGatewayCount, SiloAddresses knownGateways, int liveGatewayCount, SiloAddresses liveGateways, DateTime previousRefreshTime);
private static partial void LogDebugRefreshedLiveGatewayList(ILogger logger, int knownGatewayCount, SiloAddressesLogValue knownGateways, int liveGatewayCount, SiloAddressesLogValue liveGateways, DateTime previousRefreshTime);
}
}