@@ -24,6 +24,9 @@ internal class HostingApplicationDiagnostics
24
24
private const string DeprecatedDiagnosticsEndRequestKey = "Microsoft.AspNetCore.Hosting.EndRequest" ;
25
25
private const string DiagnosticsUnhandledExceptionKey = "Microsoft.AspNetCore.Hosting.UnhandledException" ;
26
26
27
+ private const string ActivitySourceName = "Microsoft.AspNetCore.Hosting" ;
28
+ private static readonly ActivitySource _activitySource = new ActivitySource ( ActivitySourceName ) ;
29
+
27
30
private readonly DiagnosticListener _diagnosticListener ;
28
31
private readonly ILogger _logger ;
29
32
@@ -46,11 +49,13 @@ public void BeginRequest(HttpContext httpContext, HostingApplication.Context con
46
49
}
47
50
48
51
var diagnosticListenerEnabled = _diagnosticListener . IsEnabled ( ) ;
52
+ var diagnosticListenerActivityCreationEnabled = ( diagnosticListenerEnabled && _diagnosticListener . IsEnabled ( ActivityName , httpContext ) ) ;
49
53
var loggingEnabled = _logger . IsEnabled ( LogLevel . Critical ) ;
50
54
51
- if ( loggingEnabled || ( diagnosticListenerEnabled && _diagnosticListener . IsEnabled ( ActivityName , httpContext ) ) )
55
+
56
+ if ( loggingEnabled || diagnosticListenerActivityCreationEnabled || _activitySource . HasListeners ( ) )
52
57
{
53
- context . Activity = StartActivity ( httpContext , out var hasDiagnosticListener ) ;
58
+ context . Activity = StartActivity ( httpContext , loggingEnabled , diagnosticListenerActivityCreationEnabled , out var hasDiagnosticListener ) ;
54
59
context . HasDiagnosticListener = hasDiagnosticListener ;
55
60
}
56
61
@@ -245,11 +250,20 @@ private static void RecordRequestStartEventLog(HttpContext httpContext)
245
250
}
246
251
247
252
[ 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 )
249
254
{
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
+ }
251
260
hasDiagnosticListener = false ;
252
261
262
+ if ( activity is null )
263
+ {
264
+ return null ;
265
+ }
266
+
253
267
var headers = httpContext . Request . Headers ;
254
268
if ( ! headers . TryGetValue ( HeaderNames . TraceParent , out var requestId ) )
255
269
{
0 commit comments