Thursday 18 May 2023

ASP.NET Hosting Tutorial: Introduction To NLog With ASP.NET Core

Leave a Comment
Logging is a very critical and essential part of any software. It helps us in the investigation of the essence of problems. ASP.NET Core has built-in support for logging APIs and is able to work with various logging providers. Using these built-in providers, we can send application logs to one or more destinations and also, we can plug in third-party logging frameworks, such as Serilog, Nlog, etc. In this article, we learn how to implement NLog with ASP.NET Core.


NLog is an open source and flexible framework that works with various .NET platforms including .NET Standard, Full framework (i.e., .NET Framework 4.7), Xamarin (Android and iOS), Windows phone, and UWP. NLog is easy to use and extend. Also, it provides more flexibility in term of configuration. We can also change the logging configuration on-the-fly. The target is used to store, display, and pass the log messages to the provided destination. NLog can write a log to one or more targets at the same time. NLog provides more than 30 targets that include file, event log, database, email, console, etc.

Following are the steps to configure NLog in ASP.NET Core application.
Step 1. Add NLog dependency either manually to csproj file or using NuGet

We can add an NLog dependency using NuGet by executing the following commands.
PM> Install-Package NLog
PM> Install-Package NLog.Web.AspNetCore

The above two commands are used to add dependencies to the csproj file.
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.App" />
  <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
  <PackageReference Include="NLog.Web.AspNetCore" Version="4.5.4" />
  <PackageReference Include="NLog" Version="4.5.4" />
</ItemGroup>

Step 2. Create nlog configuration file
The NLog configuration file is an XML file that contains the settings related to NLog. This file must be named in lower-case and may be put in the root of our project.

There are two main elements required by every configuration: targets and rules. It may also have other elements - such as extensions, include, and variables. These, however, are optional and can be useful in advanced scenarios.

The targets element defines a log target that is defined by a target element. There are two main attributes: name (name of the target) and type (target type such as - file, database, etc.). There are also additional attributes available with the target element but those depend on the target type; for example - target type is a file, we need to define the filename parameter that is used to define the output file name. Apart from this, the target element contains the layout attribute also that defines the logging data format.

The rules element maps the target with log level. It has logger element that contains this mapping. The logger element has following attributes.
    name – name of logger pattern
    minlevel – minimal log level
    maxlevel – maximum log level
    level – single log level
    levels - comma separated list of log levels
    writeTo – comma separated list of targets to write to
    final – no rules are processed after a final rule matches
    enabled - set to false to disable the rule without deleting it

Example
<?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="info" internalLogFile="internalLog.txt">
    <extensions>
        <add assembly="NLog.Web.AspNetCore" />
    </extensions>
    <!-- the targets to write to -->
    <targets>
        <!-- write to file -->
        <target xsi:type="File" name="alldata" fileName="demo-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
        <!-- another file log. Uses some ASP.NET core renderers -->
        <target xsi:type="File" name="otherFile-web" fileName="demo-Other-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    </targets>
    <!-- rules to map from logger name to target -->
    <rules>
        <logger name="*" minlevel="Trace" writeTo="alldata" />
        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" maxLevel="Info" final="true" />
        <loggername="*"minlevel="Trace"writeTo="otherFile-web" />
    </rules>
</nlog>


This file must be available at a place where project's DLL is placed. So, we need to enable the "copy to bin" folder.


Step 3. Configure NLog in application

Using "UseNLog" method, we can add NLog in a request pipeline as a dependency. To catch an error in program class, we can set up a logger class and after initialization of program class, we can safely shut down the log manager.
public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main function");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            logger.Error(ex, "Error in init");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }

    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Information);
            })
            .UseNLog();
}

In the above code, we are also configuring the logging (i.e. SetMinimumLevel). This can be overridden by the appsettings.json file. So, we need to adjust it correctly as we need.

Demo

As we know, Logger is available as DI (dependency injection) to every controller by default, we get an ILogger object in the constructor of the controller class.
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
    public IActionResult Index()
    {
        _logger.LogInformation("HomeController.Index method called!!!");
        return View();
    }
}


Output

The file format can be defined using the layout attribute in a target element.

Summary

NLog is an open source framework for logging. It is easy to configure with ASP.NET Core application. In this article, I have explained about NLog - file logging configuration with ASP.NET Core 2.

Best ASP.NET 7 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 7.0.2 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core 7.0.2, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core 7.0.2 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core 7.0.2. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment