Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use implicit logging scope for Activity #22376

Merged
merged 8 commits into from
Jun 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/DefaultBuilder/src/WebHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,18 @@ public static IWebHostBuilder CreateDefaultBuilder(string[] args)
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
.ConfigureLogging((hostingContext, loggingBuilder) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
loggingBuilder.Configure(options =>
{
options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
| ActivityTrackingOptions.TraceId
| ActivityTrackingOptions.ParentId;
});
loggingBuilder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
loggingBuilder.AddConsole();
loggingBuilder.AddDebug();
loggingBuilder.AddEventSourceLogger();
}).
UseDefaultServiceProvider((context, options) =>
{
Expand Down
43 changes: 0 additions & 43 deletions src/Hosting/Hosting/src/Internal/ActivityExtensions.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public void BeginRequest(HttpContext httpContext, HostingApplication.Context con
// Scope may be relevant for a different level of logging, so we always create it
// see: https://github.com/aspnet/Hosting/pull/944
// Scope can be null if logging is not on.
context.Scope = _logger.RequestScope(httpContext, context.Activity);
context.Scope = _logger.RequestScope(httpContext);

if (_logger.IsEnabled(LogLevel.Information))
{
Expand Down
31 changes: 6 additions & 25 deletions src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using Microsoft.AspNetCore.Http;
Expand All @@ -14,9 +13,9 @@ namespace Microsoft.AspNetCore.Hosting
{
internal static class HostingLoggerExtensions
{
public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext, Activity activity)
public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext)
{
return logger.BeginScope(new HostingLogScope(httpContext, activity));
return logger.BeginScope(new HostingLogScope(httpContext));
}

public static void ApplicationError(this ILogger logger, Exception exception)
Expand Down Expand Up @@ -97,15 +96,14 @@ private class HostingLogScope : IReadOnlyList<KeyValuePair<string, object>>
{
private readonly string _path;
private readonly string _traceIdentifier;
private readonly Activity _activity;

private string _cachedToString;

public int Count
{
get
{
return 5;
return 2;
}
}

Expand All @@ -121,31 +119,17 @@ public KeyValuePair<string, object> this[int index]
{
return new KeyValuePair<string, object>("RequestPath", _path);
}
else if (index == 2)
{
return new KeyValuePair<string, object>("SpanId", _activity.GetSpanId());
}
else if (index == 3)
{
return new KeyValuePair<string, object>("TraceId", _activity.GetTraceId());
}
else if (index == 4)
{
return new KeyValuePair<string, object>("ParentId", _activity.GetParentId());
}

throw new ArgumentOutOfRangeException(nameof(index));
}
}

public HostingLogScope(HttpContext httpContext, Activity activity)
public HostingLogScope(HttpContext httpContext)
{
_traceIdentifier = httpContext.TraceIdentifier;
_path = (httpContext.Request.PathBase.HasValue
? httpContext.Request.PathBase + httpContext.Request.Path
: httpContext.Request.Path).ToString();

_activity = activity;
}

public override string ToString()
Expand All @@ -154,12 +138,9 @@ public override string ToString()
{
_cachedToString = string.Format(
CultureInfo.InvariantCulture,
"RequestPath:{0} RequestId:{1}, SpanId:{2}, TraceId:{3}, ParentId:{4}",
"RequestPath:{0} RequestId:{1}",
_path,
_traceIdentifier,
_activity.GetSpanId(),
_activity.GetTraceId(),
_activity.GetParentId());
_traceIdentifier);
}

return _cachedToString;
Expand Down
44 changes: 0 additions & 44 deletions src/Hosting/Hosting/test/HostingApplicationDiagnosticsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,50 +40,6 @@ public void CreateContextWithDisabledLoggerDoesNotCreateActivity()
Assert.Null(Activity.Current);
}

[Fact]
public void CreateContextWithEnabledLoggerCreatesActivityAndSetsActivityInScope()
{
// Arrange
var logger = new LoggerWithScopes(isEnabled: true);
var hostingApplication = CreateApplication(out var features, logger: logger);

// Act
var context = hostingApplication.CreateContext(features);

Assert.Single(logger.Scopes);
var pairs = ((IReadOnlyList<KeyValuePair<string, object>>)logger.Scopes[0]).ToDictionary(p => p.Key, p => p.Value);
Assert.Equal(Activity.Current.Id, pairs["SpanId"].ToString());
Assert.Equal(Activity.Current.RootId, pairs["TraceId"].ToString());
Assert.Equal(string.Empty, pairs["ParentId"]?.ToString());
}

[Fact]
public void CreateContextWithEnabledLoggerAndRequestIdCreatesActivityAndSetsActivityInScope()
{
// Arrange

// Generate an id we can use for the request id header (in the correct format)
var activity = new Activity("IncomingRequest");
activity.Start();
var id = activity.Id;
activity.Stop();

var logger = new LoggerWithScopes(isEnabled: true);
var hostingApplication = CreateApplication(out var features, logger: logger, configure: context =>
{
context.Request.Headers["Request-Id"] = id;
});

// Act
var context = hostingApplication.CreateContext(features);

Assert.Single(logger.Scopes);
var pairs = ((IReadOnlyList<KeyValuePair<string, object>>)logger.Scopes[0]).ToDictionary(p => p.Key, p => p.Value);
Assert.Equal(Activity.Current.Id, pairs["SpanId"].ToString());
Assert.Equal(Activity.Current.RootId, pairs["TraceId"].ToString());
Assert.Equal(id, pairs["ParentId"].ToString());
}

[Fact]
public void ActivityStopDoesNotFireIfNoListenerAttachedForStart()
{
Expand Down