Monthly Archives: July 2015

NLog File Archiving Gotcha

When configuring NLog for your .Net application, you will most probably want to setup some sort of log file archiving features – that’s if you’re using a file based target. Checkout that link if you need some help on how to do this.

If you’re developing an ASP.NET MVC application, you can easily install NLog via NuGet. Be sure to search for NLog Configuration which will install a sample config file for you, along with the NLog library with the core functionality.


Here’s a sample of the default config file that you get from the NuGet package:

This is my slightly customised version:

  • I’ve changed the log file location to be in a directory under C:\logs.
  • Customised the message layout to include such things as the Thread ID, Class name where the message originates and the exception format.
  • This exception format is actually very important. If you don’t explicitly specify the formatter, any exceptions you log will not appear in your log file (or other logging target).
  • Lastly, I’ve added archiving configuration attributes to perform time based file rollover.

This code will work nicely if you’re running your webapp from within Visual Studio. Each day, NLog will rollover the previous days log file, giving it a new name based on yesterdays date:


If, however, you have configured your webapp to be accessible via IIS rather than IIS Express in Visual Studio, you will discover that the log file archiving feature won’t work! What the…!!?? This stumped me for days until I pulled out Sysinternals Process Monitor in the hope it would help me figure things out… and it did. It turns out there was a permissions error and the IIS App Pool process was not allowed to create the new archive file and roll over a new log file for the current day. So I added the right permissions to the C:\logs directory for the App Pool, but that still didn’t work. That’s when I noticed by chance, that in my NLog config file, I only had a relative path specified for the archiveFileName:

instead of the fully qualified path like this:

I then re-ran the webapp and low and behold, the archiving feature worked!

So why then does it work when you run the app from within Visual Studio with just the archive filename declared but not from under the full IIS process?? I actually don’t know. I figured it might be a possible bug, or more likely something related to User Profile loading under IIS and the resulting permissions that are required for the file rollover not being available. But this is definitely a big gotcha if you’re not careful.