Click here to Skip to main content
12,246,406 members (40,961 online)
Click here to Skip to main content
Add your own
alternative version

Stats

45.3K views
1.3K downloads
75 bookmarked
Posted

How to NLog (2.1 & 3.1) with VisualStudio 2013

, 6 Oct 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This will let you start logging quickly with VS2013 and NLog.

You can just download and run these to see how they work.

Note: For a smaller download, I removed the packages from the solution, so the first time you build it, it'll download them from NuGet.

Note: You can find an updated article here: How to NLog (4.2) with VisualStudio 2015.

Introduction

I've been trying to hit the ground running using NLog in order to log messages to the console and/or a file, but ran into wall after wall of things not working. There are plenty of tutorials and blogs and what not, suggesting you do this or that, but most of that data is rather outdated (ranging from 2006 to 2010?), so in order to save others some time, here's the quick setup to get you up and running with NLog and VisualStudio 2013.

Step 1: Open VS2013, Create a New Console Project

Nothing fancy. Name it as you wish, put it where you want.

  • For bonus points: print "hello world!" to the console.

Step 2: Get NLog from NuGet

Go to "Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution ..."

Step 2.1: Get the NLog package

Simple as 1..2..3... Search, point the mouse, click.

Note: Current version is 3.1. This tutorial works just as well with it.

Step 2.2: Get the NLog Configuration

Here's where things deviate a bit from the tutorials I've seen. You'll need to manually add the NLog configurations (which will install the NLog schema as well for you) to your packages:

Without this, you won't be able to do much and you'll get frustrating errors like this:

The reason is (like it suggests) that it can't find the schema. The why is beyond me, but installing the configuration manually will add the needed NLog.xsd schema file and let you code away happily ever after.

NOTE: On NLog 3.1, installing the configuration will install the Schema, but you won't see it in the installed packages. Don't worry, it's still there Smile | :) .

Step 3: Edit your NLog Config

The previous steps should have created a configuration file in your solution called NLog.config. Open it, and have a look inside, it should look like:

<?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">
 
  <targets>
    <!-- add your targets here -->
  
    <!--
    <target xsi:type="File" 
            name="f" 
            fileName="${basedir}/logs/${windows-identity:domain=false}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
     -->
  </targets>

  <rules>
    <!-- add your logging rules here -->
    
    <!--
    <logger name="*" minlevel="Trace" writeTo="f" />
     -->
   
  </rules>
</nlog>

Remove the comments from the default target and rules, and you are ready to start logging to a file.

Step 3.1 Extra Points

If you want to log to the console, you could replace the above (or add, to log to both) with: To your targets section:

<target  xsi:type="Console" 
            name="console" 
            layout="${shortdate} ${level} ${message}" />

And to your rules section:

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

For bonus points, change the Console above with ColoredConsole, and log different types to see the results Smile | :) .

Step 4: Edit Your Main Method

You can simply copy / paste this into your main:

static void Main(string[] args)
{
   /*
    * Welcome to this NLog demo
    */
    Console.Out.WriteLine("Greetings, some loggings is about to take place.");
    Console.Out.WriteLine("");

   /*
    * This creates your logger. 
    * Notice that in the config file we defined that everything should go into the file.
    * (and if you set the console, it'll output to it as well).
    */
    Logger logger = LogManager.GetCurrentClassLogger();

      Console.Out.WriteLine("Let's assume you're going to work, and using the bus to get there:");
      Console.Out.WriteLine("------------------------------------------------------------------");
      logger .Trace("Trace: The chatter of people on the street");
      logger .Debug("Debug: Where are you going and why?");
      logger .Info("Info: What bus station you're at.");
      logger .Warn("Warn: You're playing on the phone and not looking up for your bus");
      logger .Error("Error: You get on the wrong bus.");
      logger .Fatal("Fatal: You are run over by the bus.");
    
    /*
     * Closing app
     */
    Console.Out.WriteLine("");
    Console.Out.WriteLine("Done logging.");
    Console.Out.WriteLine("Hit any key to exit");
    Console.ReadKey();
}

