Skip to content

Commit a5c738a

Browse files
authored
Merge pull request #99 from serilog/dev
3.0.0 Release
2 parents 5fb585d + 618600a commit a5c738a

File tree

118 files changed

+79759
-195
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

118 files changed

+79759
-195
lines changed

README.md

+175-31
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
1-
# 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/)
1+
# 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/)
22

3+
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.
34

4-
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.
5+
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.
56

67
### Instructions
78

8-
**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.
9+
**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app.
910

10-
```powershell
11-
Install-Package Serilog.AspNetCore -DependencyVersion Highest
12-
Install-Package Serilog.Sinks.Console
11+
```shell
12+
dotnet add package Serilog.AspNetCore
1313
```
1414

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

1717
```csharp
18+
using Serilog;
19+
1820
public class Program
1921
{
2022
public static int Main(string[] args)
@@ -29,7 +31,7 @@ public class Program
2931
try
3032
{
3133
Log.Information("Starting web host");
32-
BuildWebHost(args).Run();
34+
CreateWebHostBuilder(args).Build().Run();
3335
return 0;
3436
}
3537
catch (Exception ex)
@@ -46,59 +48,201 @@ public class Program
4648

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

49-
```csharp
50-
public static IWebHost BuildWebHost(string[] args) =>
51-
WebHost.CreateDefaultBuilder(args)
52-
.UseStartup<Startup>()
53-
.UseSerilog() // <-- Add this line
54-
.Build();
51+
```csharp
52+
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
53+
WebHost.CreateDefaultBuilder(args)
54+
.UseStartup<Startup>()
55+
.UseSerilog(); // <-- Add this line;
5556
}
5657
```
5758

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

6061
* Remove calls to `AddLogging()`
61-
* 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)
62+
* 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)
6263
* Remove `ILoggerFactory` parameters and any `Add*()` calls on the logger factory in _Startup.cs_
6364
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)
6465

65-
That's it! With the level bumped up a little you will see log output like:
66+
That's it! With the level bumped up a little you will see log output resembling:
6667

6768
```
6869
[22:14:44.646 DBG] RouteCollection.RouteAsync
69-
Routes:
70-
Microsoft.AspNet.Mvc.Routing.AttributeRoute
71-
{controller=Home}/{action=Index}/{id?}
72-
Handled? True
70+
Routes:
71+
Microsoft.AspNet.Mvc.Routing.AttributeRoute
72+
{controller=Home}/{action=Index}/{id?}
73+
Handled? True
7374
[22:14:44.647 DBG] RouterMiddleware.Invoke
74-
Handled? True
75+
Handled? True
7576
[22:14:45.706 DBG] /lib/jquery/jquery.js not modified
7677
[22:14:45.706 DBG] /css/site.css not modified
7778
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css
7879
```
7980

80-
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.
81+
**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()`.
8182

82-
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).
83+
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).
8384

84-
### Using the package
85+
### Request logging <sup>`3.0.0-*`</sup>
8586

86-
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.
87+
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.
88+
89+
As text, this has a format like:
90+
91+
```
92+
[16:05:54 INF] HTTP GET / responded 200 in 227.3253 ms
93+
```
94+
95+
Or [as JSON](https://github.com/serilog/serilog-formatting-compact):
96+
97+
```json
98+
{
99+
"@t": "2019-06-26T06:05:54.6881162Z",
100+
"@mt": "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms",
101+
"@r": ["224.5185"],
102+
"RequestMethod": "GET",
103+
"RequestPath": "/",
104+
"StatusCode": 200,
105+
"Elapsed": 224.5185,
106+
"RequestId": "0HLNPVG1HI42T:00000001",
107+
"CorrelationId": null,
108+
"ConnectionId": "0HLNPVG1HI42T"
109+
}
110+
```
111+
112+
To enable the middleware, first change the minimum level for `Microsoft` to `Warning` in your logger configuration or _appsettings.json_ file:
113+
114+
```csharp
115+
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
116+
```
117+
118+
Then, in your application's _Startup.cs_, add the middleware with `UseSerilogRequestLogging()`:
119+
120+
```csharp
121+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
122+
{
123+
if (env.IsDevelopment())
124+
{
125+
app.UseDeveloperExceptionPage();
126+
}
127+
else
128+
{
129+
app.UseExceptionHandler("/Home/Error");
130+
}
131+
132+
app.UseSerilogRequestLogging(); // <-- Add this line
133+
134+
// Other app configuration
135+
```
136+
137+
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.)
138+
139+
During request processing, additional properties can be attached to the completion event using `IDiagnosticContext.Set()`:
140+
141+
```csharp
142+
public class HomeController : Controller
143+
{
144+
readonly IDiagnosticContext _diagnosticContext;
87145

88-
**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.
146+
public HomeController(IDiagnosticContext diagnosticContext)
147+
{
148+
_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
149+
}
150+
151+
public IActionResult Index()
152+
{
153+
// The request completion event will carry this property
154+
_diagnosticContext.Set("CatalogLoadTime", 1423);
155+
156+
return View();
157+
}
158+
```
159+
160+
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.
89161

90162
### Inline initialization
91163

92-
You can alternatively configure Serilog using a delegate as shown below:
164+
You can alternatively configure Serilog inline, in `BuildWebHost()`, using a delegate as shown below:
93165

94166
```csharp
95-
// dotnet add package Serilog.Settings.Configuration
96167
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
97-
.ReadFrom.Configuration(hostingContext.Configuration)
98-
.Enrich.FromLogContext()
99-
.WriteTo.Console())
168+
.ReadFrom.Configuration(hostingContext.Configuration)
169+
.Enrich.FromLogContext()
170+
.WriteTo.Console())
100171
```
101172

