Skip to content

3.0.0 Release #99

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 45 commits into from
Aug 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
0d2d6d0
Dev version bump [Skip CI]
nblumhardt Mar 7, 2018
7c91749
Add Azure Diagnostic Logs Streaming example [Skip CI]
nblumhardt Mar 14, 2018
98ed489
New NuGet API Key
merbla May 9, 2018
93c5d76
Added information about the Serilog.Settings.Configuration package
patriksvensson Jul 18, 2018
c4141cc
Merge pull request #56 from patriksvensson/patch-1
nblumhardt Jul 19, 2018
44c811d
fixing repository url
MaximRouiller Sep 21, 2018
a2c1d9c
Merge pull request #66 from MaximRouiller/repositoryurl
nblumhardt Sep 22, 2018
945289f
Integrate with LoggerProviderCollection
nblumhardt May 22, 2019
fb0d872
README, new samples based on the default netcoreapp2.2 template
nblumhardt May 23, 2019
aa1c0c3
README formatting
nblumhardt May 28, 2019
d41c8e7
Tabs to spaces
nblumhardt Jun 3, 2019
a04cbb2
Merge pull request #87 from serilog/add-providers
nblumhardt Jun 3, 2019
ce31a0d
New NuGet.org API key... again.
nblumhardt Jun 3, 2019
316f7e1
Update to initial configuration pattern
pmorong Jun 4, 2019
27ba52d
Merge pull request #90 from pmorong/patch-1
nblumhardt Jun 5, 2019
2e63ca9
Fix flipped conditional introduced in earlier provider support PR
nblumhardt Jun 23, 2019
4c826df
Merge pull request #93 from serilog/fix-flipped-conditional
nblumhardt Jun 23, 2019
206c627
UseSerilogRequestLogging()
nblumhardt Jun 24, 2019
df5bf0d
Allow configuration of the completion message template
nblumhardt Jun 25, 2019
81af9a7
Merge pull request #94 from serilog/request-completion-middleware
nblumhardt Jun 25, 2019
a64500c
Add `using Serilog;` - resolves #89
nblumhardt Jun 25, 2019
be446d4
README and dependency updates
nblumhardt Jun 26, 2019
fff0984
Larger clickable link
nblumhardt Jun 26, 2019
40672d3
Merge pull request #96 from serilog/readme-deps
nblumhardt Jun 26, 2019
380a0ed
Ick, how did those tabs get in there?!
nblumhardt Jun 26, 2019
bed8daf
JSON formatting [skip ci]
nblumhardt Jun 26, 2019
90452d9
Note required version for request logging features
nblumhardt Jul 19, 2019
30d47f7
Rename file to match type name; fixes #101
nblumhardt Aug 16, 2019
e68cf8d
Include Debug sink and note this in README; includes console, file, a…
nblumhardt Aug 16, 2019
16d1ca9
Describe how to write JSON output
nblumhardt Aug 16, 2019
5d49fee
Show dev branch build status, since failing PRs are misleading in ove…
nblumhardt Aug 19, 2019
b72f844
move to PackageLicenseExpression
SimonCropp Aug 20, 2019
4ca37ef
remove PackageId and AssemblyName
SimonCropp Aug 20, 2019
cffbc50
update test and sampel refs
SimonCropp Aug 20, 2019
f254ecd
remove some redundant usings
SimonCropp Aug 20, 2019
74a2dda
Merge pull request #114 from SimonCropp/licenseExpression
nblumhardt Aug 20, 2019
f8818b1
Merge pull request #115 from SimonCropp/redundantNames
nblumhardt Aug 20, 2019
73210e6
Merge pull request #116 from SimonCropp/updateSampleAndTestRefs
nblumhardt Aug 20, 2019
6940b8e
Merge pull request #117 from SimonCropp/someRedundantUsings
nblumhardt Aug 20, 2019
c1dc221
remove Serilog.Extensions.Logging
SimonCropp Aug 21, 2019
b30822e
Merge pull request #118 from SimonCropp/removeSerilogExtensionsLogging
nblumhardt Aug 21, 2019
bcc787a
Merge pull request #109 from serilog/batteries-included
nblumhardt Aug 21, 2019
97c84ca
Update to Serilog.Extensions.Hosting v3.0.0
nblumhardt Aug 27, 2019
f2de594
Merge branch 'dev' into batteries-included-2
nblumhardt Aug 27, 2019
618600a
Merge pull request #110 from serilog/batteries-included-2
nblumhardt Aug 27, 2019
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
206 changes: 175 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
# Serilog.AspNetCore [![Build status](https://ci.appveyor.com/api/projects/status/4rscdto23ik6vm2r?svg=true)](https://ci.appveyor.com/project/serilog/serilog-aspnetcore) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.AspNetCore.svg?style=flat)](https://www.nuget.org/packages/Serilog.AspNetCore/)
# Serilog.AspNetCore [![Build status](https://ci.appveyor.com/api/projects/status/4rscdto23ik6vm2r/branch/dev?svg=true)](https://ci.appveyor.com/project/serilog/serilog-aspnetcore/branch/dev) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.AspNetCore.svg?style=flat)](https://www.nuget.org/packages/Serilog.AspNetCore/) [![NuGet Prerelease Version](http://img.shields.io/nuget/vpre/Serilog.AspNetCore.svg?style=flat)](https://www.nuget.org/packages/Serilog.AspNetCore/)

