NLog File logging in Console application .NET Core

NLog File logging in Console application NET Core

Today in this article, we will see how to do traditional logging using NLog File logging in a .NET Core Console application.

In our last article, we already learned how to enable File logging for the ASP.NET Core API template using Serilog and NLog

File/Rolling File logging provider is still not available through the .NET Core Framework. We need to rely on external solutions for highend

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.

Today in this article, we will cover below aspects,

In ASP.NET WebAPI it was easy to configure and use ILogger through DI.

Unlike ASP.NET Core the Console application doesn’t have dependency injection by default. 

ILogger interface works very nicely with the .NET Core ecosystem and today in this post we will learn how to enable logging in a .NET Core Console application.

Getting Started

Create a .NET Core Console application

NLog File logging in Console application NET Core

Here I have used the .NET Core 3.1 or .NET 6 Console application but the below technique will work any lower version of .NET Core also.

Update the Main() method as below,

static void Main(string[] args)
        {
            var services = new ServiceCollection();
            ConfigureServices(services);

            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                MyApplication app = serviceProvider.GetService<MyApplication>();
                app.Run();
            }
        }

The above code demonstrates the basic DI Container which will help us in doing DI( Dependency Injection) of the Logger or Business objects.

Please install below NLog Nuget package

Please install below NLog Nuget package from the Package Manager or package manager console as below,

Install-Package NLog.Extensions.Logging -Version <>

And

 Install-Package NLog.Web.AspNetCore Version <>

Below is the implementation for ConfigureServices() method,

 private static void ConfigureServices(ServiceCollection services)
        {
            services.AddTransient<MyApplication>()
                    .AddScoped<IBusinessLayer, CBusinessLayer>()
                    .AddSingleton<IDataAccessLayer, CDataAccessLayer>();

            services.AddLogging(builder =>
             {
                 builder.SetMinimumLevel(LogLevel.Information);
                 builder.AddNLog("nlog.config");
             });

        }

In the above code, we built the custom Service container.

We added logging and custom Startup MyApplication to ServiceCollection and built the ServiceProvider for the required services which include Serilog object and other business objects.

Implementation for class ‘MyApplication’ as below,

NLog File logging in Console application NET Core

All the logs can be logged easily using the ILogger interface. If you are using any other providers like File or Database etc. The ILogger interface and its Extension methods are generic enough and let you log to appropriate sources.

AddLogging methods let you provide custom configuration for logging if needed.

You can set log severity or type of log that needs to be logged.

Logger customization is easily configured through the NLog.config file.

Please see below the log file example.

Using Generic HostBuilder for DI and logging

If using a generic host builder to configure the IOC container then logging can be achieved very much similar way as discussed above.

Please see this article for more details:

Let’s run the application and check the generated log file.

Define the NLog Configuration file

You can very much control log file structure using NLog.Config file.

It lets you define additional parameters like date format and file layout properties.

Below is an example of a log file which I have used,

<?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" />
    </rules>
  </nlog>

</configuration>

Logfile shall be generated in the app root folder itself if the path is not specified.

NLog File logging in Console application NET Core

Alternatively, you can also use Serilog for Console Application File logging requirements.

References:

That’s all, Hope this is helpful.

Please sound off your comments below.

Summary

File logging provider is not yet available through the .NET Core framework directly we need to depend on available existing external solutions. NLog helps us enable logging in a few simple steps and also addresses the file-logging requirement 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.



2 thoughts on “NLog File logging in Console application .NET Core

  1. Do you have this in Github or something? I’d love to see your references. I installed the NLog packages as described but the builder.SetMinimumLevel is not recognized by NLog, only the microsoft logging framework. Same goes for the parameter in the constructor of MyApplication of type ILogger. If I remove those items and run I get an error on the serviceProvider.GetService line saying “unable to resolve service for type NLog.ILogger”. If I reference the microsoft logging framework then it wants me to use those logging commands. I feel like maybe I’m missing a DI line in my ConfigureServices method but wanted to check your code to see if I wasn’t missing a library or something.

    1. Hello Dan, Thanks for your query. You basically need to add two using references in the code as below,
      [cc lang=”C#”]
      using Microsoft.Extensions.Logging;
      using NLog.Extensions.Logging;
      [/cc]

      Please see here Github codebase NLog File logging in Console App
      Hope this helps. Thanks.

Leave a Reply

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