diff --git a/src/Shared/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs b/src/Shared/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs index d9d02a04..0671545c 100644 --- a/src/Shared/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs +++ b/src/Shared/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs @@ -4,7 +4,6 @@ using NLog.LayoutRenderers; #if ASP_NET_CORE using Microsoft.AspNetCore.Http; - #endif namespace NLog.Web.LayoutRenderers @@ -23,7 +22,20 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) builder.Append(LookupTraceIdentifier(httpContext)); } -#if ASP_NET_CORE + /// + /// Ignore the System.Diagnostics.Activity.Current.Id value (AspNetCore3 uses ActivityId by default) + /// + 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; diff --git a/tests/Shared/LayoutRenderers/AspNetTraceIdentifierRendererTests.cs b/tests/Shared/LayoutRenderers/AspNetTraceIdentifierRendererTests.cs index 50c2a8ea..00de7a37 100644 --- a/tests/Shared/LayoutRenderers/AspNetTraceIdentifierRendererTests.cs +++ b/tests/Shared/LayoutRenderers/AspNetTraceIdentifierRendererTests.cs @@ -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