Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 17: ASP.NET Core Add log4Net Support To NorthwindCafe

Wednesday, August 28, 2019

Hour 17: ASP.NET Core Add log4Net Support To NorthwindCafe

A lot of examples on logging in ASP.NET Core shows you how to add console logging to your ASP.NET Core application.  But it's pretty useless in a real world application.  What you really want is to write to a file or a database.  There's a package called Microsoft.Extensions.Logging.Log4Net.AspNetCore that will make your application use log4Net.

Here are the steps to use log4Net:

1.  Right click on your NorthwindCafe.Web project and select "Manage NuGet Packages"

Managing Nuget Packages With Visual Studio





























2. Search for Microsoft.Extensions.Logging.Log4Net.AspNetCore

Search Nuget Package Manager for Microsoft.Extensions.Logging
















3. Click "Install", click "OK" on the preview changes pop-up, and click on "Accept" on the license screen

Install Microsoft.Extensions.Logging Package

























4.  Create a file call log4net.config in the root folder of the project with the following markup

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="NorthwindCafe.log" />
     <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

5. Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net

First you have to import the package using Microsoft.Extensions.Logging; using the using statement

Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace

public void Configure(IApplicationBuilder appIHostingEnvironment envNorthwindContext contextMicrosoft.Extensions.Logging.ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseMvc(config => {
                config.MapRoute(
                    name"Default",
                    template"{controller}/{action}/{id?}",
                    defaultsnew { controller = "Home"action = "Index" }
                    );
            });

            DbInitializer.Initialize(context);
        }

6.  Now go to the HomeController and add log4net to it by injecting it in the constructor

        private ILogger<HomeController> _logger;

public HomeController(IProductRepository repositoryILogger<HomeControllerlogger)
        {
            _repository = repository;
            _logger = logger;
        }

The entire HomeController code should look like this up to this point.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NorthwindCafe.Web.Data;

namespace NorthwindCafe.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly IProductRepository _repository;
        private readonly ILogger<HomeController_logger;

        public HomeController(IProductRepository repositoryILogger<HomeControllerlogger)
        {
            _repository = repository;
            _logger = logger;
        }

        public IActionResult Index()
        {
            var products = _repository.GetProducts();

            return View(products);
        }

        public IActionResult About()

        {

            return View();

        }

        public IActionResult Contact()
        {

            return View();

        }
    }
}

7.  Now if you run the application you will see the NorthwindCafe.log file in the application.   You can change the log level in the log4net.config file.

Change log level for log4net




































githubhttps://github.com/techjunkiejh/NorthwindCafe/tree/Hou17

Previous: Hour 16: ASP.NET Core Display Products

2 comments:

Search This Blog