Generate Alerts in Application insights after querying SQL Table using Azure functions

Viewed 98

I need to make an Azure Durable Function that queries a SQL Database containing details of all transactions, every 24 hours and when some rows indicating transactions failed with an internal server error are found, will create an alert in application insights.

This is how I am querying the database:

public static class Activities
{
    [FunctionName("QuerySQLDatabase")]
    public static async Task<List<SubscriptionsOwnershipTransfer>> QuerySQLDatabase([ActivityTrigger] string temp, ILogger log)
    {
        log.LogInformation("Starting the SQL Query");
 
        string sqlConnectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING");
 
        string[] triggerErrorsList = Environment.GetEnvironmentVariable("TRIGGER_ERROR_CODES")
        .Split(",");

        string sqlQuery = "SELECT [Id], [TransferRequestId], [MOCPSubscriptionGuid], [SourceAccountId], [TargetAccountId]"
            + ", [OperationType] ,[EnrollmentNumber], [ErrorCode], [SubErrorCode], [ErrorMessage], [SystemErrorMessage], [ModifiedOn] "
            + " FROM [dbo].[SubscriptionsOwnershipTransferQueue] "
            + " WHERE ( "
            + string.Join(" OR ",
                 triggerErrorsList
                    .Select(errorCode => $" [ErrorCode]={errorCode} "))
            + " ) AND [ModifiedOn] >= DATEADD(dd, -1, GETDATE()) AND [TransferStatus]=3";
 
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            connection.Open();
        
            using SqlCommand command = new SqlCommand(sqlQuery, connection);
            using SqlDataReader reader = await command.ExecuteReaderAsync();
        
            List<SubscriptionsOwnershipTransfer> transfers = reader.Select(r => new SubscriptionsOwnershipTransfer
            {
                Id = r["Id"] is DBNull ? null : r["Id"].ToString(),
                TransferRequestId = r["TransferRequestId"] is DBNull ? null : r["TransferRequestId"].ToString(),
                MOCPSubscriptionGuid = r["MOCPSubscriptionGuid"] is DBNull ? null : r["MOCPSubscriptionGuid"].ToString(),
                SourceAccountId = r["SourceAccountId"] is DBNull ? null : r["SourceAccountId"].ToString(),
                TargetAccountId = r["TargetAccountId"] is DBNull ? null : r["TargetAccountId"].ToString(),
                OperationType = r["OperationType"] is DBNull ? null : r["OperationType"].ToString(),
                EnrollmentNumber = r["EnrollmentNumber"] is DBNull ? null : r["EnrollmentNumber"].ToString(),
                ErrorCode = r["ErrorCode"] is DBNull ? null : r["ErrorCode"].ToString(),
                SubErrorCode = r["SubErrorCode"] is DBNull ? null : r["SubErrorCode"].ToString(),
                ErrorMessage = r["ErrorMessage"] is DBNull ? null : r["ErrorMessage"].ToString(),
                SystemErrorMessage = r["SystemErrorMessage"] is DBNull ? null : r["SystemErrorMessage"].ToString(),
                ModifiedOn = r["ModifiedOn"] is DBNull ? null : r["ModifiedOn"].ToString()
            }).ToList();

            return transfers;
        }
    }
}

How to create alerts when some row with error is found?

1 Answers

You want to know when your application responded with error code 500 (Internal Server Error). You would create an alert rule with the following details:

requests
| where resultCode == "500"
  • Aggregation granularity: 15 minutes
  • Alert frequency: 15 minutes
  • Threshold value: Greater than 0

Then alert rules monitors for any requests ending with 500 error code. The query runs every 15 minutes, over the last 15 minutes. If even one record is found, it fires the alert and triggers the actions configured.

Refer: Log alerts in Azure Monitor

Related