Skip to content

Add option to include ElapsedMs in the HttpContext prior to invoking EnrichDiagnosticContext #391

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

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -32,6 +32,7 @@ class RequestLoggingMiddleware
readonly Func<HttpContext, string, double, int, IEnumerable<LogEventProperty>> _getMessageTemplateProperties;
readonly ILogger? _logger;
readonly bool _includeQueryInRequestPath;
readonly bool _addElapsedToHttpContext;
static readonly LogEventProperty[] NoProperties = [];

public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options)
@@ -45,6 +46,7 @@ public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnost
_messageTemplate = new MessageTemplateParser().Parse(options.MessageTemplate);
_logger = options.Logger?.ForContext<RequestLoggingMiddleware>();
_includeQueryInRequestPath = options.IncludeQueryInRequestPath;
_addElapsedToHttpContext = options.AddElapsedToHttpContext;
_getMessageTemplateProperties = options.GetMessageTemplateProperties;
}

@@ -82,6 +84,11 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector

if (!logger.IsEnabled(level)) return false;

if (_addElapsedToHttpContext)
{
httpContext.Items.Add(RequestLoggingOptions.HttpContextItemsElapsedKey, elapsedMs);
}

_enrichDiagnosticContext?.Invoke(_diagnosticContext, httpContext);

if (!collector.TryComplete(out var collectedProperties, out var collectedException))
10 changes: 10 additions & 0 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingOptions.cs
Original file line number Diff line number Diff line change
@@ -41,6 +41,11 @@ static IEnumerable<LogEventProperty> DefaultGetMessageTemplateProperties(HttpCon
new LogEventProperty("StatusCode", new ScalarValue(statusCode)),
new LogEventProperty("Elapsed", new ScalarValue(elapsedMs))
];

/// <summary>
/// The key used to add the ElapsedMs value to <see cref="HttpContext"/> <c>Items</c> collection
/// </summary>
public const string HttpContextItemsElapsedKey = "Serilog.AspNetCore.ElapsedMs";

/// <summary>
/// Gets or sets the message template. The default value is
@@ -81,6 +86,11 @@ static IEnumerable<LogEventProperty> DefaultGetMessageTemplateProperties(HttpCon
/// </summary>
public bool IncludeQueryInRequestPath { get; set; }

/// <summary>
/// Add the elapsed millisecond value to the <see cref="HttpContext"/> <c>Items</c> collection before invoking <c>EnrichDiagnosticContext</c>
/// </summary>
public bool AddElapsedToHttpContext { get; set; }

/// <summary>
/// A function to specify the values of the MessageTemplateProperties.
/// </summary>
Original file line number Diff line number Diff line change
@@ -63,7 +63,29 @@ public async Task RequestLoggingMiddlewareShouldEnrich()
Assert.Equal("GET", completionEvent.Properties["RequestMethod"].LiteralValue());
Assert.True(completionEvent.Properties.ContainsKey("Elapsed"));
}

[Fact]
public async Task RequestLoggingMiddlewareShouldEnrichWithElapsed()
{
var (sink, web) = Setup(options =>
{
options.AddElapsedToHttpContext = true;
options.EnrichDiagnosticContext += (diagnosticContext, httpContext) =>
{
var elapsedValue = (double)(httpContext.Items[RequestLoggingOptions.HttpContextItemsElapsedKey] ?? -0.1);
diagnosticContext.Set("ElapsedValue", elapsedValue);
};
});

await web.CreateClient().GetAsync("/resource");

Assert.NotEmpty(sink.Writes);

var completionEvent = sink.Writes.First(logEvent => Matching.FromSource<RequestLoggingMiddleware>()(logEvent));

Assert.True((double)completionEvent.Properties["ElapsedValue"].LiteralValue()! > 0);
}

[Fact]
public async Task RequestLoggingMiddlewareShouldEnrichWithCustomisedProperties()
{