Skip to content

Commit

Permalink
aspnet-traceidentifier should automatically check Activity.Current.Id…
Browse files Browse the repository at this point in the history
… for AspNetCore3 (#524)

* aspnet-traceidentifier should automatically check System.Diagnostics.Activity.Current for AspNetCore3

* aspnet-traceidentifier should automatically check System.Diagnostics.Activity.Current for AspNetCore3 (test)
  • Loading branch information
snakefoot authored Feb 24, 2020
1 parent 4369fa1 commit 7c6861d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/Shared/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using NLog.LayoutRenderers;
#if ASP_NET_CORE
using Microsoft.AspNetCore.Http;

#endif

namespace NLog.Web.LayoutRenderers
Expand All @@ -23,7 +22,20 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
builder.Append(LookupTraceIdentifier(httpContext));
}

#if ASP_NET_CORE
/// <summary>
/// Ignore the System.Diagnostics.Activity.Current.Id value (AspNetCore3 uses ActivityId by default)
/// </summary>
public bool IgnoreActivityId { get; set; }

#if ASP_NET_CORE3
private string LookupTraceIdentifier(HttpContext httpContext)
{
if (IgnoreActivityId)
return httpContext.TraceIdentifier;
else
return System.Diagnostics.Activity.Current?.Id ?? httpContext.TraceIdentifier;
}
#elif ASP_NET_CORE
private string LookupTraceIdentifier(HttpContext httpContext)
{
return httpContext.TraceIdentifier;
Expand Down
20 changes: 20 additions & 0 deletions tests/Shared/LayoutRenderers/AspNetTraceIdentifierRendererTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,26 @@ public void AvailableTraceIdentifierRendersGuid()
Assert.Equal(expectedResult.ToString(), result);
}

#if ASP_NET_CORE3
[Fact]
public void AvailableActivityIdOverridesGuid()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

var expectedResult = System.Guid.NewGuid();
SetTraceIdentifier(httpContext, expectedResult);

System.Diagnostics.Activity.Current = new System.Diagnostics.Activity("MyOperation").Start();

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal(System.Diagnostics.Activity.Current.Id, result);
}
#endif

private static void SetTraceIdentifier(HttpContextBase httpContext, Guid? expectedResult)
{
#if ASP_NET_CORE
Expand Down

0 comments on commit 7c6861d

Please sign in to comment.