What is Serilog
Serilog is a diagnostic logging library for .NET applications. It is straightforward to set up, has a clean API, and is extensible. Serilog is built with structured logging in mind. It is a great choice for applications that require high-performance logging.
Features
Serilog has the following features:
- sinks: a sink is a ‘plugin’ that writes log events to a specific target. Serilog has a wide range of sinks, including sinks for writing to the console, files, databases, and cloud services.
- enrichers: enrichers add additional properties to log events. Serilog has a wide range of enrichers, including enrichers for adding properties like the machine name, process id, and thread id to log events.
- destructuring: destructuring allows you to log complex objects in a structured way. Serilog has built-in support for destructuring objects like exceptions, dictionaries, and collections.
- filtering: filtering allows you to control which log events are written to a sink. Serilog has a wide range of filters, including filters for controlling the minimum log level, and filters for controlling which log events are written to a sink based on the log event’s properties.
- templates: templates allow you to control the format of log events. Serilog has built-in support for templates, including support for formatting log events as JSON, XML, and plain text.
- configuration: Serilog has built-in support for configuration. You can configure Serilog using code, XML, JSON, and environment variables.
- extensibility: Serilog is extensible. You can write your own sinks, enrichers, destructurers, filters, and templates.
Getting started
To get started with Serilog, you need to install the Serilog NuGet package. You can install the Serilog NuGet package using the following command:
dotnet add package Serilog
After installing the Serilog NuGet package, you can start using Serilog in your application. The following example shows how to set up Serilog in a console application:
using Serilog;
class Program
{
static void Main()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
Log.Information("Hello, Serilog!");
}
}
Adding Serilog to a .NET 8 web application can be done with the following code:
var builder = WebApplication.CreateBuilder(args);
//Add Serilog
builder.Services.AddSerilog(cfg =>
{
cfg.ReadFrom.Configuration(builder.Configuration);
});
builder.Host.UseSerilog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
In the example above, the full configuration is done in the appsettings.json
file. The configuration is read from the appsettings.json
file, and the logger is added to the services. The logger is then used in the host. the config example below shows a configuration for Serilog that writes log events to the console, a file, and an SQL Server database:
"Serilog" : {
"Using": [
"Serilog.Sinks.File",
"Serilog.Sinks.Console",
"Serilog.Sinks.MSSqlServer"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs\\log.log",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
},
{
"Name": "Console"
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "[Connectionstring]",
"tableName": "LogEvents",
"autoCreateSqlTable": true
}
}
]
}
Sinks
As mentioned in the introduction, a sink is a ‘plugin’ that writes log events to a specific target. Serilog has a wide range of sinks, including sinks for writing to the console, files, databases, and cloud services. The following example shows how to write log events to the console:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
The following example shows how to write log events to a file:
Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.log")
.CreateLogger();
The following example shows how to write log events to an SQL Server database:
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer("[Connectionstring]", "LogEvents")
.CreateLogger();
As you can see, the pattern is always the same. You create a new logger configuration and use the WriteTo
method to specify the sink that you want to use. You can also specify additional arguments for the sink, like the path of the file, the connection string of the database, or the name of the table in the database.
The List of available sinks is quit extensive and can be found here
Enrichers
enrichers add additional properties to log events. Serilog has a wide range of enrichers, including enrichers for adding properties like the machine name, process id, and thread id to log events. The following example shows how to add the machine name to log events:
Install the package
dotnet add package Serilog.Enrichers.Environment
add the enricher to the logger configuration
Log.Logger = new LoggerConfiguration()
.Enrich.WithMachineName()
.CreateLogger();
Enrichers can also be used to mask sensitive information in log events. The following example shows how to mask the password
property in log events:
dotnet add package Serilog.Enrichers.Sensitive
builder.Host.UseSerilog((ctx, lc) =>
{
lc.ReadFrom.Configuration(configuration)
.Enrich.WithSensitiveDataMasking(cfg =>
{
cfg.MaskValue = "**MASKED**";
cfg.MaskingOperators = new List<IMaskingOperator>
{
new EmailAddressMaskingOperator()
};
});
});
this results in the following log line
[16:31:25 INF] Successfully handled SignInCommand with request {"VisitorName": "Angelo Dejaeghere", "VisitorEmail": "**MASKED**", "VisitorCompany": "string", "CompanyId": 2, "EmployeeId": 143}
Conclusion
Serilog is a great choice for applications that require high-performance logging. It is straightforward to set up, has a clean API, and is extensible. Serilog is built with structured logging in mind. It has a wide range of sinks, enrichers, destructurers, filters, and templates. It is a great choice for applications that require high-performance logging.