Skip to content

Commit 56fefca

Browse files
authored
Quick README updates to reflect .NET 6+ host configuration
1 parent bf4ae07 commit 56fefca

File tree

1 file changed

+55
-91
lines changed

1 file changed

+55
-91
lines changed

README.md

+55-91
Original file line numberDiff line numberDiff line change
@@ -18,53 +18,38 @@ dotnet add package Serilog.AspNetCore
1818

1919
```csharp
2020
using Serilog;
21-
using Serilog.Events;
2221

23-
public class Program
22+
Log.Logger = new LoggerConfiguration()
23+
.WriteTo.Console()
24+
.CreateLogger();
25+
26+
try
2427
{
25-
public static int Main(string[] args)
26-
{
27-
Log.Logger = new LoggerConfiguration()
28-
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
29-
.Enrich.FromLogContext()
30-
.WriteTo.Console()
31-
.CreateLogger();
28+
Log.Information("Starting web application");
3229

33-
try
34-
{
35-
Log.Information("Starting web host");
36-
CreateHostBuilder(args).Build().Run();
37-
return 0;
38-
}
39-
catch (Exception ex)
40-
{
41-
Log.Fatal(ex, "Host terminated unexpectedly");
42-
return 1;
43-
}
44-
finally
45-
{
46-
Log.CloseAndFlush();
47-
}
48-
}
49-
```
30+
var builder = WebApplication.CreateBuilder(args);
31+
32+
builder.Host.UseSerilog(); // <-- Add this line
33+
34+
var app = builder.Build();
5035

51-
**Then**, add `UseSerilog()` to the Generic Host in `CreateHostBuilder()`.
36+
app.MapGet("/", () => "Hello World!");
5237

53-
```csharp
54-
public static IHostBuilder CreateHostBuilder(string[] args) =>
55-
Host.CreateDefaultBuilder(args)
56-
.UseSerilog() // <-- Add this line
57-
.ConfigureWebHostDefaults(webBuilder =>
58-
{
59-
webBuilder.UseStartup<Startup>();
60-
});
38+
app.Run();
39+
}
40+
catch (Exception ex)
41+
{
42+
Log.Fatal(ex, "Application terminated unexpectedly");
43+
}
44+
finally
45+
{
46+
Log.CloseAndFlush();
6147
}
6248
```
6349

64-
**Finally**, clean up by removing the remaining configuration for the default logger:
50+
The `builder.Host.UseSerilog()` call will redirect all log events through your Serilog pipeline.
6551

66-
* 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)
67-
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)
52+
**Finally**, clean up by removing the remaining configuration for the default logger, including 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).
6853

6954
That's it! With the level bumped up a little you will see log output resembling:
7055

@@ -118,23 +103,14 @@ To enable the middleware, first change the minimum level for `Microsoft.AspNetCo
118103
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
119104
```
120105

121-
Then, in your application's _Startup.cs_, add the middleware with `UseSerilogRequestLogging()`:
106+
Then, in your application's _Program.cs_, add the middleware with `UseSerilogRequestLogging()`:
122107

123108
```csharp
124-
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
125-
{
126-
if (env.IsDevelopment())
127-
{
128-
app.UseDeveloperExceptionPage();
129-
}
130-
else
131-
{
132-
app.UseExceptionHandler("/Home/Error");
133-
}
134-
135-
app.UseSerilogRequestLogging(); // <-- Add this line
136-
137-
// Other app configuration
109+
var app = builder.Build();
110+
111+
app.UseSerilogRequestLogging(); // <-- Add this line
112+
113+
// Other app configuration
138114
```
139115

140116
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.)
@@ -204,31 +180,21 @@ To use this technique, first replace the initial `CreateLogger()` call with `Cre
204180
using Serilog;
205181
using Serilog.Events;
206182

207-
public class Program
208-
{
209-
public static int Main(string[] args)
210-
{
211-
Log.Logger = new LoggerConfiguration()
212-
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
213-
.Enrich.FromLogContext()
214-
.WriteTo.Console()
215-
.CreateBootstrapLogger(); // <-- Change this line!
183+
Log.Logger = new LoggerConfiguration()
184+
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
185+
.Enrich.FromLogContext()
186+
.WriteTo.Console()
187+
.CreateBootstrapLogger(); // <-- Change this line!
216188
```
217189

218190
Then, pass a callback to `UseSerilog()` that creates the final logger:
219191

220192
```csharp
221-
public static IHostBuilder CreateHostBuilder(string[] args) =>
222-
Host.CreateDefaultBuilder(args)
223-
.UseSerilog((context, services, configuration) => configuration
224-
.ReadFrom.Configuration(context.Configuration)
225-
.ReadFrom.Services(services)
226-
.Enrich.FromLogContext()
227-
.WriteTo.Console())
228-
.ConfigureWebHostDefaults(webBuilder =>
229-
{
230-
webBuilder.UseStartup<Startup>();
231-
});
193+
builder.Host.UseSerilog((context, services, configuration) => configuration
194+
.ReadFrom.Configuration(context.Configuration)
195+
.ReadFrom.Services(services)
196+
.Enrich.FromLogContext()
197+
.WriteTo.Console());
232198
```
233199

234200
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.
@@ -256,7 +222,7 @@ By default, Serilog ignores providers, since there are usually equivalent Serilo
256222
To have Serilog pass events to providers, **using two-stage initialization** as above, pass `writeToProviders: true` in the call to `UseSerilog()`:
257223

258224
```csharp
259-
.UseSerilog(
225+
builder.Host.UseSerilog(
260226
(hostingContext, services, loggerConfiguration) => /* snip! */,
261227
writeToProviders: true)
262228
```
@@ -276,23 +242,21 @@ To write newline-delimited JSON, pass a `CompactJsonFormatter` or `RenderedCompa
276242
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:
277243

278244
```csharp
279-
public static int Main(string[] args)
280-
{
281-
Log.Logger = new LoggerConfiguration()
282-
.MinimumLevel.Debug()
283-
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
284-
.Enrich.FromLogContext()
285-
.WriteTo.Console()
286-
// Add this line:
287-
.WriteTo.File(
288-
System.IO.Path.Combine(Environment.GetEnvironmentVariable("HOME"), "LogFiles", "Application", "diagnostics.txt"),
289-
rollingInterval: RollingInterval.Day,
290-
fileSizeLimitBytes: 10 * 1024 * 1024,
291-
retainedFileCountLimit: 2,
292-
rollOnFileSizeLimit: true,
293-
shared: true,
294-
flushToDiskInterval: TimeSpan.FromSeconds(1))
295-
.CreateLogger();
245+
Log.Logger = new LoggerConfiguration()
246+
.MinimumLevel.Debug()
247+
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
248+
.Enrich.FromLogContext()
249+
.WriteTo.Console()
250+
// Add this line:
251+
.WriteTo.File(
252+
System.IO.Path.Combine(Environment.GetEnvironmentVariable("HOME"), "LogFiles", "Application", "diagnostics.txt"),
253+
rollingInterval: RollingInterval.Day,
254+
fileSizeLimitBytes: 10 * 1024 * 1024,
255+
retainedFileCountLimit: 2,
256+
rollOnFileSizeLimit: true,
257+
shared: true,
258+
flushToDiskInterval: TimeSpan.FromSeconds(1))
259+
.CreateLogger();
296260
```
297261

298262
### Pushing properties to the `ILogger<T>`

0 commit comments

Comments
 (0)