Skip to content

Commit 458610a

Browse files
authored
Merge pull request #235 from serilog/dev
4.0.0 Release
2 parents 16be480 + 3d0fbd2 commit 458610a

File tree

123 files changed

+1509
-40587
lines changed

Some content is hidden

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

123 files changed

+1509
-40587
lines changed

Diff for: Build.ps1

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ if(Test-Path .\artifacts) {
1111

1212
$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
1313
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
14-
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"]
14+
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "main" -and $revision -ne "local"]
1515

1616
echo "build: Version suffix is $suffix"
1717

Diff for: README.md

+81-37
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
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/)
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

33
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.
44

55
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.
66

7+
**.NET Framework** and .NET Core 2.x are supported by version 3.4.0 of this package. Recent versions of _Serilog.AspNetCore_ require .NET Core 3.x, .NET 5, or later.
8+
79
### Instructions
810

911
**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app.
@@ -22,7 +24,6 @@ public class Program
2224
public static int Main(string[] args)
2325
{
2426
Log.Logger = new LoggerConfiguration()
25-
.MinimumLevel.Debug()
2627
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
2728
.Enrich.FromLogContext()
2829
.WriteTo.Console()
@@ -61,7 +62,7 @@ public class Program
6162

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

64-
* 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)
65+
* 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 _Sample_ project](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/Sample/Program.cs), if required)
6566
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)
6667

6768
That's it! With the level bumped up a little you will see log output resembling:
@@ -81,7 +82,7 @@ That's it! With the level bumped up a little you will see log output resembling:
8182

8283
**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()`.
8384

84-
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).
85+
A more complete example, including `appsettings.json` configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/Sample).
8586

8687
### Request logging
8788

@@ -146,7 +147,8 @@ During request processing, additional properties can be attached to the completi
146147

147148
public HomeController(IDiagnosticContext diagnosticContext)
148149
{
149-
_diagnosticContext = diagnosticContext ?? throw new ArgumentNullException(nameof(diagnosticContext));
150+
_diagnosticContext = diagnosticContext ??
151+
throw new ArgumentNullException(nameof(diagnosticContext));
150152
}
151153

152154
public IActionResult Index()
@@ -187,59 +189,73 @@ app.UseSerilogRequestLogging(options =>
187189
});
188190
```
189191

190-
### Inline initialization
192+
### Two-stage initialization
191193

192-
You can alternatively configure Serilog inline, in `BuildWebHost()`, using a delegate as shown below:
194+
The example at the top of this page shows how to configure Serilog immediately when the application starts. This has the benefit of catching and reporting exceptions thrown during set-up of the ASP.NET Core host.
193195

194-
```csharp
195-
.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
196-
.ReadFrom.Configuration(hostingContext.Configuration)
197-
.Enrich.FromLogContext()
198-
.WriteTo.Console())
199-
```
196+
The downside of initializing Serilog first is that services from the ASP.NET Core host, including the `appsettings.json` configuration and dependency injection, aren't available yet.
200197

201-
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.
198+
To address this, Serilog supports two-stage initialization. An initial "bootstrap" logger is configured immediately when the program starts, and this is replaced by the fully-configured logger once the host has loaded.
202199

203-
If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.
200+
To use this technique, first replace the initial `CreateLogger()` call with `CreateBoostrapLogger()`:
204201

205-
A complete example, showing this approach, can be found in [the _InlineIntializationSample_ project](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/InlineInitializationSample).
202+
```csharp
203+
using Serilog;
206204

207-
### Enabling `Microsoft.Extensions.Logging.ILoggerProvider`s
205+
public class Program
206+
{
207+
public static int Main(string[] args)
208+
{
209+
Log.Logger = new LoggerConfiguration()
210+
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
211+
.Enrich.FromLogContext()
212+
.WriteTo.Console()
213+
.CreateBootstrapLogger(); // <-- Change this line!
214+
```
208215

