How to Implement Logging using nLog in ASP.NET Core Web API

How to Implement Logging using nLog in ASP.NET Core Web API

In this article, I will discuss How to Implement Logging using nLog in the ASP.NET Core Web API Application with Examples. Please read our previous article discussing Logging into a SQL Server Database with Serilog in ASP.NET Core Web API Application. At the end of this article, you will understand the following pointers:

  1. What is nLog, and why is it used in ASP.NET Core Web API?
  2. How do you Configure nLog in an ASP.NET Core Web API?
  3. What is structured logging, and how can you implement it with nLog in ASP.NET Core?
  4. How do you handle exceptions and log them in an ASP.NET Core Web API using nLog?
  5. NLOG with Asynchronous Logging in ASP.NET Core Web API.
  6. Understanding Different Log Levels in NLog.
  7. How do you ensure that logging with nLog in ASP.NET Core does not negatively impact your application’s performance?

What is nLog, and why is it used in ASP.NET Core Web API?

nLog is a free and open-source logging platform for various .NET platforms like .NET Core, .NET Framework, Mono, and Xamarin. It’s widely used for its simplicity in logging and its ability to log to multiple targets (like files, databases, and consoles) simultaneously. It also has powerful logging capabilities, including structured and asynchronous logging. It’s highly configurable, allowing developers to control the detail of what is logged and where through configuration files or programmatically.

In the context of ASP.NET Core Web API, nLog provides a way to log information about the application’s operations, errors, and system behaviors. Here’s why it’s often used in ASP.NET Core Web API Applications:

  • Error Tracking: nLog can be configured to log detailed error information, which is useful for diagnosing issues in production. By logging exceptions and other contextual information, developers can easily pinpoint the source of problems.
  • Performance Monitoring: Logging can help developers to monitor the application’s performance by tracking request durations, response times, and other critical information. This information can be used to identify performance bottlenecks and optimize the API.
  • Debugging: During the application development, nLog can be configured to provide detailed debug information, making it easier to understand the application’s flow and identify errors.
  • Customization and Flexibility: nLog allows for highly customizable logging, enabling developers to log just the right amount of information. This is important in a production environment where too much logging can lead to performance issues, and too little can leave you without enough information to troubleshoot issues.
  • Multiple Target Logging: With nLog, you can log to multiple targets (like a file, database, and console) without changing your application code. This is useful in complex applications where different types of logs may need to be directed to different places for analysis and monitoring.
  • Structured Logging: nLog supports structured logging, which means you can log complex data types in a structured way (i.e., JSON format). 

How do you Configure nLog in an ASP.NET Core Web API?

Configuring NLog in the ASP.NET Core Web API application involves several steps to integrate the logging framework and make it available throughout your application for logging purposes. Let us proceed to understand the step-by-step process of installing and configuring NLog and using NLog to log different types of messages to different outputs in the ASP.NET Core Web API Application.

Install NLog Packages

First, you need to add NLog and its ASP.NET Core integration package to your project. You can do this via NuGet Package Manager or the Package Manager Console.

  • NLog.Web.AspNetCore: This package is for integrating NLog with ASP.NET Core.
  • NLog.Config (optional): This package manages NLog configurations via XML. When you install this package, it will add a config file named NLog.config, where you will do the NLog Configurations. If the NLog.config file is read-only; delete it and add it again.

You can install these packages using the NuGet Package Manager Console with the following commands:

Install-Package NLog.Web.AspNetCore
Install-Package NLog.Config

Configure NLog in ASP.NET Core Web API

If the NLog configuration file (nlog.config) is not created when you install the NLog.Config package, create it in your project. This XML file defines how logging should be handled (e.g., log levels (Trace, Debug, Information, Warning, Error, Fatal), targets (Console, File, Database), and rules ((Ignoring the System, Microsoft Namespaces logs))). Once you create the NLog.config file, and copy and paste the following code.

<?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="Warn"
      internalLogFile="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <target xsi:type="file" name="allfile" fileName="D:/Logs/nlog-all-${shortdate}.log" />
    <target xsi:type="console" name="console" />
    <!-- Ignore Microsoft and System namespaces -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--Ignore Microsoft -->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Ignore System -->
    <logger name="System.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Catch All -->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <logger name="*" minlevel="Debug" writeTo="console" />
  </rules>
</nlog>

This NLog configuration file configures the ASP.NET Core application to manage its logging. Here’s a detailed explanation of its components:

XML Declaration:

<?xml version=”1.0″ encoding=”utf-8″ ?>

This line declares the XML version and the encoding used in the file.

NLog Configuration:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="internal-nlog.txt">

