Skip to content

Commit db24143

Browse files
authored
chore(Orleans.Core): Use [LoggerMessage] p2 (#9540)
* chore(Orleans.Runtime): Use [LoggerMessage] p4 Cleanup `src\Orleans.Core\Networking\Connection.cs` * chore(Orleans.Runtime): Use [LoggerMessage] p4 Cleanup `src\Orleans.Core\Utils\ObserverManager.cs` * chore(Orleans.Runtime): Use [LoggerMessage] p4 Cleanup `src\Orleans.Core\Networking\Shared\SocketConnection.cs` * Migrates logging methods to source generators Replaces manual LoggerMessage.Define declarations with LoggerMessage attributes to leverage compile-time source generation. Improves performance by eliminating runtime delegate creation and reduces boilerplate code maintenance overhead.
1 parent 3a50ce5 commit db24143

File tree

4 files changed

+195
-130
lines changed

4 files changed

+195
-130
lines changed

src/Orleans.Core/Networking/Connection.cs

Lines changed: 101 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
namespace Orleans.Runtime.Messaging
1818
{
19-
internal abstract class Connection
19+
internal abstract partial class Connection
2020
{
2121
private static readonly Func<ConnectionContext, Task> OnConnectedDelegate = context => OnConnectedAsync(context);
2222
private static readonly Action<object> OnConnectionClosedDelegate = state => ((Connection)state).OnTransportConnectionClosed();
@@ -152,13 +152,7 @@ private void StartClosing(Exception exception)
152152
_initializationTcs.TrySetException(exception ?? new ConnectionAbortedException("Connection initialization failed"));
153153
_initializationTcs.Task.Ignore();
154154

155-
if (this.Log.IsEnabled(LogLevel.Information))
156-
{
157-
this.Log.LogInformation(
158-
exception,
159-
"Closing connection {Connection}",
160-
this);
161-
}
155+
LogInformationClosingConnection(this.Log, exception, this);
162156

163157
task.Start(TaskScheduler.Default);
164158
}
@@ -188,7 +182,7 @@ private async Task CloseAsync()
188182
catch (Exception processIncomingException)
189183
{
190184
// Swallow any exceptions here.
191-
this.Log.LogWarning(processIncomingException, "Exception processing incoming messages on connection {Connection}", this);
185+
LogWarningExceptionProcessingIncomingMessages(this.Log, processIncomingException, this);
192186
}
193187
}
194188

@@ -201,7 +195,7 @@ private async Task CloseAsync()
201195
catch (Exception processOutgoingException)
202196
{
203197
// Swallow any exceptions here.
204-
this.Log.LogWarning(processOutgoingException, "Exception processing outgoing messages on connection {Connection}", this);
198+
LogWarningExceptionProcessingOutgoingMessages(this.Log, processOutgoingException, this);
205199
}
206200
}
207201

@@ -215,7 +209,7 @@ private async Task CloseAsync()
215209
}
216210
catch (Exception exception)
217211
{
218-
this.Log.LogWarning(exception, "Exception aborting connection {Connection}", this);
212+
LogWarningExceptionAbortingConnection(this.Log, exception, this);
219213
}
220214

221215
await _transportConnectionClosed.Task;
@@ -228,7 +222,7 @@ private async Task CloseAsync()
228222
catch (Exception abortException)
229223
{
230224
// Swallow any exceptions here.
231-
this.Log.LogWarning(abortException, "Exception terminating connection {Connection}", this);
225+
LogWarningExceptionTerminatingConnection(this.Log, abortException, this);
232226
}
233227

234228
// Reject in-flight messages.
@@ -243,23 +237,18 @@ private async Task CloseAsync()
243237
var i = 0;
244238
while (this.outgoingMessages.Reader.TryRead(out var message))
245239
{
246-
if (i == 0 && Log.IsEnabled(LogLevel.Information))
240+
if (i == 0)
247241
{
248-
this.Log.LogInformation(
249-
"Rerouting messages for remote endpoint {EndPoint}",
250-
this.RemoteEndPoint?.ToString() ?? "(never connected)");
242+
LogInformationReroutingMessages(this.Log, new EndPointLogValue(this.RemoteEndPoint));
251243
}
252244

253245
++i;
254246
this.RetryMessage(message);
255247
}
256248

257-
if (i > 0 && this.Log.IsEnabled(LogLevel.Information))
249+
if (i > 0)
258250
{
259-
this.Log.LogInformation(
260-
"Rerouted {Count} messages for remote endpoint {EndPoint}",
261-
i,
262-
this.RemoteEndPoint?.ToString() ?? "(never connected)");
251+
LogInformationReroutedMessages(this.Log, i, new EndPointLogValue(this.RemoteEndPoint));
263252
}
264253
}
265254

