Skip to content

Monitor, Troubleshoot, and Optimize Azure Solutions with Application Insights

This guide covers the AZ-204 exam topics for monitoring, troubleshooting, and optimizing Azure solutions using Application Insights, building on our existing TaskManagerWeb (WebApp) and TaskManagerFunctions (Function App). Both apps have Application Insights enabled from their Azure Portal deployment. We'll use these to monitor metrics/logs/traces, implement web tests/alerts, and instrument custom telemetry.

Prerequisites

  • Azure Subscription (Free tier or $200 credit recommended).
  • Existing Resource Group (az204exam).
  • Deployed Apps:
  • WebApp: taskmanagerweb-yourname (ASP.NET Core MVC, Free F1 tier).
  • Function App: taskmanagerfunc-yourname (.NET 8 isolated, Consumption plan).
  • Tools:
  • .NET SDK 8.0: winget install Microsoft.DotNet.SDK.8.
  • Azure CLI.
  • Azure Functions Core Tools.

Monitor and Analyze Metrics, Logs, and Traces

Application Insights is already enabled for both apps, capturing default telemetry (requests, exceptions). We'll analyze this data in the Azure Portal.

Steps

Follow these steps to monitor and analyze metrics, logs, and traces:

  1. Access Application Insights for both apps.

  2. Check metrics for the WebApp and Function App.

  3. Query logs to analyze app behavior.

  4. Verify traces for detailed event tracking.

Step 1: Access Application Insights

  • In the Azure Portal, go to the resource group az204exam.
  • Select Application Insights for taskmanagerweb-yourname (WebApp) and taskmanagerfunc-yourname (Function App). If not visible, find them under each app’s Application Insights settings.

Step 2: Check Metrics

For the WebApp:

  • Go to Metrics > Select Server requests > Filter by cloud_RoleName == "taskmanagerweb-yourname".
  • Verify request counts, response times, and failure rates for GET /.

For the Function App:

  • Select Function Execution Count > Filter by cloud_RoleName == "taskmanagerfunc-yourname".
  • Check executions for CreateTask or ManageTask (e.g., POST /api/managetask).

Step 3: Query Logs

In Application Insights, go to Logs and run the following queries:

  • WebApp: requests | where cloud_RoleName == "taskmanagerweb-yourname" | summarize count() by timestamp (shows request trends).
  • Function App: traces | where cloud_RoleName == "taskmanagerfunc-yourname" and message contains "Creating new task" (logs from CreateTask).

Save queries for reuse.

Step 4: Verify Traces

For the WebApp:

  • In Logs, run traces | where cloud_RoleName == "taskmanagerweb-yourname" to see request traces (e.g., page loads, form submissions).

For the Function App:

  • Check traces | where message contains "Processing task in Cosmos DB" (from ManageTask).

Confirm traces show up in Transaction search for specific actions (e.g., POST requests).

Why

Analyzing metrics (requests, performance), logs (app behavior), and traces (detailed events) ensures we understand app health, a core AZ-204 skill.

Implement Application Insights Web Tests and Alerts

We'll set up a web test for the WebApp’s availability and create alerts for both apps to monitor issues.

Steps

Follow these steps to implement web tests and alerts:

  1. Create a web test for the WebApp.

  2. Set up alerts for both apps.

  3. Verify the web test and alert functionality.

Step 1: Create a Web Test

In Application Insights for taskmanagerweb-yourname, go to Availability > Add classic test. Configure:

  • Test type: URL ping test.
  • URL: https://taskmanagerweb-yourname.azurewebsites.net.
  • Frequency: Every 5 minutes.
  • Locations: Select 3 (e.g., West US, East US, West Europe).
  • Success criteria: HTTP 200, timeout < 30s.

Save and run the test. Check results in Availability after 10-15 minutes.

Step 2: Set Up Alerts

For the WebApp:

  • Go to Alerts > Create alert rule.
  • Condition: Availability test failures > 0 in last 5 minutes.
  • Action: Select Log alert to Azure Monitor (no email setup needed for exam prep).
  • Name: WebAppAvailabilityAlert.

For the Function App:

  • Go to Application Insights for taskmanagerfunc-yourname > Alerts > Create alert rule.
  • Condition: Server response time > 3 seconds for CreateTask or ManageTask.
  • Action: Log to Azure Monitor.
  • Name: FunctionResponseTimeAlert.

Test alerts:

  • Temporarily stop the WebApp (via Overview > Stop) to trigger the availability alert.
  • Simulate slow Function App responses (e.g., add delay in code, redeploy, and test).
  • Check Alerts > View alerts for triggered rules.

Step 3: Verify

  • In WebApp’s Application Insights, confirm Availability shows test results (green for success, red for failures).
  • In Alerts, ensure rules logged incidents during tests.

Why

Web tests validate app uptime, and alerts enable proactive issue detection, both critical for the exam.

Instrument an App or Service to Use Application Insights

Automatic instrumentation captures basic telemetry. We'll add custom telemetry to track specific actions in both apps.

Instrument WebApp

Follow these steps to instrument the WebApp with custom telemetry:

  1. Add the Application Insights SDK.

  2. Update the HomeController to track custom events and page views.

  3. Test locally.

  4. Deploy to Azure.

  5. Verify custom telemetry in Application Insights.

Step 1: Add Application Insights SDK

In the TaskManagerWeb directory, add the SDK.

dotnet add package Microsoft.ApplicationInsights.AspNetCore

Step 2: Update HomeController.cs

Modify Controllers/HomeController.cs:

using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;
using TaskManagerWeb.Models;
using System.Collections.Generic;

namespace TaskManagerWeb.Controllers
{
    public class HomeController : Controller
    {
        private static List<TaskItem> _tasks = new List<TaskItem>();
        private readonly TelemetryClient _telemetryClient;

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