Here,

  • xmlns and xmlns:xsi: These attributes define the XML and the NLog schemas, enabling the file to be validated against the NLog and XML configuration schemas.
  • autoReload: When this property is set to true, NLog will automatically reload the configuration if the file changes, allowing for dynamic changes without restarting the application.
  • internalLogLevel: This sets the log level for internal NLog messages (e.g., errors in logging). Warn means only warnings and higher log-level messages are logged. This will be used if the NLog is misconfigured or when it is unable to log the messages to the target outputs.
  • internalLogFile: Specifies the file name where internal NLog messages are logged. Here, it’s set to internal-nlog.txt. You need to check this file to see why NLog is not working on your project.
Targets:
<targets>
  <target xsi:type="file" name="allfile" fileName="D:/Logs/nlog-all-${shortdate}.log" />
  <target xsi:type="console" name="console" />
  <target xsi:type="Null" name="blackhole" />
</targets>

Targets define where the logs are sent. Each target has a type and a name.

  • file target with name allfile: Logs are written to a text file. The file’s location and name include the date (${shortdate}), making a new log file daily.
  • console target: Logs are sent to the console, which is useful for development environments.
  • Null target with name blackhole: This target discards anything sent to it and is used for filtering out unwanted logs. So, basically, we will use this target to ignore the System, Microsoft, etc. namespaces log messages.
Rules
<rules>
  <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
  <logger name="System.*" minlevel="Trace" writeTo="blackhole" final="true" />
  <logger name="*" minlevel="Trace" writeTo="allfile" />
  <logger name="*" minlevel="Debug" writeTo="console" />
</rules>

Rules map loggers to targets based on logger name and minimum log level. Using the name property, we need to specify the namespace, * means all namespaces. The minlevel attribute is used to specify the Minimum Log level. Similarly, the writeTo attribute is used to specify the target name to which it will send the log messages. In our code, we have configured 4 rules as follows:

  • The first two rules send all logs from Microsoft.* and System.* namespaces to the blackhole target, effectively filtering them out. The final=”true” attribute stops processing further rules for these logs.
  • The next rule sends all logs with a minimum Log Level of Trace (the lowest level, capturing all logs) to the allfile target, meaning they’re saved to the specified file.
  • The last rule sends all logs with a minimum Log Level of Debug (which includes Debug, Info, Warn, Error, and Fatal levels) to the console target, meaning they will be displayed on the Console window.
Modify nlog.config Copy to Output Directory

Ensure that your nlog.config file is set to be copied to the output directory. You can set this in the file properties within Visual Studio or modify the .csproj file to include:

<ItemGroup>
  <None Include="nlog.config">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </None>
</ItemGroup>

The above code snippet is a directive that tells the MSBuild system (which is part of the .NET build process) to always copy the nlog.config file to the output directory whenever the project is built. This is particularly useful for configuration files like nlog.config, which the NLog logging library uses to configure logging behavior. Ensuring it is always present in the output directory means the application can always read its latest settings from this file. This is important for applications that depend on external configuration for behavior at runtime.

Configure NLog as the Logging Provider in Your Application

Please add the following code to the Program.cs file to configure NLog as your application’s logging provider. This typically involves configuring the logging builder to use NLog and specifying the path to nlog.config.

var builder = WebApplication.CreateBuilder(args);

// Configure NLog for ASP.NET Core
builder.Logging.ClearProviders(); // Clears default logging providers.
builder.Host.UseNLog(); // Use NLog as the logging provider.
builder.Logging.ClearProviders();

This line clears all the logging providers that are registered by default in the ASP.NET Core application. ASP.NET Core has several logging providers (like console, debug, etc.). Clearing them ensures that only the logging providers you explicitly configure (in this case, NLog) will be used. This can help with performance and prevent duplicate logging entries from different providers.

The ClearProviders method removes all previously configured logging providers, leaving the logging system clean for you to add your preferred logging framework.

builder.Host.UseNLog();

This line configures the application to use NLog as its logging framework. After clearing the default providers, NLog is added to the application’s logging system, allowing you to use NLog for all logging purposes within your ASP.NET Core application.

Logging in Your Application

Now that NLog is configured, you can inject ILogger<T> into your controllers or services and use it for logging. So, create an empty API Controller named Test and copy and paste the following code:

using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            _logger.LogTrace("This is a Trace log, the most detailed information.");
            _logger.LogDebug("This is a Debug log, useful for debugging.");
            _logger.LogInformation("This is an Information log, general info about app flow.");
            _logger.LogWarning("This is a Warning log, indicating a potential issue.");
            _logger.LogError("This is an Error log, indicating a failure in the current operation.");
            _logger.LogCritical("This is a Critical log, indicating a serious failure in the application.");

            return Ok("Check your logs to see the different logging levels in action!");
        }
    }
}
Run and Test