If you followed all the above advice, you should see something like this:

Extracurricular Activity

The following section was removed, but I still highly encourage you to have a look at the official NLog page for levels (here: log levels), and explore them a bit too see what you can achieve with NLog.

I've based the article above on several articles and examples from the net.

The Official Tutorial

  • https://github.com/nlog/nlog/wiki/Tutorial - I simply got frustrated , since it seems rather outdated, and wouldn't work for me. You don't have an EXE installer, and you can't get the Empty NLog Configuration File to work, since it doesn't exist.

CodeProject Tutorial

  • Introduction to NLog - This article has lots of information and would go into the details of what you can do with the configuration files. I highly suggest reading it to get a hang of what's possible with NLog. If you do try to copy code from it, you might need to take care with the casing, for example: change filename TO fileName (that tutorial is 8 years old, and aimed at NLog 1 I think ... ).

Layout Renderes

${shortdate}
${logger}
${stacktrace} 

Log Viewers

You can install some external log views if you want. They will save you looking into the files, or console, by catching the messages and printing them out in a GUI of your choice.

Sentinel

I found [Sentinel] to work. It's not very recent (2011), not very clear (on the set up), but after adding the needed config (they have an example on the site), it's quite straight forward.

For future reference and ease, add to your <targets> section:

<target xsi:type="NLogViewer"
           name="viewer"
           address="udp://127.0.0.1:9999"/>

Add to your <rules> section:

<logger name="*"
           minlevel="Debug"
           writeTo="viewer" />
Harvester

For some reason [Harvester] doesn't seem to work for me.

Some extra research, and here's how to make harvester work for you as well:

Add this above the <targets>:

<extensions>
       <add assembly="Harvester.Integration.NLog, Version=2.0.2.0, Culture=neutral, PublicKeyToken=2335e074c59acad6"/>
   </extensions>

Then add this to the <targets> section:

<target xsi:type="Harvester"
        name="Harvester"
        bufferType="NamedPipeBuffer"
        binding ="\\.\pipe\Harvester"
        mutexName="HarvesterMutex" />

And last, this to your <rules> section:

<logger name="*"
       minlevel="Trace"
       writeTo="Harvester" />

I'm quite sure you can find others out there.

BareTail

This is a little gem I've found about lately. You can find it here . You can download the free version which is the one I'm using ATM.

In contrast to the two above solutions, BareTail will simply monitor a text file for changes. This means that if you are already logging into a text file, you don't need to add another target or worry about installing another program. Simply run this, point it to the text file, and it will monitor it.

It has an option to Follow Tail, which mean it will keep scrolling down when the file grows, and you can easily set the highlights color for any text pattern you want, so you can easily keep tab on whatever you find important for you.

More Articles

Wrap Up

I can't believe there wasn't a single place with all this information to get a quick start logging started. Note that you can also define your loggers in code (look at the CodeProject article I linked above), but I find the configuration (once they work) to be quite easy to work with. I hope this will help you to get up and running with your logging. Feel free to leave comments and vote.

History

November 12, 2015
  • Added link to new article (Nlog 4.2 with VS 2015)
  • Removed Extra curriculum as it might have been too gender based and made some readers feel uncomfortable.
  • minor fixes.
October 6, 2014
  • Updated and tested with NLog 3.1
  • Added BareTail to the log viewers.
  • Changed tracing level on Console from Warn to Trace.
June 16, 2014
  • Thanks for a good spot in the comments, updated "Log.Trace" ... to "logger.Trace" to reflect the correct variable name. (In the download code, it's a bit different, and it's used as "Log" there, being a static global variable).
May 10, 2014
  • Typos
  • Removed packages for smaller download size (NuGet will get them automatically when you first build the project)
May 9, 2014
  • Added Log levels and when to use them
  • Update code with "interactive" demo
April 1, 2014
  • Fixed a typo that might throw an exception
  • Added configuration for Sentinel
  • Added configuration for Harvester
March 26, 2014
  • Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

