Post

Azure | Setting Up a Health Check API with Application Insights in ASP.NET Core and Deploying to Azure

In this guide, we’ll build a Health Check API in ASP.NET Core, integrate it with Application Insights for logging and monitoring, and then deploy the application to Azure for real-time monitoring. By the end of this post, you’ll have a fully operational health check API, complete with logging and monitoring in the Azure portal.


Step 1: Set Up Application Insights in Azure

  1. Go to the Azure Portal: Sign in at https://portal.azure.com.
  2. Create an Application Insights Resource:
    • Go to Create a resource > Monitoring > Application Insights.
    • Fill in the Name, Region, and Resource Group.
    • Choose ASP.NET Core as the Application Type.
  3. Create the Resource: Once the resource is created, navigate to it and copy the Instrumentation Key or Connection String from the Overview or Properties tab.

Step 2: Add Application Insights to the ASP.NET Core Application

Install the Application Insights SDK

First, add the Application Insights package to your ASP.NET Core project:

1
dotnet add package Microsoft.ApplicationInsights.AspNetCore

Configure Application Insights in appsettings.json

In appsettings.json, add the Instrumentation Key or Connection String:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "ApplicationInsights": {
    "InstrumentationKey": "YOUR_INSTRUMENTATION_KEY_OR_CONNECTION_STRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Register Application Insights in Program.cs

In ASP.NET Core 6 and later, configure services in Program.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Microsoft.ApplicationInsights.AspNetCore.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Register Application Insights
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["ApplicationInsights:InstrumentationKey"]);

// Register Health Check Service
builder.Services.AddScoped<IHealthCheckService, HealthCheckService>();

// Add controllers
builder.Services.AddControllers();

var app = builder.Build();
app.MapControllers();
app.Run();

This configuration registers Application Insights and maps the controllers to expose the API endpoints.


Step 3: Build the Health Check API

3.1 Create the Health Check Response Model

Create a model to represent the health check response:

1
2
3
4
5
6
7
8
9
10
// Models/HealthCheckResponse.cs
namespace HealthCheckAPI.Models
{
    public class HealthCheckResponse
    {
        public string Status { get; set; }
        public string Message { get; set; }
        public DateTime Timestamp { get; set; }
    }
}

3.2 Create the Health Check Service

This service contains the logic for the health check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Services/HealthCheckService.cs
using HealthCheckAPI.Models;
using Microsoft.ApplicationInsights;

namespace HealthCheckAPI.Services
{
    public interface IHealthCheckService
    {
        HealthCheckResponse CheckHealth();
    }

    public class HealthCheckService : IHealthCheckService
    {
        private readonly TelemetryClient _telemetryClient;

        public HealthCheckService(TelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
        }

        public HealthCheckResponse CheckHealth()
        {
            var response = new HealthCheckResponse
            {
                Status = "Healthy",
                Message = "Application is running smoothly.",
                Timestamp = DateTime.UtcNow
            };

            // Log a custom event to Application Insights
            _telemetryClient.TrackEvent("HealthCheckPerformed", new Dictionary<string, string>
            {
                { "Status", response.Status },
                { "Timestamp", response.Timestamp.ToString() }
            });

            return response;
        }
    }
}

3.3 Create the Health Check Controller

The controller exposes the health check endpoint:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Controllers/HealthCheckController.cs
using HealthCheckAPI.Models;
using HealthCheckAPI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace HealthCheckAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HealthCheckController : ControllerBase
    {
        private readonly IHealthCheckService _healthCheckService;
        private readonly ILogger<HealthCheckController> _logger;

        public HealthCheckController(IHealthCheckService healthCheckService, ILogger<HealthCheckController> logger)
        {
            _healthCheckService = healthCheckService;
            _logger = logger;
        }

        [HttpGet]
        public ActionResult<HealthCheckResponse> Get()
        {
            _logger.LogInformation("Health check requested.");

            var response = _healthCheckService.CheckHealth();

            // Log result of the health check
            _logger.LogInformation("Health check status: {Status}", response.Status);

            return Ok(response);
        }
    }
}

Step 4: Test and Monitor Logs in Azure

Test the Health Check Endpoint

To test the API, make a GET request to /api/healthcheck:

1
GET https://your-app-url/api/healthcheck

You should receive a response like:

1
2
3
4
5
{
  "status": "Healthy",
  "message": "Application is running smoothly.",
  "timestamp": "2023-10-15T14:23:45Z"
}

Monitor Logs in the Azure Portal

  1. Go to Application Insights: Open the Application Insights resource in the Azure portal.
  2. View Logs:
    • Go to Logs and use Kusto Query Language (KQL) to query the health check logs:
      customEvents
      | where name == "HealthCheckPerformed"
      | order by timestamp desc
      
  3. View Real-time Metrics:
    • Navigate to Live Metrics to monitor incoming requests and health check statuses in real-time.

Step 5: Deploy to Azure

5.1 Deploy the Application to Azure App Service

Option 1: Deploy Using Visual Studio

  1. Right-click on your project in Solution Explorer and select Publish.
  2. Choose Azure App Service and select Create New to create a new App Service.
  3. Select the Subscription, Resource Group, and App Service Plan (or create a new one).
  4. Click Publish to deploy the application to Azure.

Option 2: Deploy Using Azure CLI

  1. Build and publish the application:
    1
    
    dotnet publish --configuration Release --output ./publish
    
  2. Create an Azure App Service (if not already created):
    1
    
    az webapp up --name YourAppName --resource-group YourResourceGroup --plan YourAppServicePlan
    
  3. Deploy the application: Upload the content of the ./publish folder to the Azure App Service.

Step 6: Set Up Alerts (Optional)

  1. Navigate to Application Insights: Open your Application Insights resource in the Azure portal.
  2. Go to Alerts: Select Alerts from the left-hand menu.
  3. Create a New Alert:
    • Choose + New Alert Rule.
    • Define the Condition, such as a health check failure or performance threshold.
    • Set the Action Group to notify you via email or other channels.

Conclusion

You have now built a Health Check API in ASP.NET Core, integrated it with Application Insights for logging and monitoring, and deployed it to Azure App Service. Additionally, you can monitor the health of your application in real-time using Application Insights in the Azure portal and set up alerts for issues.

Recap:

  • Health Check API: Exposes an endpoint to check the health of the application.
  • Application Insights: Logs health check events and provides performance and failure metrics.
  • Azure Deployment: Deploys the application to Azure for real-time monitoring.

With these steps, you’re equipped to monitor your application’s health efficiently and react to potential issues proactively.

This post is licensed under CC BY 4.0 by the author.