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

6.1.0 Release #310

Merged
merged 7 commits into from
Nov 30, 2022
Merged
Changes from 1 commit
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
Next Next commit
Add GetMessageTemplateProperties option
dnperfors committed Aug 29, 2022
commit ccd73c309bf61be35a6f7a31602e57526076c16a
13 changes: 5 additions & 8 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@
using Serilog.Extensions.Hosting;
using Serilog.Parsing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
@@ -32,6 +33,7 @@ class RequestLoggingMiddleware
readonly MessageTemplate _messageTemplate;
readonly Action<IDiagnosticContext, HttpContext> _enrichDiagnosticContext;
readonly Func<HttpContext, double, Exception, LogEventLevel> _getLevel;
readonly Func<HttpContext, string, double, int, IEnumerable<LogEventProperty>> _getMessageTemplateProperties;
readonly ILogger _logger;
readonly bool _includeQueryInRequestPath;
static readonly LogEventProperty[] NoProperties = new LogEventProperty[0];
@@ -47,6 +49,7 @@ public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnost
_messageTemplate = new MessageTemplateParser().Parse(options.MessageTemplate);
_logger = options.Logger?.ForContext<RequestLoggingMiddleware>();
_includeQueryInRequestPath = options.IncludeQueryInRequestPath;
_getMessageTemplateProperties = options.GetMessageTemplateProperties;
}

// ReSharper disable once UnusedMember.Global
@@ -90,13 +93,7 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector
collectedProperties = NoProperties;

// Last-in (correctly) wins...
var properties = collectedProperties.Concat(new[]
{
new LogEventProperty("RequestMethod", new ScalarValue(httpContext.Request.Method)),
new LogEventProperty("RequestPath", new ScalarValue(GetPath(httpContext, _includeQueryInRequestPath))),
new LogEventProperty("StatusCode", new ScalarValue(statusCode)),
new LogEventProperty("Elapsed", new ScalarValue(elapsedMs))
});
var properties = collectedProperties.Concat(_getMessageTemplateProperties(httpContext, GetPath(httpContext, _includeQueryInRequestPath), elapsedMs, statusCode));

var evt = new LogEvent(DateTimeOffset.Now, level, ex ?? collectedException, _messageTemplate, properties);
logger.Write(evt);
@@ -123,7 +120,7 @@ static string GetPath(HttpContext httpContext, bool includeQueryInRequestPath)
{
requestPath = httpContext.Request.Path.ToString();
}

return requestPath;
}
}
16 changes: 16 additions & 0 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingOptions.cs
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@
using Microsoft.AspNetCore.Http;
using Serilog.Events;
using System;
using System.Collections.Generic;

// ReSharper disable UnusedAutoPropertyAccessor.Global

@@ -34,6 +35,15 @@ static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
: ctx.Response.StatusCode > 499
? LogEventLevel.Error
: LogEventLevel.Information;

IEnumerable<LogEventProperty> DefaultGetMessageTemplateProperties(HttpContext httpContext, string requestPath, double elapsedMs, int statusCode) =>
new[]
{
new LogEventProperty("RequestMethod", new ScalarValue(httpContext.Request.Method)),
new LogEventProperty("RequestPath", new ScalarValue(requestPath)),
new LogEventProperty("StatusCode", new ScalarValue(statusCode)),
new LogEventProperty("Elapsed", new ScalarValue(elapsedMs))
};

/// <summary>
/// Gets or sets the message template. The default value is
@@ -74,13 +84,19 @@ static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
/// </summary>
public bool IncludeQueryInRequestPath { get; set; }

/// <summary>
/// A function to specify the values of the MessageTemplateProperties.
/// </summary>
public Func<HttpContext, string, double, int, IEnumerable<LogEventProperty>> GetMessageTemplateProperties { get; set; }

/// <summary>
/// Constructor
/// </summary>
public RequestLoggingOptions()
{
GetLevel = DefaultGetLevel;
MessageTemplate = DefaultRequestCompletionMessageTemplate;
GetMessageTemplateProperties = DefaultGetMessageTemplateProperties;
}
}
}
Original file line number Diff line number Diff line change
@@ -12,6 +12,8 @@
using Microsoft.AspNetCore.Http;
using Serilog.Filters;
using Serilog.AspNetCore.Tests.Support;
using Serilog.Events;
using System.Net.Http;

// Newer frameworks provide IHostBuilder
#pragma warning disable CS0618
@@ -66,6 +68,34 @@ public async Task RequestLoggingMiddlewareShouldEnrich()
Assert.True(completionEvent.Properties.ContainsKey("Elapsed"));
}

[Fact]
public async Task RequestLoggingMiddlewareShouldEnrichWithCustomisedProperties()
{
var (sink, web) = Setup(options =>
{
options.MessageTemplate = "HTTP {RequestMethod} responded {Status} in {ElapsedMilliseconds:0.0000} ms";
options.GetMessageTemplateProperties = (ctx, path, elapsedMs, status) =>
new[]
{
new LogEventProperty("RequestMethod", new ScalarValue(ctx.Request.Method)),
new LogEventProperty("Status", new ScalarValue(status)),
new LogEventProperty("ElapsedMilliseconds", new ScalarValue(elapsedMs))
};
});

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

Assert.NotEmpty(sink.Writes);

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

Assert.Equal("string", completionEvent.Properties["SomeString"].LiteralValue());
Assert.Equal(200, completionEvent.Properties["Status"].LiteralValue());
Assert.Equal("GET", completionEvent.Properties["RequestMethod"].LiteralValue());
Assert.True(completionEvent.Properties.ContainsKey("ElapsedMilliseconds"));
Assert.False(completionEvent.Properties.ContainsKey("Elapsed"));
}

[Fact]
public async Task RequestLoggingMiddlewareShouldEnrichWithCollectedExceptionIfNoUnhandledException()
{