Skip to content

Commit be0f551

Browse files
committed
Add tags to activity
1 parent f39a94d commit be0f551

5 files changed

Lines changed: 123 additions & 4 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ internal GrpcEventSource(string eventSourceName)
5252
{
5353
}
5454

55+
[MethodImpl(MethodImplOptions.NoInlining)]
5556
[Event(eventId: 1, Level = EventLevel.Verbose)]
5657
public void CallStart(string method)
5758
{
@@ -61,6 +62,7 @@ public void CallStart(string method)
6162
WriteEvent(1, method);
6263
}
6364

65+
[MethodImpl(MethodImplOptions.NoInlining)]
6466
[Event(eventId: 2, Level = EventLevel.Verbose)]
6567
public void CallStop()
6668
{

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

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,8 @@ private void ProcessHandlerError(Exception ex, string method)
175175
{
176176
HttpContext.Response.ConsolidateTrailers(this);
177177
}
178-
179-
GrpcEventSource.Log.CallFailed(_status.StatusCode);
180-
GrpcEventSource.Log.CallStop();
178+
179+
LogCallEnd();
181180

182181
_callComplete = true;
183182
}
@@ -260,11 +259,25 @@ private void EndCallCore()
260259
HttpContext.Response.ConsolidateTrailers(this);
261260
}
262261

263-
GrpcEventSource.Log.CallStop();
262+
LogCallEnd();
264263

265264
_callComplete = true;
266265
}
267266

267+
private void LogCallEnd()
268+
{
269+
var currentActivity = Activity.Current;
270+
if (currentActivity != null)
271+
{
272+
currentActivity.AddTag("GrpcStatus", _status.StatusCode.ToTrailerString());
273+
}
274+
if (_status.StatusCode != StatusCode.OK)
275+
{
276+
GrpcEventSource.Log.CallFailed(_status.StatusCode);
277+
}
278+
GrpcEventSource.Log.CallStop();
279+
}
280+
268281
protected override WriteOptions? WriteOptionsCore { get; set; }
269282

270283
protected override AuthContext AuthContextCore
@@ -329,6 +342,12 @@ protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders)
329342

330343
public void Initialize()
331344
{
345+
var currentActivity = Activity.Current;
346+
if (currentActivity != null)
347+
{
348+
Activity.Current.AddTag("GrpcMethod", MethodCore);
349+
}
350+
332351
GrpcEventSource.Log.CallStart(MethodCore);
333352

334353
var timeout = GetTimeout();

test/Grpc.AspNetCore.Server.Tests/Grpc.AspNetCore.Server.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<ItemGroup>
99
<Protobuf Include="Proto\*.proto" GrpcServices="Both" />
1010

11+
<Compile Include="..\Shared\ActivityReplacer.cs" Link="Infrastructure\ActivityReplacer.cs" />
1112
<Compile Include="..\Shared\HttpContextHelpers.cs" Link="Infrastructure\HttpContextHelpers.cs" />
1213
<Compile Include="..\Shared\HttpContextServerCallContextHelpers.cs" Link="Infrastructure\HttpContextServerCallContextHelpers.cs" />
1314
<Compile Include="..\Shared\MessageHelpers.cs" Link="Infrastructure\MessageHelpers.cs" />

test/Grpc.AspNetCore.Server.Tests/HttpContextServerCallContextTests.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
using System;
2020
using System.Collections.Generic;
21+
using System.Diagnostics;
2122
using System.Linq;
2223
using System.Net;
2324
using System.Security.Cryptography.X509Certificates;
@@ -608,6 +609,62 @@ private async Task LongRunningDeadlineAbort_WaitsUntilDeadlineAbortIsFinished(st
608609
Assert.IsTrue(serverCallContext._callComplete);
609610
}
610611

612+
[Test]
613+
public void Initialize_MethodInPath_SetsMethodOnActivity()
614+
{
615+
using (new ActivityReplacer())
616+
{
617+
// Arrange
618+
var httpContext = new DefaultHttpContext();
619+
httpContext.Request.Path = "/Package.Service/Method";
620+
var context = CreateServerCallContext(httpContext);
621+
622+
// Act
623+
context.Initialize();
624+
625+
// Assert
626+
Assert.AreEqual("/Package.Service/Method", Activity.Current.Tags.Single(t => t.Key == "GrpcMethod").Value);
627+
}
628+
}
629+
630+
[Test]
631+
public async Task EndCallAsync_StatusSet_SetsStatusOnActivity()
632+
{
633+
using (new ActivityReplacer())
634+
{
635+
// Arrange
636+
var httpContext = new DefaultHttpContext();
637+
var context = CreateServerCallContext(httpContext);
638+
context.Status = new Status(StatusCode.ResourceExhausted, string.Empty);
639+
640+
// Act
641+
context.Initialize();
642+
await context.EndCallAsync();
643+
644+
// Assert
645+
Assert.AreEqual("8", Activity.Current.Tags.Single(t => t.Key == "GrpcStatus").Value);
646+
}
647+
}
648+
649+
[Test]
650+
public async Task ProcessHandlerErrorAsync_Exception_SetsStatusOnActivity()
651+
{
652+
using (new ActivityReplacer())
653+
{
654+
// Arrange
655+
var httpContext = new DefaultHttpContext();
656+
var context = CreateServerCallContext(httpContext);
657+
context.Status = new Status(StatusCode.ResourceExhausted, string.Empty);
658+
659+
// Act
660+
context.Initialize();
661+
await context.ProcessHandlerErrorAsync(new Exception(), "MethodName");
662+
663+
// Assert
664+
Assert.AreEqual("2", Activity.Current.Tags.Single(t => t.Key == "GrpcStatus").Value);
665+
}
666+
}
667+
611668
private HttpContextServerCallContext CreateServerCallContext(HttpContext httpContext, ILogger? logger = null)
612669
{
613670
return new HttpContextServerCallContext(httpContext, new GrpcServiceOptions(), logger ?? NullLogger.Instance);

test/Shared/ActivityReplacer.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#region Copyright notice and license
2+
3+
// Copyright 2019 The gRPC Authors
4+
//
5+
// Licensed under the Apache License, Version 2.0 (the "License");
6+
// you may not use this file except in compliance with the License.
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
17+
#endregion
18+
19+
using System;
20+
using System.Diagnostics;
21+
22+
namespace Grpc.Tests.Shared
23+
{
24+
public class ActivityReplacer : IDisposable
25+
{
26+
private readonly Activity _activity;
27+
28+
public ActivityReplacer()
29+
{
30+
_activity = new Activity("Test");
31+
_activity.Start();
32+
}
33+
34+
public void Dispose()
35+
{
36+
Debug.Assert(Activity.Current == _activity);
37+
_activity.Stop();
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)