        public IActionResult Index()
        {
            _telemetryClient.TrackPageView("TaskManagerIndex");
            return View(_tasks);
        }

        [HttpPost]
        public IActionResult Create(string title, string description, string dueDate)
        {
            _telemetryClient.TrackEvent("TaskCreated", new Dictionary<string, string> { { "Title", title } });
            var task = new TaskItem
            {
                Title = title,
                Description = description,
                DueDate = dueDate
            };
            _tasks.Add(task);
            return RedirectToAction("Index");
        }
    }
}

Step 3: Test Locally

Run the WebApp locally to test.

cd TaskManagerWeb
dotnet run

Access https://localhost:5001, create a task, and reload the page.

Step 4: Deploy

Deploy to Azure.

az webapp up --name taskmanagerweb-yourname --resource-group az204exam

Test at https://taskmanagerweb-yourname.azurewebsites.net.

Step 5: Verify

In Application Insights for taskmanagerweb-yourname, go to Events.

  • Search for TaskCreated (filter by event name) and TaskManagerIndex (under Page Views).
  • Confirm properties like Title appear for TaskCreated.

Instrument Function App

Follow these steps to instrument the Function App with custom telemetry:

  1. Add the Application Insights SDK (already included for .NET isolated Functions).

  2. Update ManageTask.cs to track custom events and metrics.

  3. Test locally.

  4. Deploy to Azure.

  5. Verify custom telemetry in Application Insights.

Step 2: Update ManageTask.cs

Modify ManageTask.cs:

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Cosmos;
using Microsoft.ApplicationInsights;
using System.Diagnostics;

namespace TaskManagerFunctions
{
    public class ManageTask
    {
        private readonly ILogger<ManageTask> _logger;
        private readonly CosmosClient _cosmosClient;
        private readonly TelemetryClient _telemetryClient;

        public ManageTask(ILogger<ManageTask> logger, TelemetryClient telemetryClient)
        {
            _logger = logger;
            _telemetryClient = telemetryClient;
            _cosmosClient = new CosmosClient(Environment.GetEnvironmentVariable("CosmosDBConnection"), new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct });
        }

        public class TaskItem
        {
            public string id { get; set; } = Guid.NewGuid().ToString();
            public string Title { get; set; }
            public string Description { get; set; }
            public string DueDate { get; set; }
        }

        [Function("ManageTask")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", "get")] HttpRequest req)
        {
            _logger.LogInformation("Processing task in Cosmos DB.");
            var stopwatch = Stopwatch.StartNew();

            var container = _cosmosClient.GetContainer("TasksDB", "Tasks");

            if (req.Method == "POST")
            {
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                TaskItem task = JsonConvert.DeserializeObject<TaskItem>(requestBody);

                if (string.IsNullOrEmpty(task?.Title))
                {
                    return new BadRequestObjectResult("Please provide a title.");
                }

                task.id = Guid.NewGuid().ToString();
                await container.CreateItemAsync(task, new PartitionKey(task.id));
                stopwatch.Stop();
                _telemetryClient.TrackMetric("TaskCreationTime", stopwatch.ElapsedMilliseconds);
                _telemetryClient.TrackEvent("TaskCreatedInCosmos", new Dictionary<string, string> { { "Title", task.Title } });
                _logger.LogInformation($"Created task: {task.Title}");
                return new OkObjectResult(task);
            }
            else // GET
            {
                string taskId = req.Query["taskId"];
                if (string.IsNullOrEmpty(taskId))
                {
                    return new BadRequestObjectResult("Please provide taskId.");
                }

                try
                {
                    var task = await container.ReadItemAsync<TaskItem>(taskId, new PartitionKey(taskId));
                    _logger.LogInformation($"Read task: {task.Resource.Title}");
                    return new OkObjectResult(task.Resource);
                }
                catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return new NotFoundResult();
                }
            }
        }
    }
}

Step 3: Test Locally

Update local.settings.json (if needed):

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "CosmosDBConnection": "[your-connection-string]"
    }
}

Run the Function locally to test.

func start

POST a task:

curl -X POST http://localhost:7071/api/ManageTask -H "Content-Type: application/json" -d '{"Title":"Cosmos Task","Description":"Test SDK","DueDate":"2025-04-15"}'

Step 4: Deploy

Deploy to Azure.

func azure functionapp publish taskmanagerfunc-yourname

Test:

curl -X POST https://taskmanagerfunc-yourname.azurewebsites.net/api/managetask?code=[your-key] -H "Content-Type: application/json" -d '{"Title":"Azure Cosmos","Description":"Deployed","DueDate":"2025-04-15"}'

Step 5: Verify

In Application Insights for taskmanagerfunc-yourname:

  • Go to Metrics > Filter for TaskCreationTime.
  • Go to Events > Search for TaskCreatedInCosmos and check properties (e.g., Title).
  • Confirm logs in Logs with traces | where message contains "Created task".

Why

Custom instrumentation tracks specific behaviors (e.g., task creation, performance), exceeding auto-instrumentation and meeting exam requirements.

Verify All Topics

  • Metrics/Logs/Traces: Confirmed via Portal queries and Transaction search.
  • Web Tests/Alerts: Set up and tested for WebApp availability and Function App performance.
  • Instrumentation: Added custom events (TaskCreated, TaskCreatedInCosmos) and metrics (TaskCreationTime) to both apps.

Clean Up (Optional)

To avoid costs, delete all resources:

az group delete -n az204exam --no-wait --yes

Next Steps

  • Review telemetry in Application Insights to prepare exam-style questions.
  • Move to "Connect to and consume Azure services and third-party services" (e.g., integrate with Microsoft Graph or APIs).