In this article, we discuss the basics of logging and step-by-step implementation with Serilog in .NET Core 6 Web API.

Agenda

Prerequisites

Basics of Logging

Benefits of Logging

Logging is an important thing in the software development life cycle, and there are several benefits to logging.

Serilog in .NET Core

Serilog is a logging library in .NET Core applications, and it provides a flexible and extensible logging framework with structured logging.

Step 1. Install the following NuGet package from the manager.

Install serilog package

Step 2. Serilog configuration in the app settings file.

{
  "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.txt",
          "rollingInterval": "Day"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "WeatherForecast"
    }
  }
}

Explanation

Step 3. Register required Serilog services with app settings configuration and add middleware in the pipeline.

using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add serilog services to the container and read config from appsettings
builder.Host.UseSerilog((context, configuration) =>
    configuration.ReadFrom.Configuration(context.Configuration));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Configure Serilog for logging
app.UseSerilogRequestLogging();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 4. Weather Forecast class with required properties.

namespace SerilogDemo
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string? Summary { get; set; }
    }
}

Step 5. Weather Forecast controller with action method and logger injection in the constructor for logging purposes.

using Microsoft.AspNetCore.Mvc;

namespace SerilogDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("Requesting Weather Forecast Details...");

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

Step 6. Run the application and execute the application endpoint with the help of Swagger, and in the log file, we can see our log entries with details. If any error occurs while registering the services in the program class or other events, the logger is also capturing the same as shown below.

Serilog Demo

Weather podcast logs

If we want to customize and structure the log detail or upload it to cloud blob storage as per requirement, then that customization is also possible with Serilog.

GitHub: https://github.com/Jaydeep-007/SeriloggerDemo

Conclusion

In this article, we looked into the basics of logging and its benefits in real-time with step-by-step implementation with the help of .NET Core 6 Weather Forecast API.