Run your application and access the above endpoint. You should see logs appearing in your configured sinks, such as the console and log files in the Logs directory. In the Console Window, you will see the following:

How to Implement Logging using nLog in the ASP.NET Core Web API Application with Examples

Now, verify the Logs folder, and with the nlog-all-current date text file should be created, and you should see the following log messages:

How to Implement Logging using nLog in the ASP.NET Core Web API

What is structured logging, and how can you implement it with nLog in ASP.NET Core?

Structured logging is a logging approach that captures logs as structured data rather than simply formatting them as strings. This approach allows for more precise, queryable, and analyzable logs, making it easier to understand complex application behavior, debug issues, and monitor system health. Instead of treating log messages as simple text, structured logging treats them as structured data (e.g., JSON objects), where each piece of information is a key-value pair. 

How to Implement Structured Logging with NLog in ASP.NET Core

Let us see how to implement structured logging with NLog in the ASP.NET Core application. To implement structured logging with NLog, we need to specify a JSON layout for structured logging to ensure logs are structured as JSON objects. For a better understanding, please modify nlog.config file as follows that writes logs to the console and test file in a structured format:

<?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="Warn"
      internalLogFile="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <target xsi:type="file" name="allfile" fileName="D:/Logs/nlog-all-${shortdate}.log">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception:format=ToString}" />
      </layout>
    </target>
    <target xsi:type="console" name="console">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${shortdate}" />
        <attribute name="level" layout="${level}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception:format=ToString}" />
      </layout>
    </target>
    <!-- Ignore Microsoft and System namespaces -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--Ignore Microsoft -->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Ignore System -->
    <logger name="System.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Catch All -->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <logger name="*" minlevel="Debug" writeTo="console" />
  </rules>
</nlog>
Understanding Layout Element

xsi:type=”JsonLayout”: This attribute sets the layout type to JsonLayout, which formats each log entry as a JSON object. The Layout element contains many attribute elements, and each attribute element has two properties, i.e., name and layout, that define the JSON object that will be included in each log entry:

time
  • name=”time”: The name of the attribute in the JSON object.
  • layout=”${longdate}”: The layout or format of the attribute value. ${longdate} is a variable that NLog replaces with the timestamp of when the log entry was created, displayed in a detailed format (e.g., “2024-03-24 18:45:12.345”).
level
  • name=”level”: Specifies that the log level (e.g., Info, Debug, Error) should be included as an attribute in the JSON object.
  • layout=”${level}”: Uses the log level of the log entry as the value.
message
  • name=”message”: Indicates that the log message itself should be included in the JSON object.
  • layout=”${message}”: The actual log message text.
exception
  • name=”exception”: Specifies that exception details (if any) associated with the log entry should be included.
  • layout=”${exception:format=ToString}”: Formats the exception information as a string. The format=ToString option tells NLog to use the full exception message and stack trace.
Logging Structured Data using NLog in ASP.NET Core:

Let us see how to log structured data from the controller and services.

Create a Model and Controller

Let’s assume we are building an API to manage books in a library. First, define a Book model. Add a folder named Models and then a class file named Book.cs within the Models folder. Copy and paste the following code.

namespace LoggingDemo.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public int YearPublished { get; set; }
    }
}

Next, create an API Empty Controller named BooksController within the Controllers folder and then copy and paste the following code, which adds actions to add and retrieve books. Here, we log data in a structured format about the operations being performed:

using LoggingDemo.Models;
using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static readonly List<Book> Books = new List<Book>()
        {
            new Book(){Id = 1001, Title = "ASP.NET Core", Author = "Pranaya", YearPublished = 2019},
            new Book(){Id = 1001, Title = "SQL Server", Author = "Pranaya", YearPublished = 2022}
        };
        private readonly ILogger<BooksController> _logger;

        public BooksController(ILogger<BooksController> logger)
        {
            _logger = logger;
        }

        [HttpPost]
        public IActionResult AddBook([FromBody] Book book)
        {
            Books.Add(book);

            //Structured Logging, i.e., JSON Format
            _logger.LogInformation("Added a new book {@Book}", book);
            return Ok();
        }

        [HttpGet]
        public IActionResult GetBooks()
        {
            //Structured Logging, i.e., JSON Format
            _logger.LogInformation("Retrieved all books. Books: {@Books}", Books);
            return Ok(Books);
        }
    }
}

In the above controller, the AddBook action logs the entire book object as structured data using the @ operator, which tells NLog to treat the book object as structured data rather than converting it to a string. The GetBooks action logs all the books as structured data using the @ operator.

Testing and Observing Structured Logs

Run your application and use a tool like Postman or Fiddler to test the API endpoints. For example, to add a new book, you could POST to https://localhost:7234/api/books with a JSON body:

{
    "id": 1003,
    "title": "C#.NET",
    "author": "Pranaya",
    "yearPublished": 2023
}

Once you access the API with the above request body, you can verify the Console window, and it should display the following message:

Logging using nLog in the ASP.NET Core Web API Application

Now, if you open the txt file, then you will also see the same log as shown in the below image:

Logging using nLog in the ASP.NET Core Web APi

Similarly, you can also check the other GET Endpoint and observe the logs.

How do you handle exceptions and log them in an ASP.NET Core Web API using nLog?

Let’s see an example of how to handle exceptions and log them using NLog in the ASP.NET Core Web API Application. First, modify the TestController as follows. Here, we have handled the exception in the Catch block and then logged it using the logger.

using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                _logger.LogTrace("This is a Trace log, the most detailed information.");
                _logger.LogDebug("This is a Debug log, useful for debugging.");
                _logger.LogInformation("This is an Information log, general info about app flow.");
                _logger.LogWarning("This is a Warning log, indicating a potential issue.");
                _logger.LogCritical("This is a Critical log, indicating a serious failure in the application.");

                //Simulating an error situation
                int x = 10, y = 0;
                int z = x / y;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"This is an Error log, indicating a failure in the current operation.");
            }

            return Ok("Check your logs to see the different logging levels in action!");
        }
    }
}

With the above changes in place, run the application and access the above endpoint. You should see the exception messages as expected.

Implement Global Exception Handling to Handle Unhandled Exception

Let us see how to handle the unhandled expectations and log them using NLog in ASP.NET Core Web API. To achieve this, we can use the ASP.NET Core’s built-in middleware for global error handling to catch and log all unhandled exceptions. Please add the following Custom Middleware to your Main method of Program.cs to include the global exception-handling middleware:

The following code snippet is an example of custom exception handling middleware in an ASP.NET Core Web API application. This middleware is designed to catch unhandled exceptions that occur during HTTP request processing, log these exceptions using NLog, and provide a generic response to the client.

// Global Exception Handler
app.UseExceptionHandler(appBuilder =>
{
    appBuilder.Run(async context =>
    {
        var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
        if (exceptionHandlerFeature != null)
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();
            logger.Error(exceptionHandlerFeature.Error, "Unhandled Exception.");

            // Respond with a generic error message, log details
            context.Response.StatusCode = 500;
            await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
        }
    });
});

Here’s a step-by-step explanation of what the code does:

app.UseExceptionHandler(appBuilder => { … });
  • This is the entry point for configuring exception handler middleware in the application’s request processing pipeline. ASP.NET Core provides this built-in middleware, which catches exceptions thrown by subsequent middleware in the pipeline.
  • The lambda expression appBuilder => { … } is used to configure the behavior of the exception handler.
Inside the Lambda Expression:
  • appBuilder.Run(async context => { … });: This defines a terminal middleware for handling exceptions. The Run method is a way to attach a piece of middleware that doesn’t call the next middleware in the pipeline. The lambda expression passed to the Run method takes the HttpContext as a parameter, allowing you to interact with the incoming HTTP request and the outgoing response.
Inside the Run Method:
  • var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();: This line attempts to retrieve the IExceptionHandlerFeature from the current HTTP context. The IExceptionHandlerFeature is an interface provided by ASP.NET Core that contains information about the thrown exception. 
  • if (exceptionHandlerFeature != null) { … }: This checks if the IExceptionHandlerFeature was successfully retrieved, which indicates that the middleware caught an exception.
Inside the If Block:
  • var logger = NLog.LogManager.GetCurrentClassLogger();: Here, an instance of NLog’s logger is obtained using GetCurrentClassLogger. This logger instance is used for logging messages according to the settings defined in NLog’s configuration (typically nlog.config file).
  • logger.Error(exceptionHandlerFeature.Error, “Unhandled Exception.”);: This line logs the caught exception using NLog, marking it as an error. The first parameter is the exception object itself, and the second parameter is a custom message that we want to include in the log entry.
  • context.Response.StatusCode = 500;: This sets the HTTP status code of the response to 500, indicating an Internal Server Error. This is a generic way to indicate that something went wrong on the server.
  • await context.Response.WriteAsync(“An unexpected fault happened. Try again later.”);: Finally, a generic error message is written to the HTTP response. This message is what the client will see. It doesn’t include specific details about the exception to avoid leaking sensitive information about your application.
