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:
After that, we will add the ILogger factory as a parameter to the Configure function in the Startup class, as shown below:
- using System.IO;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
-
- namespace NetCoreMVCLogging
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
- {
- var path = Directory.GetCurrentDirectory();
- loggerFactory.AddFile($"{path}\\Logs\\Log.txt");
-
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
-
- app.UseHsts();
- }
- app.UseHttpsRedirection();
- app.UseStaticFiles();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }
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:
- using System.Diagnostics;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- using NetCoreMVCLogging.Models;
-
- namespace NetCoreMVCLogging.Controllers
- {
- public class HomeController : Controller
- {
- private readonly ILogger<HomeController> _logger;
-
- public HomeController(ILogger<HomeController> logger)
- {
- _logger = logger;
- }
-
- public IActionResult Index()
- {
- _logger.LogInformation("The main page has been accessed");
- return View();
- }
-
- public IActionResult Privacy()
- {
- _logger.LogInformation("The privacy page has been accessed");
- return View();
- }
-
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- }
- }
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:
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.