NLog Implementation in .Net Core Application

Introduction

NLog is an open-source library. You are not required to do any license-related things if you install the NLog package in your application.

NLog is the logging framework for .Net or .Net Core.

NLog will help you troubleshoot the application error and resolve your problem.

How to install the NLog package into your application?

There are a couple of ways to install the NLog package.

  1. Command
  2. Manually open the Nuget package manager, find NLog, and install.

Command

  • Install-Package NLog.Web.AspNetCore

Manually Install the NLog

  1. Open the project wherever you want to implement NLog.
  2. Right-click on the solution and click on Manage Nuget Packages.
  3. Search in the search box for NLog.Web.AspNetCore.
  4. Select the version based on your application and click on the Install button. Please refer to the below screenshot for more details. 
    NLog.Web.AspNetCore
  5. Once it is installed in your system, you can verify it on the below screenshot. 
    Explorer

NLog provides different logging levels. The following log levels are supported:

  • Info
  • Error
  • Debug
  • Trace
  • Fail
  • Fatal

Initialize the logger in your application.

using Microsoft.AspNetCore.Mvc;
using NLog;

namespace NLogApplication.Controllers
{
    public class ValuesController : ControllerBase
    {
        private readonly Logger _logger;

        public ValuesController()
        {
            _logger = LogManager.GetCurrentClassLogger();
        }
    }
}

Configuring the logger in your application.

You need to create the nlog.config file in your solution.

Once you have created the file, you need to right-click it and select its properties.

Change the build action to None and Copy to Output Directory to Copy always.

The below content would be required for the nlog.config file.

<?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">

  <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>

  <targets>
    <target xsi:type="File"
            name="file"
            layout="${verbose}"
            fileName="nlog.log"            
            archiveFileName="log.{#}.log"
            archiveNumbering="Date"
            archiveEvery="Day"
            archiveDateFormat="yyyyMMdd" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

To demonstrate whether the logs are working or not, you need to run the application.

Try to create one dummy API for that, as below.

using Microsoft.AspNetCore.Mvc;
using NLog;

namespace NLogApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly Logger _logger;

        public ValuesController()
        {
            _logger = LogManager.GetCurrentClassLogger();
        }

        [HttpGet]
        public IActionResult Get()
        {
            _logger.Info("This is the NLog Info.");
            _logger.Debug("This is the NLog Debug.");
            return Ok(DateTime.Now);
        }
    }
}

Build the solution, and if you find any solution errors, please resolve those errors.

Once your solution builds successfully, please run the application.

Once your application will run successfully in your browser, open Swagger or Postman and try to hit the API.

Swagger

Click on the Try it out button in the swagger documentation.

Values

Click on the Execute button.

Once the execution is done, look at the below screenshot.

Execution

For logging regarding verification, you need to follow the below steps.

  1. Right-click on your application in the solution explorer.
  2. Click on the Open Folder in file explorer.
  3. Go to the bin folder.
  4. Go to the Debug folder.
  5. Go to the .net 6.0 folder.
  6. Inside that, you have found the nlog.log file.

Open that file, and seems you see the logs inside that file as below. 

Logs File


Similar Articles