Logging is an integral element of the development process for all applications, including web APIs. It assists developers in monitoring and analyzing the flow of their applications, identifying issues, and resolving issues. NLog is a prominent logging framework in the ASP.NET Core ecosystem, providing a robust and flexible logging solution. This article examines how to implement monitoring in an ASP.NET Core WebAPI with NLog.

What exactly is NLog?

NLog is an adaptable and extensible platform for logging in.NET applications. It supports multiple logging destinations, including files, databases, and email. NLog is extremely configurable, enabling developers to configure logging behavior based on their particular needs.

Configuring NLog for ASP.NET Core WebAPI
Follow the steps below to get started with NLog in an ASP.NET Core WebAPI project:

Step 1. Add NLog dependencies
Add the required NLog dependencies to your project to get started. The NuGet Package Manager in Visual Studio can be used to search for and install the following packages:
NLog NLog.Web.AspNetCore

These packages provide the essential monitoring functionality and ASP.NET Core integration.

Step 2. Configure NLog

Create a nlog.config file in the project's root directory. This file defines NLog's configuration, including log targets and rules. Here is an example of a simple 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"
    autoReload="true" internalLogLevel="Trace" internalLogFile="${basedir}\logs\internallog.log" throwConfigExceptions="true">
    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Extended"/>
    </extensions>

    <targets>
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="logfile" fileName="${basedir}/logs/nlog-${date:format=yyyy-MM-dd}.log"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
        <!-- Other targets like console, database, etc. can be added here -->
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="logfile" />
        <!-- Other rules can be added here -->
    </rules>
</nlog>

In this example, we define a file target called "logfile" that writes log messages to a file named nlog-YYYY-MM-DD.log within your application's logs subdirectory. You can add more targets such as console, database, or email as per your requirements. The minlevel attribute specifies the minimum log level to be captured, whereas the writeTo attribute specifies the destination(s) to which log messages should be written.

Step 3. Configure NLog within the ASP.NET Core application.
To configure NLog within your ASP.NET Core WebAPI application, open the Program.cs file and make the following modifications:
using NLog.Web;

val logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // To learn more about configuring Swagger/OpenAPI, visit https://aka.ms/aspnetcore/swashbuckle. builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //Configure logging. build
     loggingBuilder.ClearProviders(); loggingBuilder.AddNLog(); ); var app = builder.Build(); // Configure the request pipeline for HTTP requests.
    if (app.Environment.IsDevelopment())
     app.UseSwagger(); app.UseSwaggerUI(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); app.UseSwaggerUI();
rescue (Exception error)
// NLog: capture configuration error
    logger.Error(exception, "Stopped program because of exception"); throw;
finally
// Ensure internal timers/threads are flushed and terminated prior to application termination (Avoid segmentation fault on Linux).
    NLog.LogManager.Shutdown(); }


4. Inject ILogger into controllers or services using C#
Create an instance of the Logger class within your controllers or services to use NLog for logging. For instance:
using NLog;

[ApiController] [Route("api/[controller]")]
public class SampleController inherits from ControllerBase; private static read-only Logger = LogManager.GetCurrentClassLogger();

    public IActionResult Get() _logger; [HttpGet].Example: Info("SampleController: Get method called");

        // ...

        return Ok(); } }


NLog entries are written to the specified file by default. Depending on the requirements of your application, you can configure additional targets, such as databases, email, and custom targets.

To view the logs, you can either manually open the log file or use tools such as NLog Viewer, which provides a graphical interface for monitoring and analyzing the logs.

This article demonstrated how to use NLog to implement logging in an ASP.NET Core WebAPI. We installed NLog, configured it to write logs to a file, and implemented logging in WebAPI controllers. NLog simplifies the process of logging and log administration in ASP.NET Core projects, which is an essential aspect of application development.