Advanced Logging Techniques in ASP.NET Core 8 with Serilog

Serilog

Introduction

Logging applications is a very crucial part of application development, as it monitors and investigates any issue or error in the application. Serilog is a popular and mostly useful tool for developers to log, providing structured logging that helps developers find errors and issues quickly.

Serilog is a diagnostic logging library for .NET applications. It provides a simple, flexible, and powerful way to log application events, errors, and other information. Serilog is designed to work well with structured logging, meaning it can log rich, structured data rather than just plain text messages.

Key Features of Serilog

  • Structured Logging: Serilog allows you to log structured data, which makes it easier to query and analyze logs. For example, you can log an object with multiple properties, and each property can be indexed and queried separately.
  • Sinks: Serilog supports various “sinks” that allow you to write logs to different storage systems, such as files, databases, consoles, and cloud services like Azure Application Insights, Elasticsearch, and more.
  • Configurable: Serilog is highly configurable. You can configure it to write logs to multiple sinks, filter logs by severity level, enrich logs with additional data, and more.
  • Performance: Serilog is designed to be performant and to minimize the impact on your application’s performance.
  • Integration: Serilog integrates well with other .NET libraries and frameworks, including ASP.NET Core, Entity Framework, and more.

In this article, we will learn how we can use Serilog for logging.

Now, let’s go.

To follow Serilog implementation steps, you can use an existing project where you need to implement logging using Serilog or Create a new Asp.NET Core Web application. Now, let’s go for implementation. For this demo, I am using the ASP.NET Core Web API project.

Step 1. Install the following packages in your project.

  • Serilog
  • Serilog.AspNetCore
  • Serilog.Sinks.File

After the installation of the necessary packages, we will need to configure Serilog in the appsetting.json file. So, in the appsetting.json file, we will add the code below for the Serilog configuration.

"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.log",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true
        }
      }
    ]
  },

Step 2. In the Program.cs we will add the Serilog configuration:

builder.Host.UseSerilog((context, configuration) =>
    configuration.ReadFrom.Configuration(context.Configuration));

Step 3. Then, above the App.Run() write Serilog middleware

app.UseSerilogRequestLogging();

Step 4. Then, we can now log in to any C# class.

Below is an example of logging in WeatherForecastController.

private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}
  [HttpGet(Name = "GetWeatherForecast")]
  public IEnumerable<WeatherForecast> Get()
  {
      _logger.LogInformation("Get Weather forecast called sucessfully");

      return Enumerable.Range(1, 5).Select(index => new WeatherForecast
      {
          Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
          TemperatureC = Random.Shared.Next(-20, 55),
          Summary = Summaries[Random.Shared.Next(Summaries.Length)]
      })
      .ToArray();
  }

Now, let’s run the app and check. When you run the app and call the GetWeatherForecast endpoint of your Api, the log will be captured inside the log folder, and you can open the folder and see the log, which will look like the below one.

Serilog type

Conclusion

This article has provided a comprehensive overview of Serilog, a powerful logging library for .NET applications. We covered its advantages, including structured logging, and demonstrated how to implement it in an ASP.NET Core 8 application. By integrating Serilog, developers can achieve more detailed and useful log data, improving debugging, monitoring, and system maintenance.

The structured logging capability of Serilog enhances log analysis and visualization, making it an essential tool for modern applications. Adopting Serilog can significantly enhance your application’s observability, reliability, and overall health.


Similar Articles