avatarCan Sener

Summary

This article provides a comprehensive guide on implementing Serilog logging in .NET Core applications, detailing the setup process, configuration, and benefits of structured logging with Serilog.

Abstract

The article titled "Implementing Serilog Logging in .NET Core" serves as a tutorial for integrating the Serilog logging library into .NET Core applications. It begins with an introduction to the importance of logging for application monitoring and issue diagnosis, positioning Serilog as a flexible and powerful tool for .NET developers. The prerequisites for the tutorial include having the .NET Core SDK (version 2.1 or higher) installed and optionally using Visual Studio or Visual Studio Code. The article walks through creating a new .NET Core application, installing necessary Serilog packages, and configuring Serilog for basic and structured logging. It also covers how to add Serilog to a .NET Core web application, with examples of configuration in the Startup.cs file. The conclusion emphasizes the advantages of using Serilog for efficient and insightful log analysis, and the article ends with a call to engage with the writer and Stackademic's educational initiatives.

Opinions

  • The author suggests that Serilog is a popular and recommended logging library for .NET applications due to its flexibility, extensibility, and structured logging capabilities.
  • Visual Studio or Visual Studio Code is recommended for the development process, indicating a preference for these integrated development environments (IDEs).
  • The article conveys that structured logging with Serilog is a key feature that enhances the monitoring and diagnostics of applications by allowing for better analysis through associated properties in log events.
  • The author encourages reader engagement by asking them to consider clapping, following the writer, and following Stackademic on social media platforms.
  • There is an implicit endorsement of Serilog's ease of use and integration, as demonstrated by the step-by-step instructions and code examples provided in the tutorial.
  • The article promotes Stackademic's mission to democratize free programming education, suggesting that the organization's resources are valuable for learners worldwide.

Implementing Serilog Logging in .NET Core

Photo by Fotis Fotopoulos on Unsplash

Introduction

Logging is a fundamental aspect of any application, helping you monitor its behavior and diagnose issues. Serilog is a popular .NET logging library that provides flexibility, extensibility, and structured logging capabilities. In this tutorial, we’ll explore how to implement Serilog in a .NET Core application. We’ll set up a .NET Core project, configure Serilog, and use it to log events in a structured and customizable manner.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  1. .NET Core SDK installed (version 2.1 or higher).
  2. Visual Studio or Visual Studio Code (optional but recommended).

Creating a .NET Core Application

Let’s start by creating a new .NET Core application. You can use Visual Studio or Visual Studio Code, or you can use the command line. Open your command prompt or terminal and run the following commands

dotnet new console -n MySerilogApp
cd MySerilogApp

This will create a new .NET Core console application named MySerilogApp.

Adding Serilog

Installing Serilog Packages

To get started with Serilog, you’ll need to install the Serilog library and a Serilog sink for the log output. Open your project directory and run the following commands:

dotnet add package Serilog
dotnet add package Serilog.Sinks.Console

Configuring Serilog

Next, you need to configure Serilog in your application. In the Program.cs file, add the following code to set up a basic console logger:

using System;
using Serilog;

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

        Log.Information("Hello, Serilog!");

        // Rest of your application logic

        Log.CloseAndFlush();
    }
}

In this code, we configure Serilog to write log events to the console. You can add more sinks, like file logging, database logging, or custom sinks, as needed.

Structured Logging with Serilog

One of the key benefits of Serilog is its support for structured logging. You can log events with associated properties and use them for better analysis. Here’s an example of structured logging with Serilog:

using System;
using Serilog;

class Program
{
    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();
        var user = new { Username = "john_doe", Email = "[email protected]" };
        Log.Information("User {Username} with email {Email} logged in.", user.Username, user.Email);
        // Rest of your application logic
        Log.CloseAndFlush();
    }
}

The structured logging in this example associates properties with the log event, making it easier to search and filter logs.

Adding Serilog to a .NET Core Web Application

If you’re working with a .NET Core web application, the setup is similar. You can configure Serilog in your Startup.cs file. Here's an example:

using Serilog;
using Serilog.Events;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI v1"));
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        // Rest of your application configuration
        Log.CloseAndFlush();
    }
}

This code configures Serilog to log events to the console for a web application.

Conclusion

In this tutorial, we’ve implemented Serilog logging in a .NET Core application. You’ve learned how to configure Serilog, perform basic and structured logging, and integrate it into a .NET Core web application. With Serilog, you can enhance the monitoring and diagnostics of your application and make log analysis more efficient and insightful.

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
Serilog
Net Core
C Sharp Programming
Logging
Implementation
Recommended from ReadMedium