Performance Counters with NLog

I spotted that NLog have a Windows Performance Counter target and decided to give it a whirl.

I'm currently working heavily with windows performance counters using a framework called PerfIt! and wanted to see if there was an easier to configure solution.

Grab the source code here:

Install-Package NLog
Install-Package NLog.Config
Install-Package Topshelf

Using the topshelf getting started guide I created a quick example app which would write an INFO level log every second.

public class Program
  public static void Main()
    HostFactory.Run(x =>
      x.Service<Service>(s =>
        s.ConstructUsing(name => new Service());
        s.WhenStarted(tc => tc.Start());
        s.WhenStopped(tc => tc.Stop());

      x.SetDescription("Ex Topshelf Host");

public class Service
  readonly Timer _timer;
  private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
  public Service()
    _timer = new Timer(1000) { AutoReset = true };
    _timer.Elapsed += (sender, eventArgs) => _logger.Info("This is an info log message");
  public void Start() { _timer.Start(); }
  public void Stop() { _timer.Stop(); }

The real magic happens in the target file. This is where the counters are created using the
autoCreate flag.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="" xmlns:xsi="" xsi:schemaLocation=" NLog.xsd" autoReload="true" throwExceptions="true" internalLogLevel="Info" internalLogFile=".\nlog-internal.log">

     counterHelp="This was created by NLog"
     incrementValue="1" />

   <target xsi:type="Console" name="console" detectConsoleAvailable="true" />

   <logger name="*" minlevel="Debug" writeTo="perf" />
   <logger name="*" minlevel="Debug" writeTo="console" />

When you put this all together, you get automatically created Performance Counters (available after you've restarted your console of course).

> Get-Counter -ListSet *example*

CounterSetName     : ExampleCategoryName
MachineName        : .
CounterSetType     : SingleInstance
Description        : Category created by NLog
Paths              : {\ExampleCategoryName(*)\Alexw.Example}
PathsWithInstances : {\ExampleCategoryName(logwritten)\Alexw.Example}
Counter            : {\ExampleCategoryName(*)\Alexw.Example}