209-
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()`.
216+
Then, pass a callback to `UseSerilog()` that creates the final logger:
210217

211-
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.
218+
```csharp
219+
public static IHostBuilder CreateHostBuilder(string[] args) =>
220+
Host.CreateDefaultBuilder(args)
221+
.UseSerilog((context, services, configuration) => configuration
222+
.ReadFrom.Configuration(context.Configuration)
223+
.ReadFrom.Services(services)
224+
.Enrich.FromLogContext()
225+
.WriteTo.Console())
226+
.ConfigureWebHostDefaults(webBuilder =>
227+
{
228+
webBuilder.UseStartup<Startup>();
229+
});
230+
```
212231

213-
**Using the recommended configuration:**
232+
It's important to note that the final logger **completely replaces** the bootstrap logger: if you want both to log to the console, for instance, you'll need to specify `WriteTo.Console()` in both places, as the example shows.
214233

215-
In the recommended configuration (in which startup exceptions are caught and logged), first create a `LoggerProviderCollection` in a static field in _Program.cs_:
234+
#### Consuming `appsettings.json` configuration
216235

217-
```csharp
218-
// using Serilog.Extensions.Logging;
219-
static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();
220-
```
236+
**Using two-stage initialization**, insert the `ReadFrom.Configuration(context.Configuration)` call shown in the example above. The JSON configuration syntax is documented in [the _Serilog.Settings.Configuration_ README](https://github.com/serilog/serilog-settings-configuration).
221237
222-
Next, add `WriteTo.Providers()` to the logger configuration:
238+
#### Injecting services into enrichers and sinks
223239

224-
```csharp
225-
.WriteTo.Providers(Providers)
226-
```
240+
**Using two-stage initialization**, insert the `ReadFrom.Services(services)` call shown in the example above. The `ReadFrom.Services()` call will configure the logging pipeline with any registered implementations of the following services:
227241

228-
Finally, pass the provider collection into `UseSerilog()`:
242+
* `IDestructuringPolicy`
243+
* `ILogEventEnricher`
244+
* `ILogEventFilter`
245+
* `ILogEventSink`
246+
* `LoggingLevelSwitch`
229247

230-
```csharp
231-
.UseSerilog(providers: Providers)
232-
```
248+
#### Enabling `Microsoft.Extensions.Logging.ILoggerProvider`s
233249

234-
Providers registered in _Startup.cs_ with `AddLogging()` will then receive events from Serilog.
250+
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()`.
235251

236-
**Using inline initialization:**
252+
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.
237253

238-
If [inline initialization](#inline-initialization) is used, providers can be enabled by adding `writeToProviders: true` to the `UseSerilog()` method call:
254+
To have Serilog pass events to providers, **using two-stage initialization** as above, pass `writeToProviders: true` in the call to `UseSerilog()`:
239255

240256
```csharp
241257
.UseSerilog(
242-
(hostingContext, loggerConfiguration) => /* snip! */,
258+
(hostingContext, services, loggerConfiguration) => /* snip! */,
243259
writeToProviders: true)
244260
```
245261

@@ -274,3 +290,31 @@ The Azure Diagnostic Log Stream ships events from any files in the `D:\home\LogF
274290
flushToDiskInterval: TimeSpan.FromSeconds(1))
275291
.CreateLogger();
276292
```
293+
294+
### Pushing properties to the `ILogger<T>`
295+
296+
If you want to add extra properties to all log events in a specific part of your code, you can add them to the **`ILogger<T>`** in **Microsoft.Extensions.Logging** with the following code. For this code to work, make sure you have added the `.Enrich.FromLogContext()` to the `.UseSerilog(...)` statement, as specified in the samples above.
297+
298+
```csharp
299+
// Microsoft.Extensions.Logging ILogger<T>
300+
// Yes, it's required to use a dictionary. See https://nblumhardt.com/2016/11/ilogger-beginscope/
301+
using (logger.BeginScope(new Dictionary<string, object>
302+
{
303+
["UserId"] = "svrooij",
304+
["OperationType"] = "update",
305+
}))
306+
{
307+
// UserId and OperationType are set for all logging events in these brackets
308+
}
309+
```
310+
311+
The code above results in the same outcome as if you would push properties in the **ILogger** in Serilog.
312+
313+
```csharp
314+
// Serilog ILogger
315+
using (logger.PushProperty("UserId", "svrooij"))
316+
using (logger.PushProperty("OperationType", "update"))
317+
{
318+
// UserId and OperationType are set for all logging events in these brackets
319+
}
320+
```

Diff for: appveyor.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ deploy:
1414
api_key:
1515
secure: jZtLAmD4ALF9x1BZR1DiV3KhKlliWbzRUAw73xfMZaBsvz19123qLz2zw1+hPdcn
1616
on:
17-
branch: /^(master|dev)$/
17+
branch: /^(main|dev)$/
1818
- provider: GitHub
1919
auth_token:
2020
secure: p4LpVhBKxGS5WqucHxFQ5c7C8cP74kbNB0Z8k9Oxx/PMaDQ1+ibmoexNqVU5ZlmX
2121
artifact: /Serilog.*\.nupkg/
2222
tag: v$(appveyor_build_version)
2323
on:
24-
branch: master
24+
branch: main

Diff for: assets/icon.png

19.9 KB
Loading

Diff for: global.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"sdk": {
33
"allowPrerelease": false,
4-
"version": "3.1.201",
4+
"version": "5.0.102",
55
"rollForward": "latestFeature"
66
}
77
}

Diff for: samples/EarlyInitializationSample/EarlyInitializationSample.csproj

-11
This file was deleted.

Diff for: samples/EarlyInitializationSample/Program.cs

-56
This file was deleted.

Diff for: samples/EarlyInitializationSample/Startup.cs

-45
This file was deleted.

Diff for: samples/EarlyInitializationSample/Views/Home/Privacy.cshtml

-6
This file was deleted.

Diff for: samples/EarlyInitializationSample/Views/Shared/Error.cshtml

-25
This file was deleted.

Diff for: samples/EarlyInitializationSample/Views/Shared/_CookieConsentPartial.cshtml

-25
This file was deleted.

0 commit comments

Comments
 (0)