Getting Started with Serilog in C#

Getting Started with Serilog in C#

Introduction

Logging is an essential aspect of software development, helping developers monitor and troubleshoot applications effectively. Serilog is a popular logging library in the .NET ecosystem, known for its flexibility and extensibility. Logging with Serilog in C# is a powerful combination.

In this blog post, we’ll explore the basics of using Serilog with C# and demonstrate how it can improve your logging experience and make debugging a breeze.

What is Serilog?

Serilog is a structured logging library for .NET applications. Unlike traditional logging libraries that rely on plain text messages, Serilog focuses on structured data, making it easier to filter, search, and analyze logs efficiently.

Serilog allows you to create log entries with structured properties, which can be especially valuable when dealing with complex systems and large-scale applications.

Setting up Serilog

To get started with Serilog, you’ll need to install the Serilog NuGet package and configure it in your C# project. You can install the package using the NuGet Package Manager Console:

Install-Package Serilog

Next, you should choose a sink for your logs. Sinks are responsible for routing log events to various outputs, such as files, databases, or external services.

One popular sink is Serilog.Sinks.Console, which outputs logs to the console. You can install it using the following command:

Install-Package Serilog.Sinks.Console

Configuring Serilog

Now that you have Serilog and a sink installed, you need to configure it in your application. Typically, this is done in your application’s entry point, such as the Main method. Here’s a basic configuration example:

using Serilog;

class Program
{
    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();

        Log.Information("Hello, Serilog!");
        
        // Your application code here
        
        Log.CloseAndFlush();
    }
}

In this example, we set up Serilog to log into the console using the WriteTo.Console() method. Depending on your requirements, you can add multiple sinks or configure more advanced settings.

Logging with Serilog

Now that Serilog is configured, you can start logging messages with it. Serilog provides various log levels, including Information, Warning, Error, and Debug. You can use these levels to categorise your log messages based on their importance.

Here’s how you can log messages using different log levels:

Log.Information("This is an informational message."); 
Log.Warning("This is a warning message."); 
Log.Error("This is an error message."); 
Log.Debug("This is a debug message.");

Additionally, you can include structured data in your log entries, making it easier to filter and search for specific information:

Log.Information("User {UserId} logged in successfully.", userId); 
Log.Error("An error occurred while processing order {OrderId}.", orderId);

Enrichers and Filtering

Serilog also allows you to enrich your log events with additional context. You can add enrichers to include information such as the current timestamp, thread ID, or any custom properties you need. Enrichers help you gain more insights into your logs.

Log.Loggernew LoggerConfiguration() 
                     .WriteTo.Console() 
                     .Enrich.WithThreadId() 
                     .Enrich.WithProperty("Application""MyApp") 
                     .CreateLogger();

Filtering is another powerful feature of Serilog. You can filter log events based on their properties and log levels, allowing you to control which events are written to the output. For example, you can configure Serilog to only log error messages or to ignore messages from specific sources.

Log.Loggernew LoggerConfiguration() 
                    .WriteTo.Console() 
                    .Filter.ByExcluding(e => e.Level == LogEventLevel.Debug) 
                    .CreateLogger();

Conclusion

Serilog is a flexible and powerful logging library for C# applications. Its structured logging approach makes it easier to manage and analyze logs, especially in complex and large-scale systems.

By configuring and using Serilog in your C# projects, you can gain valuable insights into your application’s behaviour, streamline debugging, and improve overall software quality.

So, if you’re not already using Serilog, consider trying it in your next project and experience its benefits to your logging workflow.

The official documentation for Serilog can be found here: – https://serilog.net.

I have previously blogged about logging here: – Integrating Serilog with Loki for Efficient Logging in .NET Applications, Exploring the Versatility of Serilog Sinks in .NET Applications.

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.