Add File Logging to an ASP.NET Core MVC Application

Introduction

 
One of the most common aspects of any application is the ability to write logs. These not only help to troubleshoot problems that arise out of an application, but also help to keep track of how things are going and take pre-emptive measures to stop problems before they even happen. In this article, we will look at the most common type of logging that we expect to find in any application: and that is a file log. We will see how to implement a file log in an ASP.NET Core MVC application.

Create the project and installing the required NuGet package

 
We first create an ASP.NET Core MVC application using the default template. For this, we will use the Visual Studio 2019 community edition. After the application with its initial framework is created, we will add the “Serilog.Extensions.Logging.File” NuGet package, as shown below:
 
Add File Logging To An ASP.NET Core MVC Application
 
Add File Logging To An ASP.NET Core MVC Application
 
After that, we will add the ILogger factory as a parameter to the Configure function in the Startup class, as shown below:
  1. using System.IO;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.Extensions.Configuration;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. using Microsoft.Extensions.Hosting;  
  7. using Microsoft.Extensions.Logging;  
  8.   
  9. namespace NetCoreMVCLogging  
  10. {  
  11.     public class Startup  
  12.     {  
  13.         public Startup(IConfiguration configuration)  
  14.         {  
  15.             Configuration = configuration;  
  16.         }  
  17.   
  18.         public IConfiguration Configuration { get; }  
  19.   
  20.         // This method gets called by the runtime. Use this method to add services to the container.  
  21.         public void ConfigureServices(IServiceCollection services)  
  22.         {  
  23.             services.AddControllersWithViews();  
  24.         }  
  25.   
  26.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  27.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)  
  28.         {  
  29.             var path = Directory.GetCurrentDirectory();  
  30.             loggerFactory.AddFile($"{path}\\Logs\\Log.txt");  
  31.   
  32.             if (env.IsDevelopment())  
  33.             {  
  34.                 app.UseDeveloperExceptionPage();  
  35.             }  
  36.             else  
  37.             {  
  38.                 app.UseExceptionHandler("/Home/Error");  
  39.                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
  40.                 app.UseHsts();  
  41.             }  
  42.             app.UseHttpsRedirection();  
  43.             app.UseStaticFiles();  
  44.   
  45.             app.UseRouting();  
  46.   
  47.             app.UseAuthorization();  
  48.   
  49.             app.UseEndpoints(endpoints =>  
  50.             {  
  51.                 endpoints.MapControllerRoute(  
  52.                     name: "default",  
  53.                     pattern: "{controller=Home}/{action=Index}/{id?}");  
  54.             });  
  55.         }  
  56.     }  
  57. }  
Here, we have also specified the location where we want the log file to be created. We are now ready to use this logger in our classes. We will see this used in the Home controller, as shown below:
  1. using System.Diagnostics;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.Extensions.Logging;  
  4. using NetCoreMVCLogging.Models;  
  5.   
  6. namespace NetCoreMVCLogging.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         private readonly ILogger<HomeController> _logger;  
  11.   
  12.         public HomeController(ILogger<HomeController> logger)  
  13.         {  
  14.             _logger = logger;  
  15.         }  
  16.   
  17.         public IActionResult Index()  
  18.         {  
  19.             _logger.LogInformation("The main page has been accessed");  
  20.             return View();  
  21.         }  
  22.   
  23.         public IActionResult Privacy()  
  24.         {  
  25.             _logger.LogInformation("The privacy page has been accessed");  
  26.             return View();  
  27.         }  
  28.   
  29.         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
  30.         public IActionResult Error()  
  31.         {  
  32.             return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
  33.         }  
  34.     }  
  35. }  
Now, when we run the application and click on the two links “Home” and “Privacy”, a log file is created in the sub-folder Logs which has the current date and the below contents:
 
Add File Logging To An ASP.NET Core MVC Application
 

Summary

 
In this article, we have looked at how to add file logging to an ASP.NET Core MVC application. We see that it is just a matter of adding a few lines and then we are ready to get useful informational logs. In this article, we added lines in the log file under the “information” heading. We can also add Errors, Warnings, and Debug information. I will leave this to you to further investigate the options you can set in the log file.