_Noctis_
Software Developer
Australia Australia
Coding since I Remember myself ... went through Basic on Commodore 64 to C# on an 8 core i7... In between worked with c, c++, java, assembler, php, pascal, JScript, SQL based DB's and a bit of NoSQL as well.

Love software, and I'm usually fidgeting around with technology software and hardware on my free time.

You may also be interested in...

Comments and Discussions

 
Questionone more question Pin
Southmountain19-Mar-16 17:31
memberSouthmountain19-Mar-16 17:31 
AnswerRe: one more question Pin
_Noctis_21-Mar-16 0:30
professional_Noctis_21-Mar-16 0:30 
GeneralMy vote of 5 Pin
bioNuke10-Dec-15 0:40
memberbioNuke10-Dec-15 0:40 
GeneralRe: My vote of 5 Pin
_Noctis_12-Dec-15 22:25
professional_Noctis_12-Dec-15 22:25 
QuestionThank you! Pin
tommy slick8-Jul-15 7:59
membertommy slick8-Jul-15 7:59 
AnswerRe: Thank you! Pin
_Noctis_10-Jul-15 16:09
professional_Noctis_10-Jul-15 16:09 
QuestionNot to be a stick in the mud, but... Pin
Bill Strait28-Jun-15 17:48
memberBill Strait28-Jun-15 17:48 
AnswerRe: Not to be a stick in the mud, but... Pin
_Noctis_29-Jun-15 1:44
professional_Noctis_29-Jun-15 1:44 
GeneralRe: Not to be a stick in the mud, but... Pin
Member 1180018129-Jun-15 3:36
memberMember 1180018129-Jun-15 3:36 
GeneralRe: Not to be a stick in the mud, but... Pin
Joshua “Ominousicity” S29-Jun-15 4:35
memberJoshua “Ominousicity” S29-Jun-15 4:35 
AnswerRe: Not to be a stick in the mud, but... Pin
_Noctis_11-Nov-15 11:09
professional_Noctis_11-Nov-15 11:09 
GeneralMy Vote of 5 Pin
Brisingr Aerowing15-Jun-15 18:08
professionalBrisingr Aerowing15-Jun-15 18:08 
SuggestionMy vote of 5 Pin
J.Verdurmen13-Jun-15 5:04
memberJ.Verdurmen13-Jun-15 5:04 
GeneralRe: My vote of 5 Pin
_Noctis_13-Jun-15 5:32
professional_Noctis_13-Jun-15 5:32 
GeneralRe: My vote of 5 Pin
_Noctis_11-Nov-15 11:13
professional_Noctis_11-Nov-15 11:13 
QuestionError / Missing Step for the NLog.Config Pin
Member 1148011625-Feb-15 10:30
memberMember 1148011625-Feb-15 10:30 
AnswerRe: Error / Missing Step for the NLog.Config Pin
_Noctis_2-Mar-15 1:12
professional_Noctis_2-Mar-15 1:12 
QuestionSchema and NLog.config files Pin
David M Newman14-Jan-15 13:24
memberDavid M Newman14-Jan-15 13:24 
AnswerRe: Schema and NLog.config files Pin
_Noctis_11-Nov-15 11:11
professional_Noctis_11-Nov-15 11:11 
SuggestionMy vote of 5 Pin
Marcin Wronecki16-Jun-14 2:01
memberMarcin Wronecki16-Jun-14 2:01 
GeneralRe: My vote of 5 Pin
_Noctis_16-Jun-14 2:20
member_Noctis_16-Jun-14 2:20 
GeneralMy vote of 5 Pin
Franie9-May-14 6:24
memberFranie9-May-14 6:24 
GeneralRe: My vote of 5 Pin
_Noctis_9-May-14 17:01
member_Noctis_9-May-14 17:01 
Generalmy vote of 5 Pin
Southmountain1-Apr-14 7:08
memberSouthmountain1-Apr-14 7:08 
GeneralRe: my vote of 5 Pin
_Noctis_1-Apr-14 11:30
member_Noctis_1-Apr-14 11:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 6 Oct 2014
Article Copyright 2014 by _Noctis_
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid