Logging with NLog and Papertrail with C#

In this post I’m going to spend some time discussing logging with NLog and Papertrail within C#. Logging is a must have item in any software program for a variety of reasons. Logging can help you determine when issues are occurring in real time and what is causing the issue. Logging is also useful for tracking user actions and for security auditing. This post isn’t about providing reasons for why you should be using logging, rather it is to provide some examples on ways to use logging with NLog and Papertrail.

If you aren’t familiar with Papertrail I highly recommended you check out their site. They have a free trial to get started so there’s no excuse not to try it. If you have a distributed system or utilize more than 1 server for your application then you will love Papertrail as it aggregates all your logs in one place and you can easily search through all the logs.

As great as Papertrail is, you probably don’t want to use it in development or staging. So what do you do when you are running your app in one of those environments? Your best bet is to log to text files when in development and staging and then update your app.config files to write messages to Papertrail when in production.

Here is a sample configuration when working in development and staging. You can read up on all the rules and configuration settings for NLog on their github page

Here is an example configuration in production:

Please note that your papertrail settings will be slightly different as you will need to replace the port number with the port number that papertrail provides you when you create your account. One thing you might be wondering is how to update your config files to change the configuration when moving from staging to production. There are many methods for modifying config files but in this case I’m going to show an example of using rake tasks to update the config file. Remember, the below are just examples and they are not meant to be used in your rake file, however you can feel free to use this logic as a starting point for your own rake tasks.

Hopefully the code above makes sense. As you probably noticed, the Nokogiri gem is being used. If you decide to copy the code above make sure you install the Nokogiri gem or the code will definitely not work. There is definitely some refactoring that can be done with the code above but for simplicity sake it made sense to just hard code some things within this example.

That’s it for this post. Hope it was helpful.

Posted in C#, Tools Tagged with: , ,

Leave a Reply