Modifying Test Controller:

Let us make our application throw some unhandled exceptions and see whether the custom middleware component handles them and logs the expectation details or not. So, modify the Test Controller as follows: We are throwing an unhandled exception, which the Custom Middleware Component should handle.

using Microsoft.AspNetCore.Mvc;

namespace LoggingDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {

            _logger.LogTrace("This is a Trace log, the most detailed information.");
            _logger.LogDebug("This is a Debug log, useful for debugging.");
            _logger.LogInformation("This is an Information log, general info about app flow.");
            _logger.LogWarning("This is a Warning log, indicating a potential issue.");
            _logger.LogCritical("This is a Critical log, indicating a serious failure in the application.");

            //Simulating an error situation
            int x = 10, y = 0;
            int z = x / y;

            return Ok("Check your logs to see the different logging levels in action!");
        }
    }
}
NLOG with Asynchronous Logging in ASP.NET Core Web API

Implementing NLog with asynchronous logging in the ASP.NET Core Web API Application enhances the application’s performance by offloading the logging tasks to a separate thread. Your application will continue processing the incoming requests without waiting for the logging operations to complete.

To enable asynchronous logging with NLog, please modify the nlog.config file as follows. This configuration enables asynchronous logging (async=”true”) for both the file and console targets.

<?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="Warn"
      internalLogFile="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <target xsi:type="file" name="AsyncFile" async="true" fileName="D:/Logs/nlog-all-${shortdate}.log">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${level}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception:format=ToString}" />
      </layout>
    </target>
    <target xsi:type="console" async="true" name="AsyncConsole">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${shortdate}" />
        <attribute name="level" layout="${level}" />
        <attribute name="message" layout="${message}" />
        <attribute name="exception" layout="${exception:format=ToString}" />
      </layout>
    </target>
    <!-- Ignore Microsoft and System namespaces -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--Ignore Microsoft -->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Ignore System -->
    <logger name="System.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--Catch All -->
    <logger name="*" minlevel="Trace" writeTo="AsyncFile" />
    <logger name="*" minlevel="Debug" writeTo="AsyncConsole" />
  </rules>
</nlog>
Understanding Log levels in nLog:

Understanding the different log levels in NLog is important for using it effectively. Here are the common log levels in NLog, ordered from the least to the most severe:

  1. Trace
  2. Debug
  3. Info
  4. Warn
  5. Error
  6. Fatal

When to use each log level depends on the severity of the information you want to log, and the stage of development or production of your application.

  • Use Trace and Debug Log levels during development to understand how the application is behaving.
  • Use Info Log Level in both development and production to log general operational information.
  • Use Warn Log Level to highlight issues that are not critical but should be investigated.
  • Use Error Log Level to log exceptions or issues that affect the operation but do not cause the application to stop.
  • Use Fatal Log Level to log critical issues that cause the application to terminate.
How do you ensure that logging with nLog in ASP.NET Core does not negatively impact your application’s performance?

When integrating NLog with ASP.NET Core for logging purposes, ensuring minimal performance impact on your application involves several best practices and optimizations. Here are some strategies to help you maintain optimal performance:

  • Use Asynchronous Logging: NLog supports asynchronous logging, which helps offload the logging operations to a separate thread, minimizing the impact on the application’s main thread. This can significantly improve performance, especially under high load. You can enable asynchronous logging in the NLog configuration.
  • Target Configuration: Be strategic about your logging targets. Writing logs to a file or the console is generally faster than logging to a database or over the network. If you need to log to slower targets, consider using asynchronous logging to handle the performance impacts.
  • Log Level Management: Use proper Log Levels. Debug and Trace levels are more verbose and should typically be enabled only during development or troubleshooting. For production environments, use higher log levels like Information, Error, or Warn to reduce the volume of logged information, which in turn reduces the performance overhead.
  • Avoid Complex Data in Logs: Logging complex objects or calling expensive methods within log statements can significantly degrade performance. 
  • Review Logging Needs: Periodically review your logging needs and configuration. Over time, the importance of certain log statements may change. Removing unnecessary log statements or reducing their log level can improve performance.
  • Keep NLog Updated: Ensure you are using the latest version of NLog. Performance improvements and bug fixes in newer versions can improve your application’s logging performance.

In the next article, I will discuss how to log into an SQL Server Database with NLog in an ASP.NET Core Web API Application. In this article, I explain How to Implement Logging using nLog in ASP.NET Core Web API Application with examples. I hope you enjoy this article, How to Implement Logging using nLog in ASP.NET Core Web API Application.

Leave a Reply

Your email address will not be published. Required fields are marked *