.NET Core 6 How to Log to File Using Serilog

I recently needed to place logs to a file which can be viewed later to check issues with the deployed app that’s sitting on the remote server, but realized that .NET Core does not have a provide a built-in ILoggerProvider implementation for file logging. There are many ways to do it by either using 3rd party libraries or writing your own file logger. I found that serilog is the simplest way for me, as it’s quick to set up and requires minimum effort to get things up and running. In this article, I will share with you how to log to a file using serilog.

First, create a new ASP.NET Core MVC web application. Please refer to this Microsoft Learn page for information on how to create an ASP.NET Core MVC web app in Visual Studio. Next, install the NuGet package for Serilog.Extensions.Logging.File. Specifically, click on Tools > Nuget Package Manager > Manage NuGet packages for Solution, then search for it in “Browse” tab. After the NuGet package is installed, in Program.cs, get an instance of the ILoggerFactory and call the “AddFile()” function to set the file path where the logs will be stored:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
builder.Services.AddControllersWithViews();
 
var app = builder.Build();
 
app.Services.GetRequiredService<ILoggerFactory>().AddFile("Logs/mylog-{Date}.txt");
 
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
 
app.UseHttpsRedirection();
app.UseStaticFiles();
 
app.UseRouting();
 
app.UseAuthorization();
 
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
 
app.Run();

In this case, there will be a Logs folder in the root directory of the project, and the log file will be inside the Logs folder. Let’s test it out. In Controllers > HomeController.cs, add the following snippet to do some logging:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
 
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
 
    public IActionResult Index()
    {
        _logger.LogInformation("Home page visited at {DT}",
            DateTime.UtcNow.ToLongTimeString());
        return View();
    }
 
    public IActionResult Privacy()
    {
        return View();
    }
}

Build and run the project. You should be able to find the file containing the log in the Logs folder located in the root directory of the project.

Logs Folder
Sample Log File