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; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- 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");
- // 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.UseEndpoints(endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }


radhakrish nanPosted Oct 20, 2021, 7:43 AM
Nice and simple understanding article.
Mohammad BarbastPosted Sep 13, 2021, 11:14 AM
It's better to use `AppContext.BaseDirectory` instead of `Directory.GetCurrentDirectory()`
Mohammad BarbastPosted Sep 13, 2021, 11:14 AM
Nice post.
lrbt csharpcornerPosted Dec 24, 2020, 1:47 PM
This is very good example, what if I want to do it in controller
Goutham KsPosted May 13, 2020, 9:41 AM
Informative article. Thanks for sharing Munib.