Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#
Tip/Trick

How to NLog (4.2) with Visual Studio 2015

Rate me:
Please Sign up or sign in to vote.
4.69/5 (16 votes)
11 Nov 2015CPOL3 min read 58.4K   1.5K   33   3
This will let you start logging quickly with VS2015 and NLog 4.2.

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

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

Introduction

Time flies, and the previous tip (How to NLog (2.1 & 3.1) with VisualStudio 2013) was getting a bit old, so I found some time to give the new versions a spin. This should get you up and running in no time again.

Background

The reason for my original article was the frustration of not finding anything that was useful and up to date. This one is mainly based on the new, shinny and updated tutorial by the NLog guys (see here). Like the previous, the aim of this article is to get you up and running in no time.

Step 1: Open VS2013, Create a New Console Project

Image 1

Image 2

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 ..."

Image 3

Step 2.1: Get the NLog package

Visual Studio 2015 offers a different manager than 2013. You'll have to type what you search for, and then install it.

Image 4

As an alternative, you can run the following command in the Package Manager Console:

Install-Package NLog.Config 

You're almost there. Your solution should look like this:

Image 5

The last thing you'll have to do is install the NLog.Config (should be the second on your list). This will give you the schema and a default config. Without them, you won't see any logging. Once you do this, you should have something like:

Image 6

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, you will have some sensible defaults and an example that you can use in order to log into a file (just comment out the code, and use it as is, or play around).

I'm assuming you're using the following (you can simply copy paste it into the config file):

XML
<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >

  <targets>
    <!-- Using the colored console as my target-->
    <target xsi:type="ColoredConsole" name="colored_console"/>
  </targets>

  <rules>
    <!-- Writing everything to the cololred console -->
    <logger name="*" minlevel="Trace" writeTo="colored_console"/>
  </rules>
</nlog>

Step 4: Edit Your Main Method

You can simply copy / paste this into your main:

C#
class Program
{
    /*
     * NLog tutorial suggests to use a static Logger, so here it is
     */
    private static Logger logger = LogManager.GetCurrentClassLogger();

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


        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:

Image 7

Congratulations. You're done.

I would suggest having a look at my previous article for some Log Viewers and more links.

Something Extra - Fluent Interface

This isn't really "new", since it's been added around version 3.2, But I never had the time to add it to the previous article, so here it is:

C#
// From the tutorial
logger.Info()
    .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
    .Property("Test", "InfoWrite")
    .Write();

The fluent interface simply let you "chain" your logic, and make it appear as one statement (think about linq, and using the .Where() or the .Select()).

Here's is a simple example of how to have conditional logging, without the extra if (condition) log;

C#
// Simple example of using a conditional write
for (int i = 0; i < 5; i++)
{
    logger.Trace()
          .Message("you'll only see this if `i` is a multiple of 2. i = {0}", i)
          .Property("Test", "boom")
          .WriteIf(i++ % 2 == 0);
}

This should output 3 lines (for i=0, 2 & 4) to our console. (if you're using the code, just uncomment the "FluidMethod()" line, and you'll see it.

Wrap Up

I'm rather impressed with the fact that the developers had time to update the tutorials lately, and even comment on the last article. You should be able to find all that you need in their Github page, and you're welcome to hop on the wagon and help out if you feel like it and have the time. I hope this will help you to get up and running with your logging. Feel free to leave comments and vote.

History

November 11, 2015
  • Initial release

License

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


Written By
Software Developer
Australia Australia
Coding since I Remember myself ... went through Basic on Commodore 64 to C# on a 24 cores AMD cpu... In between worked with c, c++, java, assembler, php, pascal, JavaScript, 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.

Comments and Discussions

 
SuggestionOne more approach using dependency injection Pin
Kiarash Zamanifar5-Jul-18 14:51
Kiarash Zamanifar5-Jul-18 14:51 
Generalvery useful Pin
Southmountain11-Nov-15 8:49
Southmountain11-Nov-15 8:49 
SuggestionNLog.Config depends on NLog Pin
Anders Eriksson11-Nov-15 3:17
Anders Eriksson11-Nov-15 3:17 

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.