Introduction
Logging is a crucial aspect of software development, offering developers insights into their applications’ behaviour and performance. In the .NET ecosystem, Serilog stands out as a powerful logging library that simplifies the logging process while offering flexibility and extensibility. In this guide, we’ll explore how to leverage Serilog for logging in .NET applications, covering its key features, configuration, and integration.
What is Serilog?
Serilog is a structured logging library for .NET applications, designed to produce detailed, structured, and contextual logs.It supports various output sinks such as console, file, database, and third-party services like Seq, Elasticsearch, and Splunk.
Serilog’s structured logging allows developers to log data in a structured format, making it easier to analyze and query logs. It is easy to set up, has a clean API, and runs on all recent .NET platforms. While it’s useful out of the box, Serilog can be instrumented with additional packages to extend its functionality.
Setting Up Serilog in a .NET Application
You can install the Serilog NuGet package in your .NET project by using following .NET CLI command
dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File
Basic Logging
Once you’ve installed Serilog, you can set up a basic logger like this:
using Serilog;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("log.txt",
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true)
.CreateLogger();
try
{
const string name = "Serilog";
Log.Information("Hello, {Name}!", name);
throw new InvalidOperationException("Oops...");
}
catch (Exception ex)
{
Log.Error(ex, "Unhandled exception");
}
finally
{
await Log.CloseAndFlushAsync(); // ensure all logs written before app exits
}
In this example, we’re creating a new logger configuration, setting it to write to the console, file and then creating the logger. We then log an information-level message and error-level message. At the end we call a method CloseAndFlushAsync to ensure all logs are written before app exits.
Structured Logging
One of the key features of Serilog is its support for structured logging. Unlike traditional logging, which logs string messages, structured logging logs structured data. This can make it easier to search and analyze your logs. Here’s an example:
log.Information("Processing order {OrderId}", orderId);
In this example, orderId is a property attached to the log event.
Log Levels and Filtering
Serilog allows developers to specify minimum log levels for different log sources, enabling fine-grained control over which log messages are captured. Log filtering can be implemented to include or exclude specific log events based on criteria such as log level, message content, or contextual properties.
Developers can configure filters using Serilog’s fluent configuration API. Serilog supports several log levels, including Verbose, Debug, Information, Warning, Error, and Fatal. For example:
Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .Filter.ByIncludingOnly(logEvent => logEvent.Level == LogEventLevel.Information) .CreateLogger();
Configuring Serilog for Different Sinks
Serilog supports a variety of sinks – destinations where your logs will be stored. Two common sinks are files and databases. Here’s how you can configure Serilog to log to these sinks.
File Sink
To write logs to a file, you need to install the Serilog.Sinks.File package. You can do this via the NuGet package manager in Visual Studio or by running the following command in your Package Manager Console:
Install-Package Serilog.Sinks.File
Once installed, you can configure the file sink like this:
var log = new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger();
This will write your logs to a file named log.txt.
Database Sink
To write logs to a database, you can use the Serilog.Sinks.MSSqlServer package for SQL Server databases. Install it via NuGet or the Package Manager Console:
Install-Package Serilog.Sinks.MSSqlServer
You can then configure the database sink like this:
var connectionString = "Server=.;Database=LogDB;Integrated Security=True;"; var tableName = "Logs"; var log = new LoggerConfiguration() .WriteTo.MSSqlServer(connectionString, tableName) .CreateLogger();
This will write your logs to a table named Logs in the LogDB database on your local SQL Server instance.
Remember, these are just two examples. Serilog supports many other sinks such as Elasticsearch, Seq, console, debug, and more. You can find a full list of available sinks in the Serilog documentation
Here are some best practices for configuring Serilog in your .NET applications:
- Avoid the Static Logger Class: Serilog comes with a static Log class that can be used throughout the application to log events and information. However, using this static class can break the dependency inversion principle. It’s recommended to integrate Serilog with Microsoft’s built-in logging interface.
- Configure Serilog From appsettings.json: It’s better to use the configuration system to set up Serilog in your applications. This allows you to change the configuration without needing to publish a new build of your application.
- Use the Right Sink for Your Needs: Serilog uses what are called sinks to send your logs to a text file, database, or log management solutions. Choose the sink that best fits your application’s needs.
- Use Structured Logging: When Serilog was first released, one of the biggest reasons to use it was its support for structured logging. Structured logging makes it easy to search for logs by the logging level.
- Make Good Use of Multiple Serilog Logging Levels: Be sure to use verbose, debug, information, warning, error, and fatal logging levels as appropriate. This is really valuable if you want to specify only certain levels to be logged to specific logging sinks or to reduce logging in production.
- Use Enrichments: Enrichments are a way to add additional information to every log event. They can be very useful for adding context to your logs.
Summary
Logging plays a vital role in monitoring, troubleshooting, and optimizing software applications. Serilog simplifies the logging process in .NET applications with its intuitive API, structured logging capabilities, and extensive configuration options. By following the guidelines outlined in this guide, developers can leverage Serilog to create robust and informative logs that facilitate effective application monitoring and maintenance.
Whether you’re building a small web application or a complex enterprise system, Serilog empowers you to take control of your application’s logging and gain valuable insights into its behavior and performance.