Skip to content

Allow RequestLoggingOptions configuration outside of Configure(IApplicationBuilder) #197

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

Merged
merged 1 commit into from
Jun 18, 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
9 changes: 9 additions & 0 deletions samples/InlineInitializationSample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.AspNetCore;

namespace InlineInitializationSample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLoggingOptions>(o =>
{
o.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress.MapToIPv4());
};
});

services.AddControllersWithViews();
}

Expand Down
24 changes: 20 additions & 4 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingOptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2019 Serilog Contributors
// Copyright 2019-2020 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -21,10 +21,20 @@
namespace Serilog.AspNetCore
{
/// <summary>
/// Contains options for the <see cref="Serilog.AspNetCore.RequestLoggingMiddleware"/>.
/// Contains options for the <see cref="RequestLoggingMiddleware"/>.
/// </summary>
public class RequestLoggingOptions
{
const string DefaultRequestCompletionMessageTemplate =
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";

static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
ex != null
? LogEventLevel.Error
: ctx.Response.StatusCode > 499
? LogEventLevel.Error
: LogEventLevel.Information;

/// <summary>
/// Gets or sets the message template. The default value is
/// <c>"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms"</c>. The
Expand Down Expand Up @@ -52,13 +62,19 @@ public class RequestLoggingOptions
/// </summary>
public Action<IDiagnosticContext, HttpContext> EnrichDiagnosticContext { get; set; }


/// <summary>
/// The logger through which request completion events will be logged. The default is to use the
/// static <see cref="Log"/> class.
/// </summary>
public ILogger Logger { get; set; }

internal RequestLoggingOptions() { }
/// <summary>
/// Constructor
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

)

/// </summary>
public RequestLoggingOptions()
{
GetLevel = DefaultGetLevel;
MessageTemplate = DefaultRequestCompletionMessageTemplate;
}
}
}
27 changes: 8 additions & 19 deletions src/Serilog.AspNetCore/SerilogApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2019 Serilog Contributors
// Copyright 2019-2020 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -13,10 +13,12 @@
// limitations under the License.

using System;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Serilog.AspNetCore;
using Serilog.Events;

namespace Serilog
{
Expand All @@ -25,16 +27,6 @@ namespace Serilog
/// </summary>
public static class SerilogApplicationBuilderExtensions
{
const string DefaultRequestCompletionMessageTemplate =
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";

static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
ex != null
? LogEventLevel.Error
: ctx.Response.StatusCode > 499
? LogEventLevel.Error
: LogEventLevel.Information;

/// <summary>
/// Adds middleware for streamlined request logging. Instead of writing HTTP request information
/// like method, path, timing, status code and exception details
Expand Down Expand Up @@ -70,12 +62,9 @@ public static IApplicationBuilder UseSerilogRequestLogging(
Action<RequestLoggingOptions> configureOptions = null)
Copy link
Contributor

@sungam3r sungam3r Jul 8, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This parameter seems (a bit) redundant now.

{
if (app == null) throw new ArgumentNullException(nameof(app));

var opts = new RequestLoggingOptions
{
GetLevel = DefaultGetLevel,
MessageTemplate = DefaultRequestCompletionMessageTemplate
};

var opts = app.ApplicationServices.GetService<IOptions<RequestLoggingOptions>>()?.Value ?? new RequestLoggingOptions();

configureOptions?.Invoke(opts);

if (opts.MessageTemplate == null)
Expand Down
12 changes: 10 additions & 2 deletions test/Serilog.AspNetCore.Tests/Serilog.AspNetCore.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,17 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.2" PrivateAssets="All" />
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.5" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.1'">
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.1.3" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,16 +1,103 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading.Tasks;

using Xunit;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Builder;

using Serilog.Filters;
using Serilog.AspNetCore.Tests.Support;

namespace Serilog.AspNetCore.Tests
{
public class SerilogWebHostBuilderExtensionsTests
public class SerilogWebHostBuilderExtensionsTests : IClassFixture<SerilogWebApplicationFactory>
{
SerilogWebApplicationFactory _web;

public SerilogWebHostBuilderExtensionsTests(SerilogWebApplicationFactory web)
{
_web = web;
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task DisposeShouldBeHandled(bool dispose)
{
var logger = new DisposeTrackingLogger();
using (var web = Setup(logger, dispose))
{
await web.CreateClient().GetAsync("/");
}

Assert.Equal(dispose, logger.IsDisposed);
}

[Fact]
public void Todo()
public async Task RequestLoggingMiddlewareShouldEnrich()
{
var (sink, web) = Setup(options =>
{
options.EnrichDiagnosticContext += (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("SomeInteger", 42);
};
});

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

Assert.NotEmpty(sink.Writes);

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

Assert.Equal(42, completionEvent.Properties["SomeInteger"].LiteralValue());
Assert.Equal("string", completionEvent.Properties["SomeString"].LiteralValue());
Assert.Equal("/resource", completionEvent.Properties["RequestPath"].LiteralValue());
Assert.Equal(200, completionEvent.Properties["StatusCode"].LiteralValue());
Assert.Equal("GET", completionEvent.Properties["RequestMethod"].LiteralValue());
Assert.True(completionEvent.Properties.ContainsKey("Elapsed"));
}

WebApplicationFactory<TestStartup> Setup(ILogger logger, bool dispose, Action<RequestLoggingOptions> configureOptions = null)
{
var web = _web.WithWebHostBuilder(
builder => builder
.ConfigureServices(sc => sc.Configure<RequestLoggingOptions>(options =>
{
options.Logger = logger;
options.EnrichDiagnosticContext += (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("SomeString", "string");
};
}))
.Configure(app =>
{
app.UseSerilogRequestLogging(configureOptions);
app.Run(_ => Task.CompletedTask); // 200 OK
})
.UseSerilog(logger, dispose));

return web;
}

(SerilogSink, WebApplicationFactory<TestStartup>) Setup(Action<RequestLoggingOptions> configureOptions = null)
{
var sink = new SerilogSink();
var logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Sink(sink)
.CreateLogger();

var web = Setup(logger, true, configureOptions);

return (sink, web);
}
}
}
12 changes: 12 additions & 0 deletions test/Serilog.AspNetCore.Tests/Support/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Serilog.Events;

namespace Serilog.AspNetCore.Tests.Support
{
public static class Extensions
{
public static object LiteralValue(this LogEventPropertyValue @this)
{
return ((ScalarValue)@this).Value;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Serilog.AspNetCore.Tests.Support
{
public class SerilogWebApplicationFactory : WebApplicationFactory<TestStartup>
{
protected override IWebHostBuilder CreateWebHostBuilder() => new WebHostBuilder().UseStartup<TestStartup>();
protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.UseContentRoot(".");
}

public class TestStartup { }
}