11using System ;
22using System . Text ;
3- using NLog . Config ;
43using NLog . LayoutRenderers ;
54#if ASP_NET_CORE
65using Microsoft . AspNetCore . Http ;
@@ -21,47 +20,38 @@ public class AspNetTraceIdentifierLayoutRenderer : AspNetLayoutRendererBase
2120 /// <inheritdoc />
2221 protected override void Append ( StringBuilder builder , LogEventInfo logEvent )
2322 {
24- var httpContext = HttpContextAccessor ? . HttpContext ;
25- builder . Append ( LookupTraceIdentifier ( httpContext ) ) ;
23+ builder . Append ( LookupTraceIdentifier ( ) ) ;
2624 }
2725
2826 /// <summary>
29- /// Ignore the System.Diagnostics.Activity.Current.Id value (AspNetCore3 uses ActivityId by default)
27+ /// Ignore the System.Diagnostics.Activity.Current.Id value, and always use HttpContext.TraceIdentifier
3028 /// </summary>
3129 public bool IgnoreActivityId { get ; set ; }
3230
33- #if NETCOREAPP3_0_OR_GREATER
34- private string ? LookupTraceIdentifier ( HttpContext ? httpContext )
31+ #if ASP_NET_CORE
32+ private string ? LookupTraceIdentifier ( )
3533 {
3634 if ( IgnoreActivityId )
37- return httpContext ? . TraceIdentifier ;
35+ return HttpContextAccessor ? . HttpContext ? . TraceIdentifier ;
3836 else
39- return System . Diagnostics . Activity . Current ? . Id ?? httpContext ? . TraceIdentifier ;
40- }
41- #elif ASP_NET_CORE
42- private string ? LookupTraceIdentifier ( HttpContext ? httpContext )
43- {
44- return httpContext ? . TraceIdentifier ;
37+ return System . Diagnostics . Activity . Current ? . Id ?? HttpContextAccessor ? . HttpContext ? . TraceIdentifier ;
4538 }
4639#else
4740 /// <summary>
4841 /// Requires IIS ETW feature enabled. https://docs.microsoft.com/en-us/iis/configuration/system.webServer/httpTracing/
4942 ///
5043 /// See also http://blog.tatham.oddie.com.au/2012/02/07/code-request-correlation-in-asp-net/
5144 /// </summary>
52- private static string ? LookupTraceIdentifier ( System . Web . HttpContextBase ? httpContext )
45+ private string ? LookupTraceIdentifier ( )
5346 {
54- IServiceProvider ? serviceProvider = httpContext ;
55- if ( serviceProvider != null )
47+ IServiceProvider ? serviceProvider = HttpContextAccessor ? . HttpContext ;
48+ var workerRequest = ( System . Web . HttpWorkerRequest ? ) serviceProvider ? . GetService ( typeof ( System . Web . HttpWorkerRequest ) ) ;
49+ if ( workerRequest != null )
5650 {
57- var workerRequest = ( System . Web . HttpWorkerRequest ) serviceProvider . GetService ( typeof ( System . Web . HttpWorkerRequest ) ) ;
58- if ( workerRequest != null )
51+ Guid requestIdGuid = workerRequest . RequestTraceIdentifier ;
52+ if ( requestIdGuid != Guid . Empty )
5953 {
60- Guid requestIdGuid = workerRequest . RequestTraceIdentifier ;
61- if ( requestIdGuid != Guid . Empty )
62- {
63- return requestIdGuid . ToString ( ) ;
64- }
54+ return requestIdGuid . ToString ( ) ;
6555 }
6656 }
6757
0 commit comments