Azure Functions and Sentry in Visual Studio 2017

Sentry is a fantastic tool for error tracking in all kinds of applications, including Azure Functions.

I focus primarily on the ASP.NET and ASP.NET Core stack and the integrations couldn’t be easier. I’m building out several Azure Functions projects at the moment in Visual Studio 2017 and wanted to incorporate Sentry to report on exceptions.

The default configuration for .NET Core for Sentry is to incorporate the SDK via the WebHostBuilder in the Progam.cs in the root of your ASP.NET Core web application.

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        // Add this:
        .UseSentry()
        .Build();

Unfortunately, an Azure Functions App doesn’t expose the code used to wire up the WebHost, so the implementation needs to be done within each Function.

Thankfully, the implementation is very simple using the SDK.

How to add Sentry to Azure Functions in Visual Studio 2017

Create a new Azure Functions app

Create a new Function in your Functions App

You will need the Sentry Project’s DSN value. To get this, go to the Settings page of your Sentry project and click on “Client Keys (DSN)” under the SDK Setup heading.

Getting your DSN from a Sentry Project

Once you have your DSN value, create a setting for “SENTRY_DSN” in your local.settings.json file in the root of your Azure Functions Project in VS 2017.

Adding your Sentry DSN in your local.settings.json file

Open your Package Manager console in Visual Studio and enter “Install-Package Sentry.AspNetCore” and press enter to add the Sentry SDK to your project.

The last remaining step is to include Sentry in your function. To do this, just add a using section to your function. You can manually trigger exceptions as well as catch any unhandled exceptions using a Try Catch block

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Sentry;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            using (SentrySdk.Init())
            {
                try
                {
                    //Unhandled divide by zero Exception
                    int myVar = 1;
                    var oops = myVar / 0;

                    //Manual exception
                    throw new Exception("My manually thrown exception");
                }
                catch (Exception ex)
                {
                    SentrySdk.CaptureException(ex);
                }
            }
        }
    }
}

Related Posts

Leave a Reply