Serilog logging for ASP.NET Core. This package routes ASP.NET Core log messages through Serilog, so you can get information about ASP.NET's internal operations written to the same Serilog sinks as your application events.

Serilog logging for ASP.NET Core. This package routes ASP.NET Core log messages through Serilog, so you can get information about ASP.NET's internal operations logged to the same Serilog sinks as your application events.
With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.

### Instructions

**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app. You will need a way to view the log messages - _Serilog.Sinks.Console_ writes these to the console; there are [many more sinks available](https://www.nuget.org/packages?q=Tags%3A%22serilog%22) on NuGet.
**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app.

```powershell
Install-Package Serilog.AspNetCore -DependencyVersion Highest
Install-Package Serilog.Sinks.Console
```shell
dotnet add package Serilog.AspNetCore
```

**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged:

```csharp
using Serilog;

public class Program
{
public static int Main(string[] args)
Expand All @@ -29,7 +31,7 @@ public class Program
try
{
Log.Information("Starting web host");
BuildWebHost(args).Run();
CreateWebHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
Expand All @@ -46,59 +48,201 @@ public class Program

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

```csharp
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog() // <-- Add this line
.Build();
```csharp
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(); // <-- Add this line;
}
```

**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 [this example](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/SimpleWebSample/Program.cs), if required)
* 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 like:
That's it! With the level bumped up a little you will see log output resembling:

```
[22:14:44.646 DBG] RouteCollection.RouteAsync
Routes:
Microsoft.AspNet.Mvc.Routing.AttributeRoute
{controller=Home}/{action=Index}/{id?}
Handled? True
Routes:
Microsoft.AspNet.Mvc.Routing.AttributeRoute
{controller=Home}/{action=Index}/{id?}
Handled? True
[22:14:44.647 DBG] RouterMiddleware.Invoke
Handled? True
Handled? True
[22:14:45.706 DBG] /lib/jquery/jquery.js not modified
[22:14:45.706 DBG] /css/site.css not modified
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css
```

Tip: to see Serilog output in the Visual Studio output window when running under IIS, select _ASP.NET Core Web Server_ from the _Show output from_ drop-down list.
**Tip:** to see Serilog output in the Visual Studio output window when running under IIS, either select _ASP.NET Core Web Server_ from the _Show output from_ drop-down list, or replace `WriteTo.Console()` in the logger configuration with `WriteTo.Debug()`.

A more complete example, showing _appsettings.json_ configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/SimpleWebSample).
A more complete example, showing `appsettings.json` configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/EarlyInitializationSample).

### Using the package
### Request logging <sup>`3.0.0-*`</sup>

With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.
The package includes middleware for smarter HTTP request logging. The default request logging implemented by ASP.NET Core is noisy, with multiple events emitted per request. The included middleware condenses these into a single event that carries method, path, status code, and timing information.

As text, this has a format like:

```
[16:05:54 INF] HTTP GET / responded 200 in 227.3253 ms
```

Or [as JSON](https://github.com/serilog/serilog-formatting-compact):

```json
{
"@t": "2019-06-26T06:05:54.6881162Z",
"@mt": "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms",
"@r": ["224.5185"],
"RequestMethod": "GET",
"RequestPath": "/",
"StatusCode": 200,
"Elapsed": 224.5185,
"RequestId": "0HLNPVG1HI42T:00000001",
"CorrelationId": null,
"ConnectionId": "0HLNPVG1HI42T"
}
```

To enable the middleware, first change the minimum level for `Microsoft` to `Warning` in your logger configuration or _appsettings.json_ file:

```csharp
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
```

Then, in your application's _Startup.cs_, add the middleware with `UseSerilogRequestLogging()`:

```csharp
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseSerilogRequestLogging(); // <-- Add this line
// Other app configuration
```

It's important that the `UseSerilogRequestLogging()` call appears _before_ handlers such as MVC. The middleware will not time or log components that appear before it in the pipeline. (This can be utilized to exclude noisy handlers from logging, such as `UseStaticFiles()`, by placing `UseSerilogRequestLogging()` after them.)

During request processing, additional properties can be attached to the completion event using `IDiagnosticContext.Set()`:

```csharp
public class HomeController : Controller
{
readonly IDiagnosticContext _diagnosticContext;

**Tip:** change the minimum level for `Microsoft` to `Warning` and plug in this [custom logging middleware](https://github.com/datalust/serilog-middleware-example/blob/master/src/Datalust.SerilogMiddlewareExample/Diagnostics/SerilogMiddleware.cs) to clean up request logging output and record more context around errors and exceptions.
public HomeController(IDiagnosticContext diagnosticContext)
{
_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
}

public IActionResult Index()
{
// The request completion event will carry this property
_diagnosticContext.Set("CatalogLoadTime", 1423);

return View();
}
```

This pattern has the advantage of reducing the number of log events that need to be constructed, transmitted, and stored per HTTP request. Having many properties on the same event can also make correlation of request details and other data easier.

### Inline initialization

You can alternatively configure Serilog using a delegate as shown below:
You can alternatively configure Serilog inline, in `BuildWebHost()`, using a delegate as shown below:

```csharp
// dotnet add package Serilog.Settings.Configuration
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console())
.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, but at the expense of recording `Exception`s raised earlier in program startup.
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.

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

A complete example, showing this approach, can be found in [the _InlineIntializationSample_ project](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/InlineInitializationSample).
### Enabling `Microsoft.Extensions.Logging.ILoggerProvider`s <sup>`3.0.0-*`</sup>

Serilog sends events to outputs called _sinks_, that implement Serilog's `ILogEventSink` interface, and are added to the logging pipeline using `WriteTo`. _Microsoft.Extensions.Logging_ has a similar concept called _providers_, and these implement `ILoggerProvider`. Providers are what the default logging configuration creates under the hood through methods like `AddConsole()`.

By default, Serilog ignores providers, since there are usually equivalent Serilog sinks available, and these work more efficiently with Serilog's pipeline. If provider support is needed, it can be optionally enabled.

**Using the recommended configuration:**

In the recommended configuration (in which startup exceptions are caught and logged), first create a `LoggerProviderCollection` in a static field in _Program.cs_:

```csharp
// using Serilog.Extensions.Logging;
static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();
```

Next, add `WriteTo.Providers()` to the logger configuration:

```csharp
.WriteTo.Providers(Providers)
```

Finally, pass the provider collection into `UseSerilog()`:

```csharp
.UseSerilog(providers: Providers)
```

Providers registered in _Startup.cs_ with `AddLogging()` will then receive events from Serilog.

**Using iniline initialization:**

If [inline initialization](#inline-initialization) is used, providers can be enabled by adding `writeToProviders: true` to the `UseSerilog()` method call:

```csharp
.UseSerilog(
(hostingContext, loggerConfiguration) => /* snip! */,
writeToProviders: true)
```

### JSON output

The `Console()`, `Debug()`, and `File()` sinks all support JSON-formatted output natively, via the included _Serilog.Formatting.Compact_ package.

To write newline-delimited JSON, pass a `CompactJsonFormatter` or `RenderedCompactJsonFormatter` to the sink configuration method:

```csharp
.WriteTo.Console(new RenderedCompactJsonFormatter())
```

### Writing to the Azure Diagnostics Log Stream

The Azure Diagnostic Log Stream ships events from any files in the `D:\home\LogFiles\` folder. To enable this for your app, add a file sink to your `LoggerConfiguration`, taking care to set the `shared` and `flushToDiskInterval` parameters:

```csharp
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
// Add this line:
.WriteTo.File(
@"D:\home\LogFiles\Application\myapp.txt",
fileSizeLimitBytes: 1_000_000,
rollOnFileSizeLimit: true,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(1))
.CreateLogger();
```
9 changes: 2 additions & 7 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
version: '{build}'
skip_tags: true
image: Visual Studio 2017 Preview
configuration: Release
image: Visual Studio 2017
install:
- ps: mkdir -Force ".\build\" | Out-Null
#- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/release/2.0.0/scripts/obtain/dotnet-install.ps1" -OutFile ".\build\installcli.ps1"
#- ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli"
#- ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 2.0.0-preview2-006497'
#- ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path"
build_script:
- ps: ./Build.ps1
test: off
Expand All @@ -16,7 +11,7 @@ artifacts:
deploy:
- provider: NuGet
api_key:
secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x
secure: gvYNwOSxj9Bq4erOm7alpWzHlEmNLLUV99VYKV1WF9qTJeDkvYpswoNHi9sAlZH4
skip_symbols: true
on:
branch: /^(master|dev)$/
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"sdk": {
"version": "2.0.0"
"version": "2.2.105"
}
}
44 changes: 44 additions & 0 deletions samples/EarlyInitializationSample/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using EarlyInitializationSample.Models;
using Microsoft.Extensions.Logging;
using Serilog;

namespace EarlyInitializationSample.Controllers
{
public class HomeController : Controller
{
static int _callCount;

readonly ILogger<HomeController> _logger;
readonly IDiagnosticContext _diagnosticContext;

public HomeController(ILogger<HomeController> logger, IDiagnosticContext diagnosticContext)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
}

public IActionResult Index()
{
_logger.LogInformation("Hello, world!");

_diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));

return View();
}

public IActionResult Privacy()
{
throw new InvalidOperationException("Something went wrong.");
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
17 changes: 17 additions & 0 deletions samples/EarlyInitializationSample/EarlyInitializationSample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions samples/EarlyInitializationSample/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace EarlyInitializationSample.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
Loading