Saturday, 3 October 2020

                                                           Use NLog in project


first install the below  highlighted nlog package using nuget.

step1:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>

    <TargetFramework>netcoreapp3.1</TargetFramework>

  </PropertyGroup>

  <ItemGroup>

    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />

    <PackageReference Include="NLog.Config" Version="4.7.3" />

    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />

  </ItemGroup>

  <ItemGroup>

    <None Update="C:\Users\mukesh\.nuget\packages\nlog.config\4.7.3\contentFiles\any\any\NLog.config">

      <CopyToOutputDirectory>Always</CopyToOutputDirectory>

    </None>

  </ItemGroup>

</Project>

Step 2

Now create the project and create NLOG.config and paste the below code.
and create the folders demologs in c drive 


<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true">
<targets>
<target xsi:type="File" name="fileTarget" fileName="C:\DemoLogs\nlog-all-${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="consoleTarget" />
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="fileTarget" />
</rules>
</nlog>

now create a controller such as a random name and put the code below

Step 3:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Fluent;

namespace NLOG.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NlogController : ControllerBase
    {
        private static ILogger<NlogController> _logger;
        public NlogController(ILogger<NlogController> logger)
        {
            _logger = logger;
        }
        [HttpGet]
        public void Get()
        {
            _logger.LogInformation(" Nlog Controller request");
            int count;
            try
            {
                for (count = 0; count <= 5; count++)
                {
                    if (count == 3)
                    {
                        throw new Exception("Nlog Exception Occured");
                    }
                    else
                    {
                        _logger.LogInformation("Iteration Count is {iteration}", count);
                    }
                }
            }
            catch (Exception ex)
            {

                _logger.LogError(ex, "Exception Caught");
            }
        }
    }
}

Step 4:

configuring in program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace NLOG.WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("Application Starting Up");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog();  // NLog: Setup NLog for Dependency injection
    }
}

output would be like this







No comments:

Post a Comment