Adding logging to file in ASP.NET MVC Core using Serilog

24. April 2020

Open the Project.csproj file and add the following code

<PackageReference Include="Serilog.Extensions.Logging.File" Version="1.0.1"/>

Or you can open up the nuget Package Manager Console and write this command and press enter 

Install-Package Serilog.Extensions.Logging.File

 Or you can open the Powershell in goto the directory of your project and run this command 

dotnet add package Serilog.Extensions.Logging.File

This will automatically add the dependencies

 

Now open the Startup.cs file add the following code

loggerFactory.AddFile("Logs/myapp-{Date}.txt");

And do remember to add the IloggerFactory loggerFactory parameter in Configure method parameters list . Line mentioning the file path is where the file will be created for logging.

 

 

Add the following code to your controller

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {

            _logger.LogInformation("Message displayed : " + $"HomePage visited at {DateTime.UtcNow.ToLongDateString()} , {DateTime.UtcNow.ToLongTimeString()}");
            return View();
        }
}

Now you run the application and whenever you browse to the Index method of Home controller the log file will be appended .

Now check Logs Folder which contains the file with Date suffixed

 

 

ASP.NET MVC Core, Logging, Serilog , ,

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading