Quick Overview:
The blog helps you learn about the procedure to implement NLog in the ASP.NET Core project fully. You will perform every step necessary to implement the logging logic in the application, causing it to store the logs in a text file. From creating a project from scratch and testing it, you will find every necessary aspect in this guide.

Configuring NLog with ASP.NET Core

When any .NET application goes live and if it encounters an unexpected error, the support team first checks the logs. It helps them to escalate the issue and identify the root cause of the problem. However, if there is no mechanism that stores the logs, then it can be a highly time-consuming and cost-consuming task.

For every business to resolve application complexity within minimal time, we recommend fully integrating NLog with ASP.NET Core applications. NLog in ASP.NET Core helps to store logs in an easy-to-read format, helping to identify the cause seamlessly.

To learn this logging framework for .NET, continue with this blog. It will aid you in understanding its working and complete implementation procedure.

What is NLog in ASP.NET Core?

NLog is a freely available technology that fully integrates with the .NET framework, .NET standard, and other .NET-based technologies. Its primary purpose is to help store the application logs in a file, database, and console. .NET professionals consider it a highly popular platform due to its high performance and easy integration curve.

The NLog platform is compatible with the following .NET technologies:

  • .NET 5
  • .NET 6
  • .NET Standard 2.0
  • .NET Core up to 3.1 version
  • Mono 4
  • ASP.NET Core
  • ASP.NET Classic
  • Xamarin Android
  • Xamarin iOS
  • UWP

In addition, the top features of the NLog logging framework for .NET applications are listed below:

  • You can change its configuration on the go. It means that you don’t need to restart the application to let it work.
  • You can use the layout renders to template the log messages.
  • It enables the addition of custom layouts and targets to fulfill business requirements.
  • It supports structured logging and enables the management of log event properties.
  • You can configure it using two methods per convenience. The first method uses the appSettings.json file, and the other uses NLog.Config XML file.

The Procedure To Fully Implement NLog in ASP.NET Core

To learn the configuration of NLog, we’ll be creating an ASP.NET Core Web API project using the Visual Studio IDE. 2019 or later, the version of the IDE is preferred, as it comes with all required mechanisms and a built-in NuGet package manager.

The procedure to create an ASP.NET Core project is pretty streamlined. You only need to open the Visual Studio IDE, select the project from the provided template, fill in the details, and lastly, hit the create button. Once the Web API project is generated, follow the below procedure, which is divided into five phases for better insight.

Ready to Build an ASP.NET Core Web Applications for Your Organization?

Empower your organization with custom ASP.NET Core Web Applications crafted by our team of 10+ years of experienced .NET developers. Let’s build excellence together!

Phase 1: Creating the Projects

Besides our main API project, we’ll need two more projects to learn the NLog configuration and work. Now, you should create two projects with the names “Contracts” and “LoggerService.” The Contract project will be used inside the main project for storing interfaces. The LoggerService will be used for implementing the logging logic.

To create the project, follow the below steps.

  • Step 1: Go to the solutions window and right-click on it.
  • Step 2: Select the “Add” button and, under it, “New Project.
  • Step 3: Select the “Class Library” option and set its name as “Contracts.”
  • Step 4: Now repeat the step 1 to 3 for creating the “LoggerService” project.

After you create both projects, reference them to the main project. You can do it by following the procedure.

  • Step #1: In the solutions explorer, go to the main project.
  • Step #2: Use right-click on the main project and select Dependencies.
  • Step #3: Select the “Add Project Reference” option.
  • Step #4: Choose the “Solution” option, available under Project.
  • Step #5: Select the LoggerService project option. As a result, a reference will be created.

Now, perform the same procedure, but this time, instead of the main project, add the “Contracts” reference to the “LoggerService” project.

Phase 2: NLog Installation and Interface Development

In the logger service, we’ll be implementing the four methods, which will log the info, debug, warning, and error messages. The interface (ILoggerManager) for all these four methods will be created inside the “Contracts” project.

Now, execute the following steps.

Step 1: Create an ILoggerManager interface with the following code block.

namespace Contracts
{
    public interface ILoggerManager
    {
        void LogInfo(string message);
        void LogWarn(string message);
        void LogDebug(string message);
        void LogError(string message);
    }
}

Before this interface is configured inside the LoggerService project, you should install the NLog.

Step 2: Right-click on the LoggerService >> Dependencies >> Manage NuGet Packages. It will open the NuGet manager window. You need to input the framework name below to find and install it.

NLog.Extensions.Logging

Besides, there’s an alternative way of installing this platform. By navigating to View >> Other Windows >> Package Manager Console. It will open a command line interface, on which you need to run the following command.

Install-Package NLog.Extensions.Logging

You will have your NLog mechanism installed and ready to use within a few minutes. You can use any of the installation methods at your convenience.

Phase 3: NLog.Config File and Interface Implementation

To implement the interface created in Phase 2, follow the below-listed steps.

1: Inside the LoggerService project, create a new class file with the name “LoggerManager.

2: Modify the LoggerManager class file with the below code.

using Contracts;
using NLog;

namespace LoggerService
{
    public class LoggerManager : ILoggerManager
    {
        private static ILogger logger = LogManager.GetCurrentClassLogger();

        public void LogDebug(string message) => logger.Debug(message);

        public void LogError(string message) => logger.Error(message);

        public void LogInfo(string message) => logger.Info(message);

        public void LogWarn(string message) => logger.Warn(message);
    }
}

3: In the main project, create a text file that will store the logs created by the NLog mechanism. Name the file “nlog.config” in the main project and populate it.

Further, add the following code to the file. But ensure that you change the “filename” and “internal log” parameters per your system specifications.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="d:Projects\Blog-AccountOwner\Project\internal_logs\internallog.txt">

  <targets>
    <target name="logfile" xsi:type="File"
            fileName="d:/Projects/Blog-AccountOwner/Project/logs/${shortdate}_logfile.txt"
            layout="${longdate} ${level:uppercase=true} ${message}"/>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="logfile" />
  </rules>
</nlog>

Phase 4: Logging Server Configuration

To configure the Logger Service, follow the below-listed steps.

Step 1: Open the “Program” class and modify it per the following code.

using NLog;
var builder = WebApplication.CreateBuilder(args);
LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));

If you are utilizing the .NET 5 version, modify the “Startup” constructor as follows.

public Startup(IConfiguration configuration)
{   
    LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
    Configuration = configuration;
}

Step 2: Inside the .NET Core IOC container, add the logger service. You can do it by calling the service through the following three ways.

  • builder.Services.AddScoped: It will call the service and create an instance for every HTTP request received by the application.
  • builder.Services.AddSingleton: It will call and create the instance only once. Further, the same instance will be shared every time an HTTP request is received.
  • builder.Services.AddTransiet: It calls and creates a service instance for every component in the request. For instance, if four components are requesting service through one HTTP request, the app will create four instances instead of one.

So, you should add any of the methods in the “ServiceExtensions” class. In this tutorial, we are using the builder.Services.AddSingleton method.

public static void ConfigureLoggerService(this IServiceCollection services)
{
    services.AddSingleton<ILoggerManager, LoggerManager>();
}

Step 3: Now, invoke this extension method in the Program class by using the below code.

builder.Services.ConfigureLoggerService();

You need to put this code above the “builder.Services.AddControllers()” method. Mainly, here, we have taken the benefit of DI (dependency injection). It helps ASP.NET Core applications to automatically call the service from the IOC (Inversion of Control) container.

Phase 5: Testing the NLog Configuration

After completing all the above four phases, you should test the ASP.NET Core logging using the NLog. But, before you run the application, navigate to Main Project >> Controllers folder >> WeatherForecastController.cs.

Open the WeatherForecastController.cs and modify it per the following code.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILoggerManager _logger;

    public WeatherForecastController(ILoggerManager logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<string> Get()
    {
        _logger.LogInfo("Here is info message from the controller.");
        _logger.LogDebug("Here is debug message from the controller.");
        _logger.LogWarn("Here is warn message from the controller.");
        _logger.LogError("Here is error message from the controller.");

        return new string[] { "value1", "value2" };
    }
}

Now, run the application and open the http://localhost:5000/weatherforecast. On the output screen, an array of strings will be displayed. But you should check the “nlog.config” file in the main project. If this file contains the logs, then you have successfully implemented the NLog logging framework for .NET applications.

Similarly, you can use NLog for other projects to store the logs and make your development and troubleshooting tasks effortless.

Concluding Up on Implement NLog in ASP.NET Core

NLog is considered a reliable platform for fulfilling the requirements of logging info, debugging, errors, alerts, and other log messages. You can install it using the NuGet Package Manager for ASP.NET Core applications. In the practical example above, we implemented it for a .NET Core Web API project, resulting in the storage of all logs in a file with a path defined in the business logic.

For enterprise software, logging is crucial, as it assists in efficiently troubleshooting and resolving errors. Also, it supports developers in checking the functionality of each application component. So, you should always consider implementing NLog in ASP.NET Core applications, as it provides an efficient logging framework to log errors and application workflow in ASP.NET Core web apps. Implementing NLog in ASP.NET Core ensures robust logging for enterprise-level web applications.

Parag Mehta

Verified Expert in Software & Web App Engineering

Parag Mehta, the CEO and Founder of Positiwise Software Pvt Ltd has extensive knowledge of the development niche. He is implementing custom strategies to craft highly-appealing and robust applications for its clients and supporting employees to grow and ace the tasks. He is a consistent learner and always provides the best-in-quality solutions, accelerating productivity.

Hire Best Web Application Development Company

Related Posts