Skip to content

Commit

Permalink
Merge pull request #202 from serilog/dev
Browse files Browse the repository at this point in the history
3.4.0 Release
  • Loading branch information
nblumhardt authored Jul 24, 2020
2 parents 210a242 + d05c38c commit 16be480
Show file tree
Hide file tree
Showing 19 changed files with 295 additions and 62 deletions.
27 changes: 27 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
name: Bug report
about: Report a bug and help us to improve Serilog
title: ''
labels: bug
assignees: ''

---

The Serilog maintainers want you to have a great experience using Serilog, and will happily track down and resolve bugs. We all have limited time, though, so please think through all of the factors that might be involved and include as much useful information as possible 😊.

ℹ If the problem is caused by a sink or other related package, please try to track down the correct repository for that package and create the report there: this tracker is for the **Serilog.AspNetCore** package only.

**Description**
What's going wrong?

**Reproduction**
Please provide code samples showing how you're configuring and calling Serilog to produce the behavior.

**Expected behavior**
A concise description of what you expected to happen.

**Relevant package, tooling and runtime versions**
What Serilog version are you using, on what platform?

**Additional context**
Add any other context about the problem here.
20 changes: 20 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an improvement to Serilog
title: ''
labels: enhancement
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
16 changes: 16 additions & 0 deletions .github/ISSUE_TEMPLATE/usage-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
name: Usage help
about: Get help with using Serilog
title: ''
labels: invalid
assignees: ''

---

Hi! 👋

The Serilog community wants you to have a great experience using Serilog. Unfortunately, only a handful of maintainers actively follow this repository, and our time is short, so we cannot answer usage questions posted here.

Fortunately, a much larger group of people (including some of us) also watch and answer questions on the [`serilog` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/serilog).

