File Logging using NLog in ASP.NET Core

In this post, we will understand how to enable File Logging using NLog in ASP.NET Core and do customization to existing behavior using an example.

In the last article, we saw how to Enable Logging in to .NET Core API using built-in Providers.

We also learned the technique of using Serilog for ASP.NET Core WebAPI file logging requirements.

Today in this article, we will cover below aspects,

We found and understood that the File logging provider is still not available through .NET Core framework and we need to rely on external solutions.

Microsoft recommends using a third-party logger framework like a Serilog or NLog for other high-end logging requirements like Database or File/Rolling File logging.

Getting started

Create an API using .NET Core 3.1 or .NET 6 project template


Please add below NuGet Packages using Nuget Manager,

Or

Install-Package NLog.Web.AspNetCore -Version 4.8.6

Configure the NLog in Main() method

Please update the Main method for adding the file logging as shown in the below-highlighted code in Program.cs

public static void Main(string[] args)
        {

            // NLog: setup the logger 
            var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("Init-Start");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Something went wrong !");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads
                NLog.LogManager.Shutdown();
            } 
        }

Enable NLog Logging

Update the CreateHostBuilder() method for nLog as below,

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();

and you are done!!

Lets now use the logging-in controller using the regular ILogger Interface.

Here below controller uses the ILogger interface using Dependency injection.

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly ILogger _logger;

        public ValuesController(ILogger<ValuesController> logger)
        {
            _logger = logger;
        }
        // GET api/values
        [HttpGet("{id}")]
        public ActionResult<IEnumerable<string>> Get(int id)
        {
           _logger.LogInformation("Start : Getting item details for {ID}", id);

            List<string> list = new List<string>();
            list.Add("A");
            list.Add("B");

            _logger.LogInformation("Completed : Item details for {ID}", list);
            return list;
        }
        
    }

Once the code is executed the log file will be created in the specified path and logging will be captured as shown below figure.

You can enable logging on any controller and another layer of your API like the Business or domain layer easily using DI (dependency injection).

Logging can be enabled right from Startup.cs and Program.cs files as to any other layer of an application.

Below is an example of file logging,

File Logging using NLog in ASPNET Core

That’s all!

For the above sample, I have used the below appsettings.json file for log configurations,

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Sample nlog.config file is as below,

<?xml version="1.0" encoding="utf-8"?>
<configuration>

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

    <!-- enable asp.net core layout renderers -->
    <extensions>
      <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <!-- the targets to write to -->
    <targets>
      <!-- write logs to file  -->
      <target xsi:type="File" name="allfile" fileName="nlog-thecodebuzz-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
      <!--All logs, including from Microsoft-->
      <logger name="*" minlevel="Trace" writeTo="allfile" />

      <!--Skip non-critical Microsoft logs and so log only own logs-->
      <logger name="Microsoft.*" maxlevel="Info" final="true" />
      <!-- BlackHole without writeTo -->
      <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>
  </nlog>

</configuration>

It supports multiple configurations and all configurations can be easily managed using the above config file.

The logger file will be created in the project output directory.

Custom log file path can be provided using the below for fileName property in the config file,

<target xsi:type="File" name="allfile" fileName=" C:\Test\nlog-thecodebuzz-${shortdate}.log "

Other useful references:

One can use the same concept for .NET Core Console application logging as well.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

It’s very easy to configure file logging in .NET Core WebAPI using NLog. File logging provider is not yet available through the .NET Core framework and certainly, we need to depend on custom or any existing external solutions. NLog helps us enable logging in a few simple steps and address the file-based logging need easily.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.