@@ -24,6 +24,9 @@ internal class HostingApplicationDiagnostics
2424 private const string DeprecatedDiagnosticsEndRequestKey = "Microsoft.AspNetCore.Hosting.EndRequest" ;
2525 private const string DiagnosticsUnhandledExceptionKey = "Microsoft.AspNetCore.Hosting.UnhandledException" ;
2626
27+ private const string ActivitySourceName = "Microsoft.AspNetCore.Hosting" ;
28+ private static readonly ActivitySource _activitySource = new ActivitySource ( ActivitySourceName ) ;
29+
2730 private readonly DiagnosticListener _diagnosticListener ;
2831 private readonly ILogger _logger ;
2932
@@ -46,11 +49,13 @@ public void BeginRequest(HttpContext httpContext, HostingApplication.Context con
4649 }
4750
4851 var diagnosticListenerEnabled = _diagnosticListener . IsEnabled ( ) ;
52+ var diagnosticListenerActivityCreationEnabled = ( diagnosticListenerEnabled && _diagnosticListener . IsEnabled ( ActivityName , httpContext ) ) ;
4953 var loggingEnabled = _logger . IsEnabled ( LogLevel . Critical ) ;
5054
51- if ( loggingEnabled || ( diagnosticListenerEnabled && _diagnosticListener . IsEnabled ( ActivityName , httpContext ) ) )
55+
56+ if ( loggingEnabled || diagnosticListenerActivityCreationEnabled || _activitySource . HasListeners ( ) )
5257 {
53- context . Activity = StartActivity ( httpContext , out var hasDiagnosticListener ) ;
58+ context . Activity = StartActivity ( httpContext , loggingEnabled , diagnosticListenerActivityCreationEnabled , out var hasDiagnosticListener ) ;
5459 context . HasDiagnosticListener = hasDiagnosticListener ;
5560 }
5661
@@ -245,11 +250,20 @@ private static void RecordRequestStartEventLog(HttpContext httpContext)
245250 }
246251
247252 [ MethodImpl ( MethodImplOptions . NoInlining ) ]
248- private Activity StartActivity ( HttpContext httpContext , out bool hasDiagnosticListener )
253+ private Activity ? StartActivity ( HttpContext httpContext , bool loggingEnabled , bool diagnosticListenerActivityCreationEnabled , out bool hasDiagnosticListener )
249254 {
250- var activity = new Activity ( ActivityName ) ;
255+ var activity = _activitySource . CreateActivity ( ActivityName , ActivityKind . Server ) ;
256+ if ( activity is null && ( loggingEnabled || diagnosticListenerActivityCreationEnabled ) )
257+ {
258+ activity = new Activity ( ActivityName ) ;
259+ }
251260 hasDiagnosticListener = false ;
252261
262+ if ( activity is null )
263+ {
264+ return null ;
265+ }
266+
253267 var headers = httpContext . Request . Headers ;
254268 if ( ! headers . TryGetValue ( HeaderNames . TraceParent , out var requestId ) )
255269 {
0 commit comments