Skip to content

Getting started with .NET Core 2 Console application

Rolf Kristensen edited this page Mar 27, 2021 · 16 revisions

⚠️ ASP.NET Core users should use the ASP.NET Core 2 tutorial


Explains how to setup NLog as logging provider for .NET Core and Microsoft Extension Logging (MEL).

Demonstrated with a Console application. Example project can also be found on GitHub.

Notice that NLog can be used on .NET Core without help from Microsoft Extension Logging and NLog.Extension.Logging. See NLog Tutorial for .NET Framework.

0. Create a new .NET Core console project

In Visual Studio 2017, using .NET 4.6.1+ or .NET Core 2


1. Add dependency in csproj manually or using NuGet



    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
    <PackageReference Include="NLog" Version="4.6.5" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.5.1" />

2. Create a nlog.config file.

Create nlog.config (lowercase all) file in the root of your application project (File Properties: Copy Always)

We use this example:

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema:>
<nlog xmlns="" xsi:schemaLocation="NLog NLog.xsd"
      internalLogLevel="Info" >

  <!-- the targets to write to -->
    <!-- write logs to file -->
    <target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log"
            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
    <target xsi:type="Console" name="logconsole"
            layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />

  <!-- rules to map from logger name to target -->
    <logger name="*" minlevel="Trace" writeTo="logfile,logconsole" />

It is recommended to read the NLog Tutorial. For more detailed information about config file can be found here.

If you like to include other targets or layout renderers, check the Platform support.

Ensure to configure your project-file to copy NLog.config to the output directory:

     <None Update="nlog.config" CopyToOutputDirectory="Always" />

3. Update your program

3.1 Create your runner class

 public class Runner
     private readonly ILogger<Runner> _logger;

     public Runner(ILogger<Runner> logger)
         _logger = logger;

     public void DoAction(string name)
         _logger.LogDebug(20, "Doing hard work! {Action}", name);

3.2 Setup the Dependency injector (DI) container

private static IServiceProvider BuildDi(IConfiguration config)
   return new ServiceCollection()
      .AddTransient<Runner>() // Runner is the custom class
      .AddLogging(loggingBuilder =>
            // configure Logging with NLog

3.3 Add required usings

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;

3.4 Update your main()

First create the DI container, then get your Runner and start running!

static void Main(string[] args)
   var logger = LogManager.GetCurrentClassLogger();
      var config = new ConfigurationBuilder()
         .SetBasePath(System.IO.Directory.GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)

      var servicesProvider = BuildDi(config);
      using (servicesProvider as IDisposable)
         var runner = servicesProvider.GetRequiredService<Runner>();

         Console.WriteLine("Press ANY key to exit");
   catch (Exception ex)
      // NLog: catch any exception and log it.
      logger.Error(ex, "Stopped program because of exception");
      // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)

4 Example output

On screen:


In file:

2017/10/16 23:08:46.479|DEBUG|Doing hard work! Action1 |ConsoleExample.Runner|Action=Action1, EventId_Id=20, EventId_Name=, EventId=20

Configure NLog Targets for output

Next step, see Configure NLog with nlog.config

Clone this wiki locally