Please head over to Stack Overflow, ask your question, and tag it with `serilog`. Thanks! ❤
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class Program
try
{
Log.Information("Starting web host");
CreateWebHostBuilder(args).Build().Run();
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
Expand All @@ -46,21 +46,22 @@ public class Program
}
```

**Then**, add `UseSerilog()` to the web host builder in `BuildWebHost()`.
**Then**, add `UseSerilog()` to the Generic Host in `CreateHostBuilder()`.

```csharp
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(); // <-- Add this line;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog() // <-- Add this line
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
```

**Finally**, clean up by removing the remaining configuration for the default logger:

* Remove calls to `AddLogging()`
* Remove the `"Logging"` section from _appsettings.json_ files (this can be replaced with [Serilog configuration](https://github.com/serilog/serilog-settings-configuration) as shown in [the _EarlyInitializationSample_ project](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/EarlyInitializationSample/Program.cs), if required)
* Remove `ILoggerFactory` parameters and any `Add*()` calls on the logger factory in _Startup.cs_
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)

That's it! With the level bumped up a little you will see log output resembling:
Expand Down Expand Up @@ -191,13 +192,13 @@ app.UseSerilogRequestLogging(options =>
You can alternatively configure Serilog inline, in `BuildWebHost()`, using a delegate as shown below:

```csharp
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console())
```

This has the advantage of making the `hostingContext`'s `Configuration` object available for [configuration of the logger](https://github.com/serilog/serilog-settings-configuration), but at the expense of losing `Exception`s raised earlier in program startup.
This has the advantage of making a service provider and the `hostingContext`'s `Configuration` object available for [configuration of the logger](https://github.com/serilog/serilog-settings-configuration), but at the expense of losing `Exception`s raised earlier in program startup.

If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.

Expand Down
6 changes: 3 additions & 3 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
version: '{build}'
skip_tags: true
image: Visual Studio 2017
image: Visual Studio 2019
install:
- ps: ./Setup.ps1
build_script:
Expand All @@ -10,9 +10,9 @@ artifacts:
- path: artifacts/Serilog.*.nupkg
deploy:
- provider: NuGet
api_key:
secure: gvYNwOSxj9Bq4erOm7alpWzHlEmNLLUV99VYKV1WF9qTJeDkvYpswoNHi9sAlZH4
skip_symbols: true
api_key:
secure: jZtLAmD4ALF9x1BZR1DiV3KhKlliWbzRUAw73xfMZaBsvz19123qLz2zw1+hPdcn
on:
branch: /^(master|dev)$/
- provider: GitHub
Expand Down
6 changes: 4 additions & 2 deletions global.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"sdk": {
"version": "3.0.100"
"allowPrerelease": false,
"version": "3.1.201",
"rollForward": "latestFeature"
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
7 changes: 2 additions & 5 deletions samples/InlineInitializationSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@ public static void Main(string[] args)

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Debug()
Expand Down
11 changes: 9 additions & 2 deletions samples/InlineInitializationSample/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
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
18 changes: 16 additions & 2 deletions src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@

namespace Serilog.AspNetCore
{
// ReSharper disable once ClassNeverInstantiated.Global
class RequestLoggingMiddleware
{
readonly RequestDelegate _next;
readonly DiagnosticContext _diagnosticContext;
readonly MessageTemplate _messageTemplate;
readonly Action<IDiagnosticContext, HttpContext> _enrichDiagnosticContext;
readonly Func<HttpContext, double, Exception, LogEventLevel> _getLevel;
readonly ILogger _logger;
static readonly LogEventProperty[] NoProperties = new LogEventProperty[0];

public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnosticContext, RequestLoggingOptions options)
Expand All @@ -42,6 +44,7 @@ public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnost
_getLevel = options.GetLevel;
_enrichDiagnosticContext = options.EnrichDiagnosticContext;
_messageTemplate = new MessageTemplateParser().Parse(options.MessageTemplate);
_logger = options.Logger?.ForContext<RequestLoggingMiddleware>();
}

// ReSharper disable once UnusedMember.Global
Expand Down Expand Up @@ -73,7 +76,7 @@ public async Task Invoke(HttpContext httpContext)

bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector, int statusCode, double elapsedMs, Exception ex)
{
var logger = Log.ForContext<RequestLoggingMiddleware>();
var logger = _logger ?? Log.ForContext<RequestLoggingMiddleware>();
var level = _getLevel(httpContext, elapsedMs, ex);

if (!logger.IsEnabled(level)) return false;
Expand Down Expand Up @@ -106,7 +109,18 @@ static double GetElapsedMilliseconds(long start, long stop)

static string GetPath(HttpContext httpContext)
{
return httpContext.Features.Get<IHttpRequestFeature>()?.RawTarget ?? httpContext.Request.Path.ToString();
/*
In some cases, like when running integration tests with WebApplicationFactory<T>
the RawTarget returns an empty string instead of null, in that case we can't use
?? as fallback.
*/
var requestPath = httpContext.Features.Get<IHttpRequestFeature>()?.RawTarget;
if (string.IsNullOrEmpty(requestPath))
{
requestPath = httpContext.Request.Path.ToString();
}

return requestPath;
}
}
}
31 changes: 28 additions & 3 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 @@ -16,13 +16,25 @@
using Serilog.Events;
using System;

// ReSharper disable UnusedAutoPropertyAccessor.Global

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 @@ -50,6 +62,19 @@ public class RequestLoggingOptions
/// </summary>
public Action<IDiagnosticContext, HttpContext> EnrichDiagnosticContext { get; set; }

internal RequestLoggingOptions() { }
/// <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; }

/// <summary>
/// Constructor
/// </summary>
public RequestLoggingOptions()
{
GetLevel = DefaultGetLevel;
MessageTemplate = DefaultRequestCompletionMessageTemplate;
}
}
}
33 changes: 24 additions & 9 deletions src/Serilog.AspNetCore/Serilog.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

<PropertyGroup>
<Description>Serilog support for ASP.NET Core logging</Description>
<VersionPrefix>3.2.0</VersionPrefix>
<VersionPrefix>3.4.0</VersionPrefix>
<Authors>Microsoft;Serilog Contributors</Authors>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;netcoreapp3.1</TargetFrameworks>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyOriginatorKeyFile>../../assets/Serilog.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageTags>serilog;aspnet;aspnetcore</PackageTags>
<PackageIcon>serilog-extension-nuget.png</PackageIcon>
<PackageIconUrl>https://serilog.net/images/serilog-extension-nuget.png</PackageIconUrl>
<PackageProjectUrl>https://github.com/serilog/serilog-aspnetcore</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
Expand All @@ -21,16 +22,30 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.8.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="3.0.0" />
<None Include="images/serilog-extension-nuget.png" Pack="true" PackagePath="/" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="1.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.1" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.2" />
</ItemGroup>

</Project>
Loading

0 comments on commit 16be480

Please sign in to comment.