This is a sample project showing Serilog configured in the default .NET 6 web application template.
To show how everything fits together, the sample includes:
- Support for .NET 6's
ILogger<T>
andWebApplicationBuilder
- Namespace-specific logging levels to suppress noise from the framework
- JSON configuration
- Clean, themed console output
- Local logging to a rolling file
- Centralized structured logging with Seq
- Streamlined HTTP request logging
- Filtering out of noisy events using Serilog.Expressions
- Exception logging
- Fallback/fail-safe bootstrap logger
- Proper flushing of logs at exit
The code is not commented, so that the structure is easier to compare with the default template. If you're keen to understand the trade-offs and reasoning behind the choices made here, there's some commentary on each section in Setting up from scratch below.
You'll need the .NET 6.0 SDK or later to run the sample. Check the version you have installed with:
dotnet --version
After checking out this repository or downloading a zip file of the source code, you can run the project with:
dotnet run
Some URLs will be printed to the terminal: open them in a browser to see request logging in action.
/
— should show "Hello, world!" and respond successfully/oops
— throws an exception, which will be logged
To see structured log output, start a temporary local Seq instance with:
docker run --rm -it -e ACCEPT_EULA=y -p 5341:80 datalust/seq
and open http://localhost:5341
in your browser (for Windows users, there's also an MSI at https://datalust.co/download).
You can freely copy code from this project to your own applications. If you'd like to set up from scratch, and skip any steps that aren't relevant to you, try following the steps below.
mkdir dotnet6-serilog-example
cd dotnet6-serilog-example
dotnet new web
dotnet add package serilog.aspnetcore
dotnet add package serilog.sinks.seq
dotnet add package serilog.expressions
Its important that logging is initialized as early as possible, so that errors that might prevent your app from starting are logged.
At the very top of Program.cs
:
using Serilog;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
Log.Information("Starting up");
CreateBootstrapLogger()
sets up Serilog so that the initial logger configuration (which writes only to Console
), can be swapped
out later in the initialization process, once the web hosting infrastructure is available.
Configuration of the web application in Program.cs
can now be enclosed in a try
block.
try
{
// <snip>
}
catch (Exception ex)
{
Log.Fatal(ex, "Unhandled exception");
}
finally
{
Log.Information("Shut down complete");
Log.CloseAndFlush();
}
The catch
block will log any exceptions thrown during start-up.
The Log.CloseAndFlush()
in the finally
block ensures that any queued log events will be properly recorded when the program exits.
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.ReadFrom.Configuration(ctx.Configuration));
In appsettings.json
, remove "Logging"
and add "Serilog"
.
The complete JSON configuration from the example is:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "@mt = 'An unhandled exception has occurred while executing the request.'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": { "path": "./logs/log-.txt", "rollingInterval": "Day" }
},
{
"Name": "Seq",
"Args": { "serverUrl": "http://localhost:5341" }
}
]
},
"AllowedHosts": "*"
}
Remove all "Logging"
configuration from appsettings.Development.json
. (During development, you should normally use the same logging
level as you use in production; if you can't find problems using the production logs in development, you'll have an even harder time
finding problems in the real production environment.)
By default, the ASP.NET Core framework logs multiple information-level events per request.
Serilog's request logging streamlines this, into a single message per request, including path, method, timings, status code, and exception.
app.UseSerilogRequestLogging();
This setup enables both Serilog's static Log
class, as you see used in the example above, and Microsoft.Extensions.Logging's
ILogger<T>
, which can be consumed through dependency injection into controllers and other components.
If you're running a local Seq instance, you can now view the structured properties attached to your application logs in the Seq UI:
Ask your question on Stack Overflow and tag it with serilog
.