Skip to content

Commit a456d47

Browse files
authored
Wrap EventSource calls with IsEnabled (#2052)
1 parent 8471823 commit a456d47

File tree

10 files changed

+132
-34
lines changed

10 files changed

+132
-34
lines changed

src/Grpc.AspNetCore.Server/Internal/GrpcEventSource.cs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616

1717
#endregion
1818

19+
using System.Diagnostics;
1920
using System.Diagnostics.Tracing;
2021
using System.Runtime.CompilerServices;
2122
using Grpc.Core;
2223

2324
namespace Grpc.AspNetCore.Server.Internal;
2425

25-
internal class GrpcEventSource : EventSource
26+
internal sealed class GrpcEventSource : EventSource
2627
{
2728
public static readonly GrpcEventSource Log = new GrpcEventSource();
2829

@@ -68,6 +69,8 @@ internal GrpcEventSource(string eventSourceName)
6869
[Event(eventId: 1, Level = EventLevel.Verbose)]
6970
public void CallStart(string method)
7071
{
72+
AssertEventSourceEnabled();
73+
7174
Interlocked.Increment(ref _totalCalls);
7275
Interlocked.Increment(ref _currentCalls);
7376

@@ -78,6 +81,8 @@ public void CallStart(string method)
7881
[Event(eventId: 2, Level = EventLevel.Verbose)]
7982
public void CallStop()
8083
{
84+
AssertEventSourceEnabled();
85+
8186
Interlocked.Decrement(ref _currentCalls);
8287

8388
WriteEvent(2);
@@ -87,6 +92,8 @@ public void CallStop()
8792
[Event(eventId: 3, Level = EventLevel.Error)]
8893
public void CallFailed(StatusCode statusCode)
8994
{
95+
AssertEventSourceEnabled();
96+
9097
Interlocked.Increment(ref _callsFailed);
9198

9299
WriteEvent(3, (int)statusCode);
@@ -96,6 +103,8 @@ public void CallFailed(StatusCode statusCode)
96103
[Event(eventId: 4, Level = EventLevel.Error)]
97104
public void CallDeadlineExceeded()
98105
{
106+
AssertEventSourceEnabled();
107+
99108
Interlocked.Increment(ref _callsDeadlineExceeded);
100109

101110
WriteEvent(4);
@@ -105,6 +114,8 @@ public void CallDeadlineExceeded()
105114
[Event(eventId: 5, Level = EventLevel.Verbose)]
106115
public void MessageSent()
107116
{
117+
AssertEventSourceEnabled();
118+
108119
Interlocked.Increment(ref _messageSent);
109120

110121
WriteEvent(5);
@@ -114,6 +125,8 @@ public void MessageSent()
114125
[Event(eventId: 6, Level = EventLevel.Verbose)]
115126
public void MessageReceived()
116127
{
128+
AssertEventSourceEnabled();
129+
117130
Interlocked.Increment(ref _messageReceived);
118131

119132
WriteEvent(6);
@@ -123,11 +136,20 @@ public void MessageReceived()
123136
[Event(eventId: 7, Level = EventLevel.Verbose)]
124137
public void CallUnimplemented(string method)
125138
{
139+
AssertEventSourceEnabled();
140+
126141
Interlocked.Increment(ref _callsUnimplemented);
127142

128143
WriteEvent(7, method);
129144
}
130145

146+
[Conditional("DEBUG")]
147+
[NonEvent]
148+
private void AssertEventSourceEnabled()
149+
{
150+
Debug.Assert(IsEnabled(), "Event source should be enabled.");
151+
}
152+
131153
protected override void OnEventCommand(EventCommandEventArgs command)
132154
{
133155
if (command.Command == EventCommand.Enable)

src/Grpc.AspNetCore.Server/Internal/HttpContextServerCallContext.cs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -297,9 +297,15 @@ private void LogCallEnd()
297297
}
298298
if (_status.StatusCode != StatusCode.OK)
299299
{
300-
GrpcEventSource.Log.CallFailed(_status.StatusCode);
300+
if (GrpcEventSource.Log.IsEnabled())
301+
{
302+
GrpcEventSource.Log.CallFailed(_status.StatusCode);
303+
}
304+
}
305+
if (GrpcEventSource.Log.IsEnabled())
306+
{
307+
GrpcEventSource.Log.CallStop();
301308
}
302-
GrpcEventSource.Log.CallStop();
303309
}
304310

305311
protected override WriteOptions? WriteOptionsCore { get; set; }
@@ -379,7 +385,10 @@ public void Initialize(ISystemClock? clock = null)
379385
_activity.AddTag(GrpcServerConstants.ActivityMethodTag, MethodCore);
380386
}
381387

382-
GrpcEventSource.Log.CallStart(MethodCore);
388+
if (GrpcEventSource.Log.IsEnabled())
389+
{
390+
GrpcEventSource.Log.CallStart(MethodCore);
391+
}
383392

384393
var timeout = GetTimeout();
385394

@@ -459,7 +468,10 @@ private TimeSpan GetTimeout()
459468
internal async Task DeadlineExceededAsync()
460469
{
461470
GrpcServerLog.DeadlineExceeded(Logger, GetTimeout());
462-
GrpcEventSource.Log.CallDeadlineExceeded();
471+
if (GrpcEventSource.Log.IsEnabled())
472+
{
473+
GrpcEventSource.Log.CallDeadlineExceeded();
474+
}
463475

464476
var status = new Status(StatusCode.DeadlineExceeded, "Deadline Exceeded");
465477

src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,10 @@ public static async Task WriteSingleMessageAsync<TResponse>(this PipeWriter pipe
6565
serializer(response, serializationContext);
6666

6767
GrpcServerLog.MessageSent(serverCallContext.Logger);
68-
GrpcEventSource.Log.MessageSent();
68+
if (GrpcEventSource.Log.IsEnabled())
69+
{
70+
GrpcEventSource.Log.MessageSent();
71+
}
6972
}
7073
catch (Exception ex)
7174
{
@@ -112,7 +115,10 @@ public static async Task WriteStreamedMessageAsync<TResponse>(this PipeWriter pi
112115
}
113116

114117
GrpcServerLog.MessageSent(serverCallContext.Logger);
115-
GrpcEventSource.Log.MessageSent();
118+
if (GrpcEventSource.Log.IsEnabled())
119+
{
120+
GrpcEventSource.Log.MessageSent();
121+
}
116122
}
117123
catch (Exception ex)
118124
{
@@ -226,8 +232,10 @@ public static async ValueTask<T> ReadSingleMessageAsync<T>(this PipeReader input
226232
serverCallContext.DeserializationContext.SetPayload(null);
227233

228234
GrpcServerLog.ReceivedMessage(logger);
229-
230-
GrpcEventSource.Log.MessageReceived();
235+
if (GrpcEventSource.Log.IsEnabled())
236+
{
237+
GrpcEventSource.Log.MessageReceived();
238+
}
231239

232240
// Store the request
233241
// Need to verify the request completes with no additional data
@@ -318,8 +326,10 @@ public static async ValueTask<T> ReadSingleMessageAsync<T>(this PipeReader input
318326
serverCallContext.DeserializationContext.SetPayload(null);
319327

320328
GrpcServerLog.ReceivedMessage(logger);
321-
322-
GrpcEventSource.Log.MessageReceived();
329+
if (GrpcEventSource.Log.IsEnabled())
330+
{
331+
GrpcEventSource.Log.MessageReceived();
332+
}
323333

324334
return request;
325335
}

src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,10 @@ public RequestDelegate CreateUnimplementedMethod()
118118

119119
var unimplementedMethod = httpContext.Request.RouteValues["unimplementedMethod"]?.ToString() ?? "<unknown>";
120120
Log.MethodUnimplemented(logger, unimplementedMethod);
121-
GrpcEventSource.Log.CallUnimplemented(httpContext.Request.Path.Value!);
122-
121+
if (GrpcEventSource.Log.IsEnabled())
122+
{
123+
GrpcEventSource.Log.CallUnimplemented(httpContext.Request.Path.Value!);
124+
}
123125
GrpcProtocolHelpers.SetStatus(GrpcProtocolHelpers.GetTrailersDestination(httpContext.Response), new Status(StatusCode.Unimplemented, "Method is unimplemented."));
124126
return Task.CompletedTask;
125127
};
@@ -146,8 +148,10 @@ public RequestDelegate CreateUnimplementedService()
146148

147149
var unimplementedService = httpContext.Request.RouteValues["unimplementedService"]?.ToString() ?? "<unknown>";
148150
Log.ServiceUnimplemented(logger, unimplementedService);
149-
GrpcEventSource.Log.CallUnimplemented(httpContext.Request.Path.Value!);
150-
151+
if (GrpcEventSource.Log.IsEnabled())
152+
{
153+
GrpcEventSource.Log.CallUnimplemented(httpContext.Request.Path.Value!);
154+
}
151155
GrpcProtocolHelpers.SetStatus(GrpcProtocolHelpers.GetTrailersDestination(httpContext.Response), new Status(StatusCode.Unimplemented, "Service is unimplemented."));
152156
return Task.CompletedTask;
153157
};

src/Grpc.Net.Client/Internal/GrpcCall.cs

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -585,8 +585,10 @@ private async Task RunCall(HttpRequestMessage request, TimeSpan? timeout)
585585
}
586586
else
587587
{
588-
GrpcEventSource.Log.MessageReceived();
589-
588+
if (GrpcEventSource.Log.IsEnabled())
589+
{
590+
GrpcEventSource.Log.MessageReceived();
591+
}
590592
FinishResponseAndCleanUp(status.Value);
591593
finished = FinishCall(request, diagnosticSourceEnabled, activity, status.Value);
592594

@@ -809,7 +811,10 @@ public Exception CreateFailureStatusException(Status status)
809811
private (bool diagnosticSourceEnabled, Activity? activity) InitializeCall(HttpRequestMessage request, TimeSpan? timeout)
810812
{
811813
GrpcCallLog.StartingCall(Logger, Method.Type, request.RequestUri!);
812-
GrpcEventSource.Log.CallStart(Method.FullName);
814+
if (GrpcEventSource.Log.IsEnabled())
815+
{
816+
GrpcEventSource.Log.CallStart(Method.FullName);
817+
}
813818

814819
// Deadline will cancel the call CTS.
815820
// Only exceed deadline/start timer after reader/writer have been created, otherwise deadline will cancel
@@ -882,19 +887,26 @@ private bool FinishCall(HttpRequestMessage request, bool diagnosticSourceEnabled
882887
if (IsDeadlineExceededUnsynchronized())
883888
{
884889
GrpcCallLog.DeadlineExceeded(Logger);
885-
GrpcEventSource.Log.CallDeadlineExceeded();
886-
890+
if (GrpcEventSource.Log.IsEnabled())
891+
{
892+
GrpcEventSource.Log.CallDeadlineExceeded();
893+
}
887894
_deadline = DateTime.MaxValue;
888895
}
889896
}
890897
}
891898

892899
GrpcCallLog.GrpcStatusError(Logger, status.StatusCode, status.Detail);
893-
GrpcEventSource.Log.CallFailed(status.StatusCode);
900+
if (GrpcEventSource.Log.IsEnabled())
901+
{
902+
GrpcEventSource.Log.CallFailed(status.StatusCode);
903+
}
894904
}
895905
GrpcCallLog.FinishedCall(Logger);
896-
GrpcEventSource.Log.CallStop();
897-
906+
if (GrpcEventSource.Log.IsEnabled())
907+
{
908+
GrpcEventSource.Log.CallStop();
909+
}
898910
// Activity needs to be stopped in the same execution context it was started
899911
if (activity != null)
900912
{
@@ -1096,8 +1108,10 @@ private void DeadlineExceeded()
10961108
Debug.Assert(Monitor.IsEntered(this));
10971109

10981110
GrpcCallLog.DeadlineExceeded(Logger);
1099-
GrpcEventSource.Log.CallDeadlineExceeded();
1100-
1111+
if (GrpcEventSource.Log.IsEnabled())
1112+
{
1113+
GrpcEventSource.Log.CallDeadlineExceeded();
1114+
}
11011115
// Set _deadline to DateTime.MaxValue to signal that deadline has been exceeded.
11021116
// This prevents duplicate logging and cancellation.
11031117
_deadline = DateTime.MaxValue;

src/Grpc.Net.Client/Internal/GrpcEventSource.cs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616

1717
#endregion
1818

19+
using System.Diagnostics;
1920
using System.Diagnostics.Tracing;
2021
using System.Runtime.CompilerServices;
2122
using Grpc.Core;
2223

2324
namespace Grpc.Net.Client.Internal;
2425

25-
internal class GrpcEventSource : EventSource
26+
internal sealed class GrpcEventSource : EventSource
2627
{
2728
public static readonly GrpcEventSource Log = new GrpcEventSource();
2829

@@ -68,6 +69,8 @@ internal void ResetCounters()
6869
[Event(eventId: 1, Level = EventLevel.Verbose)]
6970
public void CallStart(string method)
7071
{
72+
AssertEventSourceEnabled();
73+
7174
Interlocked.Increment(ref _totalCalls);
7275
Interlocked.Increment(ref _currentCalls);
7376

@@ -78,6 +81,8 @@ public void CallStart(string method)
7881
[Event(eventId: 2, Level = EventLevel.Verbose)]
7982
public void CallStop()
8083
{
84+
AssertEventSourceEnabled();
85+
8186
Interlocked.Decrement(ref _currentCalls);
8287

8388
WriteEvent(2);
@@ -87,6 +92,8 @@ public void CallStop()
8792
[Event(eventId: 3, Level = EventLevel.Error)]
8893
public void CallFailed(StatusCode statusCode)
8994
{
95+
AssertEventSourceEnabled();
96+
9097
Interlocked.Increment(ref _callsFailed);
9198

9299
WriteEvent(3, (int)statusCode);
@@ -96,6 +103,8 @@ public void CallFailed(StatusCode statusCode)
96103
[Event(eventId: 4, Level = EventLevel.Error)]
97104
public void CallDeadlineExceeded()
98105
{
106+
AssertEventSourceEnabled();
107+
99108
Interlocked.Increment(ref _callsDeadlineExceeded);
100109

101110
WriteEvent(4);
@@ -105,6 +114,8 @@ public void CallDeadlineExceeded()
105114
[Event(eventId: 5, Level = EventLevel.Verbose)]
106115
public void MessageSent()
107116
{
117+
AssertEventSourceEnabled();
118+
108119
Interlocked.Increment(ref _messageSent);
109120

110121
WriteEvent(5);
@@ -114,11 +125,20 @@ public void MessageSent()
114125
[Event(eventId: 6, Level = EventLevel.Verbose)]
115126
public void MessageReceived()
116127
{
128+
AssertEventSourceEnabled();
129+
117130
Interlocked.Increment(ref _messageReceived);
118131

119132
WriteEvent(6);
120133
}
121134

135+
[Conditional("DEBUG")]
136+
[NonEvent]
137+
private void AssertEventSourceEnabled()
138+
{
139+
Debug.Assert(IsEnabled(), "Event source should be enabled.");
140+
}
141+
122142
protected override void OnEventCommand(EventCommandEventArgs command)
123143
{
124144
if (command.Command == EventCommand.Enable)

src/Grpc.Net.Client/Internal/Http/PushUnaryContent.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,10 @@ protected override Task SerializeToStreamAsync(Stream stream, TransportContext?
4747
#pragma warning restore CA2012 // Use ValueTasks correctly
4848
if (writeMessageTask.IsCompletedSuccessfully())
4949
{
50-
GrpcEventSource.Log.MessageSent();
50+
if (GrpcEventSource.Log.IsEnabled())
51+
{
52+
GrpcEventSource.Log.MessageSent();
53+
}
5154
return Task.CompletedTask;
5255
}
5356

@@ -57,7 +60,10 @@ protected override Task SerializeToStreamAsync(Stream stream, TransportContext?
5760
private static async Task WriteMessageCore(ValueTask writeMessageTask)
5861
{
5962
await writeMessageTask.ConfigureAwait(false);
60-
GrpcEventSource.Log.MessageSent();
63+
if (GrpcEventSource.Log.IsEnabled())
64+
{
65+
GrpcEventSource.Log.MessageSent();
66+
}
6167
}
6268

6369
protected override bool TryComputeLength(out long length)

0 commit comments

Comments
 (0)