@@ -334,10 +323,7 @@ private async Task ProcessIncoming()
334323
{
335324
if (IsValid)
336325
{
337-
this.Log.LogWarning(
338-
exception,
339-
"Exception while processing messages from remote endpoint {EndPoint}",
340-
this.RemoteEndPoint);
326+
LogWarningExceptionProcessingMessagesFromRemote(this.Log, exception, this.RemoteEndPoint);
341327
}
342328

343329
error = exception;
@@ -402,10 +388,7 @@ private async Task ProcessOutgoing()
402388
{
403389
if (IsValid)
404390
{
405-
this.Log.LogWarning(
406-
exception,
407-
"Exception while processing messages to remote endpoint {EndPoint}",
408-
this.RemoteEndPoint);
391+
LogWarningExceptionProcessingMessagesToRemote(this.Log, exception, this.RemoteEndPoint);
409392
}
410393

411394
error = exception;
@@ -419,13 +402,7 @@ private async Task ProcessOutgoing()
419402

420403
private void RerouteMessage(Message message)
421404
{
422-
if (this.Log.IsEnabled(LogLevel.Information))
423-
{
424-
this.Log.LogInformation(
425-
"Rerouting message {Message} from remote endpoint {EndPoint}",
426-
message,
427-
this.RemoteEndPoint?.ToString() ?? "(never connected)");
428-
}
405+
LogInformationReroutingMessage(this.Log, message, new EndPointLogValue(this.RemoteEndPoint));
429406

430407
ThreadPool.UnsafeQueueUserWorkItem(state =>
431408
{
@@ -453,12 +430,7 @@ private static EndPoint NormalizeEndpoint(EndPoint endpoint)
453430
/// <returns><see langword="true"/> if the exception should not be caught and <see langword="false"/> if it should be caught.</returns>
454431
private bool HandleReceiveMessageFailure(Message message, Exception exception)
455432
{
456-
this.Log.LogError(
457-
exception,
458-
"Exception reading message {Message} from remote endpoint {Remote} to local endpoint {Local}",
459-
message,
460-
this.RemoteEndPoint,
461-
this.LocalEndPoint);
433+
LogErrorExceptionReadingMessage(this.Log, exception, message, this.RemoteEndPoint, this.LocalEndPoint);
462434

463435
// If deserialization completely failed, rethrow the exception so that it can be handled at another level.
464436
if (message is null || exception is InvalidMessageFrameException)
@@ -500,12 +472,7 @@ private bool HandleSendMessageFailure(Message message, Exception exception)
500472
// We get here if we failed to serialize the msg (or any other catastrophic failure).
501473
// Request msg fails to serialize on the sender, so we just enqueue a rejection msg.
502474
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
503-
this.Log.LogError(
504-
exception,
505-
"Exception sending message {Message} to remote endpoint {Remote} from local endpoint {Local}",
506-
message,
507-
this.RemoteEndPoint,
508-
this.LocalEndPoint);
475+
LogErrorExceptionSendingMessage(this.Log, exception, message, this.RemoteEndPoint, this.LocalEndPoint);
509476

510477
if (message is null || exception is InvalidMessageFrameException)
511478
{
@@ -535,10 +502,9 @@ private bool HandleSendMessageFailure(Message message, Exception exception)
535502
}
536503
else
537504
{
538-
this.Log.LogWarning(
539-
(int)ErrorCode.Messaging_OutgoingMS_DroppingMessage,
505+
LogWarningDroppingMessage(
506+
this.Log,
540507
exception,
541-
"Dropping message which failed during serialization: {Message}",
542508
message);
543509

544510
MessagingInstruments.OnDroppedSentMessage(message);
@@ -581,5 +547,89 @@ public void Reset()
581547
this.connection = null;
582548
}
583549
}
550+
551+
private readonly struct EndPointLogValue(EndPoint endPoint)
552+
{
553+
public override string ToString() => endPoint?.ToString() ?? "(never connected)";
554+
}
555+
556+
[LoggerMessage(
557+
Level = LogLevel.Information,
558+
Message = "Closing connection {Connection}"
559+
)]
560+
private static partial void LogInformationClosingConnection(ILogger logger, Exception exception, Connection connection);
561+
562+
[LoggerMessage(
563+
Level = LogLevel.Warning,
564+
Message = "Exception processing incoming messages on connection {Connection}"
565+
)]
566+
private static partial void LogWarningExceptionProcessingIncomingMessages(ILogger logger, Exception exception, Connection connection);
567+
568+
[LoggerMessage(
569+
Level = LogLevel.Warning,
570+
Message = "Exception processing outgoing messages on connection {Connection}"
571+
)]
572+
private static partial void LogWarningExceptionProcessingOutgoingMessages(ILogger logger, Exception exception, Connection connection);
573+
574+
[LoggerMessage(
575+
Level = LogLevel.Warning,
576+
Message = "Exception aborting connection {Connection}"
577+
)]
578+
private static partial void LogWarningExceptionAbortingConnection(ILogger logger, Exception exception, Connection connection);
579+
580+
[LoggerMessage(
581+
Level = LogLevel.Warning,
582+
Message = "Exception terminating connection {Connection}"
583+
)]
584+
private static partial void LogWarningExceptionTerminatingConnection(ILogger logger, Exception exception, Connection connection);
585+
586+
[LoggerMessage(
587+
Level = LogLevel.Information,
588+
Message = "Rerouting messages for remote endpoint {EndPoint}"
589+
)]
590+
private static partial void LogInformationReroutingMessages(ILogger logger, EndPointLogValue endPoint);
591+
592+
[LoggerMessage(
593+
Level = LogLevel.Information,
594+
Message = "Rerouted {Count} messages for remote endpoint {EndPoint}"
595+
)]
596+
private static partial void LogInformationReroutedMessages(ILogger logger, int count, EndPointLogValue endPoint);
597+
598+
[LoggerMessage(
599+
Level = LogLevel.Warning,
600+
Message = "Exception while processing messages from remote endpoint {EndPoint}"
601+
)]
602+
private static partial void LogWarningExceptionProcessingMessagesFromRemote(ILogger logger, Exception exception, EndPoint endPoint);
603+
604+
[LoggerMessage(
605+
Level = LogLevel.Warning,
606+
Message = "Exception while processing messages to remote endpoint {EndPoint}"
607+
)]
608+
private static partial void LogWarningExceptionProcessingMessagesToRemote(ILogger logger, Exception exception, EndPoint endPoint);
609+
610+
[LoggerMessage(
611+
Level = LogLevel.Information,
612+
Message = "Rerouting message {Message} from remote endpoint {EndPoint}"
613+
)]
614+
private static partial void LogInformationReroutingMessage(ILogger logger, Message message, EndPointLogValue endPoint);
615+
616+
[LoggerMessage(
617+
Level = LogLevel.Error,
618+
Message = "Exception reading message {Message} from remote endpoint {Remote} to local endpoint {Local}"
619+
)]
620+
private static partial void LogErrorExceptionReadingMessage(ILogger logger, Exception exception, Message message, EndPoint remote, EndPoint local);
621+
622+
[LoggerMessage(
623+
Level = LogLevel.Error,
624+
Message = "Exception sending message {Message} to remote endpoint {Remote} from local endpoint {Local}"
625+
)]
626+
private static partial void LogErrorExceptionSendingMessage(ILogger logger, Exception exception, Message message, EndPoint remote, EndPoint local);
627+
628+
[LoggerMessage(
629+
EventId = (int)ErrorCode.Messaging_OutgoingMS_DroppingMessage,
630+
Level = LogLevel.Warning,
631+
Message = "Dropping message which failed during serialization: {Message}"
632+
)]
633+
private static partial void LogWarningDroppingMessage(ILogger logger, Exception exception, Message message);
584634
}
585635
}

src/Orleans.Core/Networking/Shared/SocketConnection.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
namespace Orleans.Networking.Shared
1313
{
14-
internal sealed class SocketConnection : TransportConnection
14+
internal sealed partial class SocketConnection : TransportConnection
1515
{
1616
private static readonly int MinAllocBufferSize = SlabMemoryPool.BlockSize / 2;
1717
private static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
@@ -99,7 +99,7 @@ private async Task StartAsync()
9999
}
100100
catch (Exception ex)
101101
{
102-
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.{nameof(StartAsync)}.");
102+
LogErrorUnexpectedExceptionInStartAsync(_trace, ex);
103103
}
104104
}
105105

@@ -355,7 +355,7 @@ private void CancelConnectionClosedToken()
355355
}
356356
catch (Exception ex)
357357
{
358-
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.{nameof(CancelConnectionClosedToken)}.");
358+
LogErrorUnexpectedExceptionInCancelConnectionClosedToken(_trace, ex);
359359
}
360360
}
361361

@@ -376,5 +376,17 @@ private static bool IsConnectionAbortError(SocketError errorCode)
376376
errorCode == SocketError.Interrupted ||
377377
(errorCode == SocketError.InvalidArgument && !IsWindows);
378378
}
379+
380+
[LoggerMessage(
381+
Level = LogLevel.Error,
382+
Message = "Unexpected exception in SocketConnection.StartAsync."
383+
)]
384+
private static partial void LogErrorUnexpectedExceptionInStartAsync(ILogger logger, Exception exception);
385+
386+
[LoggerMessage(
387+
Level = LogLevel.Error,
388+
Message = "Unexpected exception in SocketConnection.CancelConnectionClosedToken."
389+
)]
390+
private static partial void LogErrorUnexpectedExceptionInCancelConnectionClosedToken(ILogger logger, Exception exception);
379391
}
380392
}

0 commit comments

Comments
 (0)