Friday, June 22, 2018

Dotnet Core console app with NLOG in Visual Studio Code

In this post I am going to create simple minimalistic dotnet core console application and integrate it with nlog.

Let's create a folder for our project. I am going to name it nlog_console.

$mkdir nlog_console
$cd nlog_console

Now we create dotnet core console app project and if you have Visual Studio Code installed run the second command below.

$dotnet new console
$code . &

Now lets add nlog package to a project.

$dotnet add package nlog

This will add the following code to our project file.

<PackageReference Include="nlog" Version="4.5.6" />

Nlog framework requires configuration file 'nlog.config' to specify logger tagerts and rules. We can copy paste the sample nlog.config file from this github page or use one below.

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

<nlog xmlns=""
xsi:schemaLocation="NLog NLog.xsd"
internalLogLevel="Info" >


<target xsi:type="File" name="file"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
<target xsi:type="Console" name="console"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />

<logger name="*" minlevel="Trace" writeTo="file,console" />


'nlog.config' file need to be copied to destination directory during project build. To achieve it add the code below to a project file.

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

Now we need to add actual logging code to a program. Copy paste the Program class code below.

using System;

namespace dotnetcore_nlog
class Program
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
Console.WriteLine("Hello World!");
log.Trace("Loggin trace.");

To build and run our console app run code below or add launch.json config to Visual Studio Code.

$dotnet build
$dotnet run

You should see the following output and log file created in the same directory as our console app.

2018/06/19 18:48:13.130|TRACE|Loggin trace. |nlog_console.Program|


Show Comments: OR


Post a Comment