Skip to content

Using Serilog in .Net 5+/Core

In this article we will see how you can quickly setup Serilog logging in your .Net Core or .Net 5+ applications very easily. We will setup file based logs, with rolling intervals. Rolling intervals creates new log files based on interval we configured. I am using .Net 6 here in this article.

For .Net Console Application

For .Net console application, first we need to add below nuget packages in our project:

dotnet add package Serilog
dotnet add package Serilog.Sinks.File

After that we need to create new logger at the start of the program and then we can use this logger to log Information. Below is the code in a very minimilastic Program.cs file:

using Serilog;


Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

Log.Information("Application Started.");

Console.WriteLine("Hello, World!");

Here we have created logger configuration and then created a logger. This logger logs to Logs/myapp.txt file and new file will be created based on each day. It will produce file with name myapp<YYYYddmm>.txt format.


For Asp.Net Application

For asp.net application, first we need to add below package in our project:

dotnet add package Serilog.AspNetCore

Now we need to create a new logger configuration and then use it in our request pipeline. So, after these changes, the program.cs file for your MVC or WebAPI project will look like this:

// Add this code block
using Serilog;

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

Log.Information("Starting web application");
// Add end

var builder = WebApplication.CreateBuilder(args);


builder.Host.UseSerilog(); // Add this one also

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();
}

app.UseSerilogRequestLogging(); // Add this line also

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

In above code snippet, in the program.cs file first we have created a logger configuration and then created a logger. This logger logs to Logs/myapp.txt file and new file will be created based on each day. After that we have added Serilog in the builder host and finally we are using it in our request pipeline via UseSerilogRequestLogging.

Now you can use ILogger in your any controller or normal classes which gets ILogger via dependency injection. So for example, you can use it in the WeatherForecastController class like this:

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("Serilog: GetWeatherForecast"); // Log data to file
        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();
    }
}

If you have questions, please let me know in comments.

Be First to Comment

Leave a Reply

Your email address will not be published.