If you aren’t familiar with Slack it is a relatively new tool centered around team communication and collaboration. At KiZAN we utilize Slack on several projects to collaborate with clients on a daily basis. Besides collaboration Slack offers a large library of “out of the box” integrations and a full featured api. These integrations are something that developers can easily take advantage of. If you follow me on Twitter you may have read tweets by me where I am giddy with excitement about Hangfire. Hangfire is another tool for developers to add to their tool belts that assists with the processing of background jobs. So what happens when you want to be proactive about exception handling in your background jobs? (Who am I kidding – we never have exceptions!) Enter the subject of this post: Logging Hangfire Exceptions in Slack
Before we get started we are going to use one more tool in this example – NLog. NLog is my logging framework of choice but you can use whatever you want and achieve the same results (log4net, Serilog, Elmah, etc.)
Logging Hangfire Exceptions in Slack
Step 1: Create the Webhook
The first step in this process is to log into slack and navigate to configure integrations and find the Incoming Webhook.
Select view and then choose the channel you want to use to post your messages to. Slack will give you more options and customizations that you can do such as setting up and icon, customizing the name, etc. The most important piece of information we will need here is the Webhook Url. This url will be used for logging Hangfire exceptions in Slack. If you want to learn more about the other integrations Slack offers take a look at their Getting Started documentation.
Step 2: Implement the Custom NLog Target
For our second and final step we will assume that you’ve got your Hangfire Service already up and running. If you don’t have it up and running then go do that now and come back (seriously do it – it only takes a few minutes if you follow the Quick Start guide). This step requires minimal setup. The first thing we do is derive a class from the TargetWithLayout class from NLog and override the Write method. As you can see from the code snippets below we use this target to send our message to the Webhook Url we configured earlier!
The last item of business here is that we need to configure the new Slack Target. This is done the same way you setup other targets with NLog (see the method in our bootstrap class).
Step 3: Profit
Now that you are Logging Hangfire Exceptions in Slack you can sit back, relax, and customize your Slack messages even more! If you are interested in just how much you can customize and add to your Slack Post Model take a look here.