Logging in Asp.net Core example

Here you learn how to create logs in asp.net core application and some asp.net core logging best practices.

Logging is one of the very important functionalities in software development, Asp.net Core Logging can be used for various reason, but most of the time we use logging function for User Activity logging and Error Logging, You can use logging anywhere you want.

In Asp.net Core we have built-in logging apart from third party logging utility like Log4net. ASP.NET Core logging framework is not as feature-rich as third party libraries, So let’s understand how much we can do with Asp.Net Core built-in Logging

Asp.net Core Logging Example

Asp.Net Core Built-in Logging:
Before we learn about Logging implementation in Asp.Net Core, let’s understand important logging classes, interface and functions in Asp.Net Core Framework.

To use Logging, we need to add namespace Microsoft.Extensions.Logging . We learn about ILoggingFactory, ILoggingProvider, ILogger, LoggingFactory Logging is done using ILogger extension methods:

  • LogDebug()
  • LogInformation()
  • LogWarning()
  • LogError()
  • LogCritical()
asp.net core logging appsettings.json

Setting up code in asppsetting.json

{
      "Logging": {
        "IncludeScopes": false,
            "LogLevel": {
              "Default": "Debug",
              "System": "Information",
              "Microsoft": "Information"
                }
            }
    }

Now setup ILoggerFactory in Configure method of Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            //removed all other code for clarity
        }
asp.net core logging dependency injection

We need to use ILogger, ILoggerFactory using dependency injection in constructor

Now open your controller class and use dependency injection through constructor, you can do that in two ways
public class homeController : Controller
  {
    ILogger _logger;
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
    //you can have either one
    public HomeController(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger(typeof(HomeController));
    }
    public IActionResult index()
    {
        _logger.LogInformation("just testing LogInformation()");
        _logger.LogError("There is no error, just testing LogError()");
        return View();
    }
}

Log4net for Asp.net core logging

How to use third party logging utility like Log4Net with Asp.net Core.

Tough Asp.Net Core has built-in Logging mechanism, but I still prefer Log4Net net because of many option of logging and easy to implement.

Here are the few simple steps to implement Log4Net in your Asp.net Core application.

Step 1
Install Log4Net utility using NugetPackage
Right Click on your project => Manage NuGet Package =>

log4net asp.net core configuration

Step 2
Create a xml file in root of the application with name "log4net.config"

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingFile" />
</root>
<appender name="RollingFile" type="log4net.Appender.FileAppender">
<file value="D:\example.log" /> 
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
</layout>
</appender>
</log4net>
</configuration>

Make sure you change the file tag value, mention your file path, where you want file to be created.

Step 3
Now setup log4net Repository in Program.cs file

public class Program
    {
       public static void Main(string[] args)
        {
           var log4netRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
            log4net.Config.XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config"));
            BuildWebHost(args).Run();
        }
}

Step 4
Now open your controller class and setup _log4net local object, so you can access all log4net methods in this controller, for example we have called _log4net.Info() method in index.

public class HomeController : Controller
    {
 static readonly log4net.ILog _log4net = log4net.LogManager.GetLogger(typeof(HomeController));
public IActionResult index()
    {
            _log4net.Info("Hello logging world log4net!");
            return View();
    }
}

Now run the application, and to check if log details written properly in file you mentioned in <file value="D:\example.log" /> tag

Hope this was helpful!

Asp.Net Core C# Examples | Join Asp.Net MVC Course