102-
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.
173+
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.
103174

104175
If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.
176+
177+
A complete example, showing this approach, can be found in [the _InlineIntializationSample_ project](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/InlineInitializationSample).
178+
179+
### Enabling `Microsoft.Extensions.Logging.ILoggerProvider`s <sup>`3.0.0-*`</sup>
180+
181+
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()`.
182+
183+
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.
184+
185+
**Using the recommended configuration:**
186+
187+
In the recommended configuration (in which startup exceptions are caught and logged), first create a `LoggerProviderCollection` in a static field in _Program.cs_:
188+
189+
```csharp
190+
// using Serilog.Extensions.Logging;
191+
static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();
192+
```
193+
194+
Next, add `WriteTo.Providers()` to the logger configuration:
195+
196+
```csharp
197+
.WriteTo.Providers(Providers)
198+
```
199+
200+
Finally, pass the provider collection into `UseSerilog()`:
201+
202+
```csharp
203+
.UseSerilog(providers: Providers)
204+
```
205+
206+
Providers registered in _Startup.cs_ with `AddLogging()` will then receive events from Serilog.
207+
208+
**Using iniline initialization:**
209+
210+
If [inline initialization](#inline-initialization) is used, providers can be enabled by adding `writeToProviders: true` to the `UseSerilog()` method call:
211+
212+
```csharp
213+
.UseSerilog(
214+
(hostingContext, loggerConfiguration) => /* snip! */,
215+
writeToProviders: true)
216+
```
217+
218+
### JSON output
219+
220+
The `Console()`, `Debug()`, and `File()` sinks all support JSON-formatted output natively, via the included _Serilog.Formatting.Compact_ package.
221+
222+
To write newline-delimited JSON, pass a `CompactJsonFormatter` or `RenderedCompactJsonFormatter` to the sink configuration method:
223+
224+
```csharp
225+
.WriteTo.Console(new RenderedCompactJsonFormatter())
226+
```
227+
228+
### Writing to the Azure Diagnostics Log Stream
229+
230+
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:
231+
232+
```csharp
233+
public static int Main(string[] args)
234+
{
235+
Log.Logger = new LoggerConfiguration()
236+
.MinimumLevel.Debug()
237+
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
238+
.Enrich.FromLogContext()
239+
.WriteTo.Console()
240+
// Add this line:
241+
.WriteTo.File(
242+
@"D:\home\LogFiles\Application\myapp.txt",
243+
fileSizeLimitBytes: 1_000_000,
244+
rollOnFileSizeLimit: true,
245+
shared: true,
246+
flushToDiskInterval: TimeSpan.FromSeconds(1))
247+
.CreateLogger();
248+
```

appveyor.yml

+2-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
version: '{build}'
22
skip_tags: true
3-
image: Visual Studio 2017 Preview
4-
configuration: Release
3+
image: Visual Studio 2017
54
install:
65
- ps: mkdir -Force ".\build\" | Out-Null
7-
#- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/release/2.0.0/scripts/obtain/dotnet-install.ps1" -OutFile ".\build\installcli.ps1"
8-
#- ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli"
9-
#- ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 2.0.0-preview2-006497'
10-
#- ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path"
116
build_script:
127
- ps: ./Build.ps1
138
test: off
@@ -16,7 +11,7 @@ artifacts:
1611
deploy:
1712
- provider: NuGet
1813
api_key:
19-
secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x
14+
secure: gvYNwOSxj9Bq4erOm7alpWzHlEmNLLUV99VYKV1WF9qTJeDkvYpswoNHi9sAlZH4
2015
skip_symbols: true
2116
on:
2217
branch: /^(master|dev)$/

global.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"sdk": {
3-
"version": "2.0.0"
3+
"version": "2.2.105"
44
}
55
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using System;
2+
using System.Diagnostics;
3+
using System.Threading;
4+
using Microsoft.AspNetCore.Mvc;
5+
using EarlyInitializationSample.Models;
6+
using Microsoft.Extensions.Logging;
7+
using Serilog;
8+
9+
namespace EarlyInitializationSample.Controllers
10+
{
11+
public class HomeController : Controller
12+
{
13+
static int _callCount;
14+
15+
readonly ILogger<HomeController> _logger;
16+
readonly IDiagnosticContext _diagnosticContext;
17+
18+
public HomeController(ILogger<HomeController> logger, IDiagnosticContext diagnosticContext)
19+
{
20+
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
21+
_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
22+
}
23+
24+
public IActionResult Index()
25+
{
26+
_logger.LogInformation("Hello, world!");
27+
28+
_diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));
29+
30+
return View();
31+
}
32+
33+
public IActionResult Privacy()
34+
{
35+
throw new InvalidOperationException("Something went wrong.");
36+
}
37+
38+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
39+
public IActionResult Error()
40+
{
41+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
42+
}
43+
}
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp2.2</TargetFramework>
5+
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
6+
</PropertyGroup>
7+
8+
<ItemGroup>
9+
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
10+
</ItemGroup>
11+
12+
<ItemGroup>
13+
<PackageReference Include="Microsoft.AspNetCore.App" />
14+
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
15+
</ItemGroup>
16+
17+
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace EarlyInitializationSample.Models
2+
{
3+
public class ErrorViewModel
4+
{
5+
public string RequestId { get; set; }
6+
7+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8+
}
9+
}

0 commit comments

Comments
 (0)