Integrating Azure Smart Detector Alerts with Google Chat: A Complete Implementation Guide

Integrating Azure Smart Detector Alerts with Google Chat: A Complete Implementation Guide

In modern DevOps environments, quick notification of system issues is crucial. Let’s explore how to integrate Azure Smart Detector Alerts with Google Chat using Azure Functions, enabling real-time monitoring notifications directly in your team’s chat space.

Prerequisites

  • Azure subscription
  • Google Workspace account
  • Visual Studio 2022 (Or any other IDE of your choice)
  • NET 8.0 SDK

Project Setup

  1. Create new Azure Functions project in Visual Studio
  2. Select .NET 8 Isolated worker process
  3. Name it “GoogleChatIntegration”

Required NuGet Packages

  • Microsoft.Azure.Functions.Worker
  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Hosting
  • Microsoft.Azure.Functions.Worker.ApplicationInsights

Project Structure

GoogleChatIntegration/

├── Functions/

│   └── SmartDetectorAlert.cs

├── Models/

│   ├── Alert.cs

│   └── ResponseMessage.cs

├── Program.cs

└── README.md

Let’s implement each component step by step.

Implementation

1. Configure Function Host

First, set up Program.cs to configure dependency injection and services:

using Microsoft.Azure.Functions.Worker;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

var host = new HostBuilder()

    .ConfigureFunctionsWebApplication()

    .ConfigureServices(services =>

    {

        services.AddApplicationInsightsTelemetryWorkerService();

        services.ConfigureFunctionsApplicationInsights();

        services.AddHttpClient();

    })

    .Build();

host.Run();

This setup:

  • Configures the isolated worker process
  • Adds Application Insights for monitoring
  • Registers HttpClient for Google Chat communication
  • Sets up dependency injection

2. Alert Models

Create the models to handle Azure alerts:

public class Alert

{

    public string SchemaId { get; set; }

    public AlertData Data { get; set; }

}

public class AlertData

{

    public Essentials Essentials { get; set; }

    public AlertContext AlertContext { get; set; }

}

public class Essentials

{

    public string AlertId { get; set; }

    public string AlertRule { get; set; }

    public string Severity { get; set; }

    public string SignalType { get; set; }

    public string MonitorCondition { get; set; }

    public string MonitoringService { get; set; }

    public List<string> AlertTargetIDs { get; set; }

    public List<string> ConfigurationItems { get; set; }

    public string OriginAlertId { get; set; }

    public string FiredDateTime { get; set; }

    public string Description { get; set; }

    public string EssentialsVersion { get; set; }

    public string AlertContextVersion { get; set; }

}

3. Google Chat Message Model

Create ResponseMessage.cs for formatting Google Chat messages:

public class ResponseMessage

{

    public string text { get; set; }

}

4. Smart Detector Alert Function

Implement the core functionality in SmartDetectorAlert.cs:

public class SmartDetectorAlert

{

    private readonly ILogger<SmartDetectorAlert> _logger;

    private readonly HttpClient _httpClient;

    public SmartDetectorAlert(ILogger<SmartDetectorAlert> logger, HttpClient httpClient)

    {

        _logger = logger;

        _httpClient = httpClient;

    }

    [Function("SmartDetectionRule")]

    public async Task<IActionResult> SmartDetectionRule(

        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)

    {

        _logger.LogInformation("C# HTTP trigger function processed a request.");

        var googleSpaceUrl = Environment.GetEnvironmentVariable("GOOGLE_SPACE_URL")

            ?? throw new InvalidOperationException("GOOGLE_SPACE_URL environment variable is not set.");

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

        _logger.LogTrace($"Received request body: {requestBody}");

        try

        {

            var options = new JsonSerializerOptions

            {

                PropertyNameCaseInsensitive = true

            };

            var requestData = JsonSerializer.Deserialize<Alert>(requestBody, options);

            if (requestData?.Data?.Essentials?.Description != null)

            {

                var messageText = $"Alert: {requestData.Data.Essentials.AlertRule} - {requestData.Data.Essentials.Description}";

                var responseMessage = new ResponseMessage { text = messageText };

                var json = JsonSerializer.Serialize(responseMessage);

                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(googleSpaceUrl, content);

                if (response.IsSuccessStatusCode)

                {

                    _logger.LogInformation($"Message sent to Google Chat successfully: {responseMessage.text}");

                    return new OkObjectResult($"Message sent to Google Chat successfully: {responseMessage.text}");

                }

                else

                {

                    _logger.LogError($"Error: {response.StatusCode}");

                    return new StatusCodeResult((int)response.StatusCode);

                }

            }

            else

            {

                _logger.LogWarning("Deserialized data is missing expected properties");

                return new BadRequestObjectResult("Invalid alert data structure");

            }

        }

        catch (JsonException ex)

        {

            _logger.LogError($"JSON Deserialization error: {ex.Message}");

            return new BadRequestObjectResult($"Error parsing JSON: {ex.Message}");

        }

    }

}

Configuration Steps

1. Google Chat Setup

  1. Open Google Chat
  2. Navigate to your desired space
  3. Click the space name to open settings
  4. Select “Apps & integrations”
  5. Click “Add webhooks”
  6. Name your webhook (e.g., “Azure Alerts”)
  7. Save and copy the webhook URL

2. Azure Function Configuration

  1. Create Function App in Azure Portal:
    • Runtime stack: .NET 8 Isolate
    • Operating System: Linux
    • Plan type: Consumption (Serverless)
  2. Configure application settings:
    • Name: GOOGLE_SPACE_URL
    • Value: Your Google Chat webhook URL
  3. Enable Application Insights
  4. Note the Function URL and key for later use

3. Azure Smart Detector Setup

  1. Navigate to Azure Portal > Your Resource
  2. Select “Alerts” under Monitoring
  3. Click “New alert rule”
  4. Choose “Smart Detection” as signal type
  5. Configure conditions based on your monitoring needs
  6. Create action group:
  • Type: Webhook
  • Name: GoogleChatWebhook
  • URL: Your Azure Function URL with function key
  • Enable Common Alert Schema

Testing

  1. Use the Test button in Action Group
  2. Monitor function logs in Application Insights
  3. Check Google Chat for the test notification
  4. Review alert history in Azure Portal

Security Best Practices

  • Store sensitive URLs in Azure Key Vault
  • Use Function-level authorization
  • Implement IP restrictions if needed
  • Regularly rotate function keys
  • Monitor function access logs

Monitoring Best Practices

  • Set up Application Insights alerts
  • Monitor function execution times
  • Track webhook response times
  • Set up availability tests

This integration provides real-time monitoring alerts directly in Google Chat, helping teams stay informed about critical system events. The solution is scalable and can be extended to handle different types of Azure alerts.

Stay tuned for our next post about deploying this solution using Azure DevOps Pipelines!

Leave a Comment

Your email address will not be published. Required fields are marked *