From 8c1c6cef651759a61115b7dca4659fe0905bb74b Mon Sep 17 00:00:00 2001 From: Rolf Kristensen Date: Sun, 2 Dec 2018 19:33:41 +0100 Subject: [PATCH] Added aspnet-traceidentifier for AspNet for NLog.Web --- .../AspNetTraceIdentifierLayoutRenderer.cs | 33 ++++++++++++++++++- NLog.Web/NLog.Web.csproj | 3 ++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/NLog.Web.AspNetCore/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs b/NLog.Web.AspNetCore/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs index 0f66ce387..9a5bc0c94 100644 --- a/NLog.Web.AspNetCore/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs +++ b/NLog.Web.AspNetCore/LayoutRenderers/AspNetTraceIdentifierLayoutRenderer.cs @@ -17,7 +17,38 @@ public class AspNetTraceIdentifierLayoutRenderer : AspNetLayoutRendererBase protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { var httpContext = HttpContextAccessor.HttpContext; - builder.Append(httpContext.TraceIdentifier); + builder.Append(LookupTraceIdentifier(httpContext)); } + +#if ASP_NET_CORE + private string LookupTraceIdentifier(Microsoft.AspNetCore.Http.HttpContext httpContext) + { + return httpContext.TraceIdentifier; + } +#else + /// + /// Requires IIS ETW feature enabled. https://docs.microsoft.com/en-us/iis/configuration/system.webServer/httpTracing/ + /// + /// See also http://blog.tatham.oddie.com.au/2012/02/07/code-request-correlation-in-asp-net/ + /// + private string LookupTraceIdentifier(System.Web.HttpContextBase httpContext) + { + var provider = httpContext as IServiceProvider; + if (provider != null) + { + var workerRequest = (System.Web.HttpWorkerRequest)provider.GetService(typeof(System.Web.HttpWorkerRequest)); + if (workerRequest != null) + { + Guid requestIdGuid = workerRequest.RequestTraceIdentifier; + if (requestIdGuid != Guid.Empty) + { + return requestIdGuid.ToString(); + } + } + } + + return null; + } +#endif } } diff --git a/NLog.Web/NLog.Web.csproj b/NLog.Web/NLog.Web.csproj index 3c177816d..936d3c791 100644 --- a/NLog.Web/NLog.Web.csproj +++ b/NLog.Web/NLog.Web.csproj @@ -75,6 +75,9 @@ + + AspNetTraceIdentifierLayoutRenderer.cs +