Get your web application errors into Slack

Get your devops going by integrating your application into your team communication tooling.

Advertisements

bugbotTo get more out of Slack and your team, you can integrate Slack with your application. Integrating with slack is done with webhooks. In this sample I use a Incoming Webhook to post the messages from the application to slack. By adding a GlobalExceptionFilter to you .Net Core web application, you can get all exceptions that are not handled in your web application.

Setup integration

enterprise-grid-logo@2xGo to the slack website to setup your integration. Here you go to Manage => Custom Integrations => Incoming Webhooks => Add configuration. Here you add the integration and get the Url with the access token. This url let you post messages to the specified slack channel.

Slack client

The slack client get the messages into an payload object and then make a JSON to post it to Slack. When creating the client, you need to specify the url with access token from the Slack website.

 public class SlackClient
    {
        private readonly Uri _uri;
        private readonly Encoding _encoding = new UTF8Encoding();

        public SlackClient(string urlWithAccessToken)
        {
            _uri = new Uri(urlWithAccessToken);
        }

        //Post a message using simple strings
        public void PostMessage(string text, Exception ex, string username = null, string channel = null, string color = "#D00000")
        {
            Payload payload = new Payload()
            {
                Channel = channel,
                Username = username,
                Text = text,
                Color = color,
                Attachments = new Payload.Attach[] {  new Payload.Attach()
                {
                    Title = "Exception: "+ex.Message,
                    Short = false,
                    Value = ex.ToString()
                } }
            };
            PostMessage(payload);
        }

        //Post a message using a Payload object
        public void PostMessage(Payload payload)
        {
            string payloadJson = JsonConvert.SerializeObject(payload);
            using (WebClient client = new WebClient())
            {
                NameValueCollection data = new NameValueCollection();
                data["payload"] = payloadJson;
                var response = client.UploadValues(_uri, "POST", data);
                string responseText = _encoding.GetString(response);
            }
        }

        public class Payload
        {
            [JsonProperty("channel")]
            public string Channel { get; set; }
            [JsonProperty("username")]
            public string Username { get; set; }
            [JsonProperty("pretext")]
            public string Text { get; set; }
            [JsonProperty("color")]
            public string Color { get; set; }
            [JsonProperty("fields")]
            public Attach[] Attachments { get; set; }

            public class Attach
            {
                [JsonProperty("title")]
                public string Title { get; set; }
                [JsonProperty("value")]
                public string Value { get; set; }
                [JsonProperty("short")]
                public bool Short { get; set; }
            }
        }
    }

Global exception filter

public class GlobalExceptionFilter : IExceptionFilter
{
    private readonly ErrorLoggingService _errorLogging;
    public GlobalExceptionFilter(ConfigurationManager configManager)
    {
        this.configManager = configManager;
    }

    public void OnException(ExceptionContext context)
    {
         new SlackClient(configManager.SlackUrl).PostMessage(
                       "I'm reporting a critical exception", context.Exception
                                                        );
    }
}

Register the global exception filter

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(o => { o.Filters.Add(typeof(GlobalExceptionFilter)); });

Now you are ready to test!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s