Logging in ASP.NET Core WebAPI using NLog


Logging is an essential part of any application development process, including web APIs. It helps developers track and analyze the flow of their applications, identify issues, and troubleshoot problems. One popular logging framework in the ASP.NET Core ecosystem is NLog, which provides a flexible and robust logging solution. In this article, we will explore how to implement logging in an ASP.NET Core WebAPI using NLog.

What is NLog?

NLog is a flexible and extensible logging platform for .NET applications. It provides a rich set of features and supports various logging targets, such as files, databases, and email. NLog is highly customizable, allowing developers to configure logging behavior according to their specific requirements.

Setting up NLog in ASP.NET Core WebAPI

To get started with NLog in an ASP.NET Core WebAPI project, follow the steps below:

Step 1. Add NLog dependencies

Begin by adding the required NLog dependencies to your project. In Visual Studio, you can use the NuGet Package Manager to search for and install the following packages:

  • NLog
  • NLog.Web.AspNetCore

These packages provide the core logging functionality and the necessary integration with ASP.NET Core.

Step 2. Configure NLog

Next, create an nlog.config file at the root of your project. This file will define the configuration for NLog, including log targets and rules. Here's a basic example of an 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 -->
		<add assembly="NLog.Extended"/>

		<!-- 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 -->
		<logger name="*" minlevel="Trace" writeTo="logfile" />
        <!-- Other rules can be added here -->

In this example, we define a file target named "logfile" that writes log messages to a file named nlog-YYYY-MM-DD.log inside the logs folder of your application. 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, and the writeTo attribute determines the target(s) to which the log messages should be written.

Step 3. Configure NLog in the ASP.NET Core app

To configure NLog in your ASP.NET Core WebAPI application, open the Program.cs file and modify as follows:

using NLog.Web;

var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    //configure logging
    builder.Services.AddLogging(loggingBuilder =>
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
catch (Exception exception)
    // NLog: catch setup errors
    logger.Error(exception, "Stopped program because of exception");
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)

Step 4. Inject ILogger into controllers or services

To use NLog for logging within your controllers or services, create an instance of the Logger class. For example:

using NLog;

public class SampleController : ControllerBase
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    public IActionResult Get()
        _logger.Info("SampleController: Get method called");

        // ...

        return Ok();

Viewing the Logs

By default, NLog logs are written to the specified file. You can configure additional targets like databases, email, or custom targets based on your application's needs.

To view the logs, you can either open the log file directly or use tools like NLog Viewer, which provides a graphical interface to monitor and analyze the logs.


In this article, we learned how to implement logging in an ASP.NET Core WebAPI using NLog. We set up NLog, configured it to write logs to a file, and used the logging functionality in WebAPI controllers. Logging is an essential aspect of application development, and NLog simplifies the process of logging and log management in ASP.NET Core projects.

Similar Articles