使用 Azure Functions 创建和运行自定义可用性测试Create and run custom availability tests using Azure Functions

本文将介绍如何使用 TrackAvailability() 创建一个 Azure 函数,该函数会根据 TimerTrigger 函数中给定的配置和你自己的业务逻辑定期运行。This article will cover how to create an Azure Function with TrackAvailability() that will run periodically according to the configuration given in TimerTrigger function with your own business logic. 此测试的结果将发送到 Application Insights 资源,你可以在其中查询可用性结果数据并对其发出警报。The results of this test will be sent to your Application Insights resource, where you will be able to query for and alert on the availability results data. 这样,你就可以创建自定义测试,类似于通过门户的可用性监视执行的测试。This allows you to create customized tests similar to what you can do via Availability Monitoring in the portal. 使用自定义测试,你可以编写比使用门户 UI 更为复杂的可用性测试、监视 Azure VNET 内部的应用、更改终结点地址或创建可用性测试(即使该功能在你所在的区域中不可用)。Customized tests will allow you to write more complex availability tests than is possible using the portal UI, monitor an app inside of your Azure VNET, change the endpoint address, or create an availability test even if this feature is not available in your region.

备注

此示例只是为了向你展示TrackAvailability() API 调用在 Azure 函数中的工作机制,This example is designed solely to show you the mechanics of how the TrackAvailability() API call works within an Azure Function. 而不是为了演示如何编写基础 HTTP 测试代码/业务逻辑,后者是将其转变为功能完全正常的可用性测试所需的。Not how to write the underlying HTTP Test code/business logic that would be required to turn this into a fully functional availability test. 默认情况下,如果你逐步完成此示例,你将创建一个始终会产生故障的可用性测试。By default if you walk through this example you will be creating an availability test that will always generate a failure.

创建计时器触发的函数Create timer triggered function

  • 如果有 Application Insights 资源:If you have an Application Insights Resource:
    • 默认情况下,Azure Functions 会创建 Application Insights 资源,但如果你想要使用已创建的资源之一,则需在创建过程中指定。By default Azure Functions creates an Application Insights resource but if you would like to use one of your already created resources you will need to specify that during creation.
    • 使用以下选项,按照有关如何创建 Azure Functions 资源和计时器触发的函数的说明进行操作(在清理前停止)。Follow the instructions on how to create an Azure Functions resource and Timer triggered function (stop before clean up) with the following choices.
      • 选择顶部附近的“监视”选项卡。Select the Monitoring tab near the top.

         使用自己的 App Insights 资源创建 Azure Functions 应用Create an Azure Functions app with your own App Insights resource

      • 选择“Application Insights”下拉框,然后键入或选择资源的名称。Select the Application Insights dropdown box and type or select the name of your resource.

        选择现有 Application Insights 资源

      • 选择“查看 + 创建”Select Review + create

  • 如果尚未为计时器触发的函数创建 Application Insights 资源:If you do not have an Application Insights Resource created yet for your timer triggered function:

代码示例Sample code

将下面的代码复制到 run.csx 文件中(这将替换预先存在的代码)。Copy the code below into the run.csx file (this will replace the pre-existing code). 为此,请进入 Azure Functions 应用程序,选择左侧的计时器触发器函数。To do this, go into your Azure Functions application and select your timer trigger function on the left.

Azure 门户中 Azure 函数的 run.csxAzure function's run.csx in Azure portal

备注

对于“终结点地址”,你将使用 EndpointAddress= https://dc.applicationinsights.azure.cn/v2/trackFor the Endpoint Address you would use: EndpointAddress= https://dc.applicationinsights.azure.cn/v2/track.

#load "runAvailabilityTest.csx"
 
using System;
using System.Diagnostics;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
 
// The Application Insights Instrumentation Key can be changed by going to the overview page of your Function App, selecting configuration, and changing the value of the APPINSIGHTS_INSTRUMENTATIONKEY Application setting.
// DO NOT replace the code below with your instrumentation key, the key's value is pulled from the environment variable/application setting key/value pair.
private static readonly string instrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
 
//[CONFIGURATION_REQUIRED]
// Visit /azure-monitor/app/custom-endpoints#regions-that-require-endpoint-modification for more details.
private const string EndpointAddress = "https://dc.applicationinsights.azure.cn/v2/track";
 
private static readonly TelemetryConfiguration telemetryConfiguration = new TelemetryConfiguration(instrumentationKey, new InMemoryChannel { EndpointAddress = EndpointAddress });
private static readonly TelemetryClient telemetryClient = new TelemetryClient(telemetryConfiguration);
 
public async static Task Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"Entering Run at: {DateTime.Now}");
 
    if (myTimer.IsPastDue)
    {
        log.LogWarning($"[Warning]: Timer is running late! Last ran at: {myTimer.ScheduleStatus.Last}");
    }
 
    // [CONFIGURATION_REQUIRED] provide {testName} accordingly for your test function
    string testName = "AvailabilityTestFunction";
 
    // REGION_NAME is a default environment variable that comes with App Service
    string location = Environment.GetEnvironmentVariable("REGION_NAME");
 
    log.LogInformation($"Executing availability test run for {testName} at: {DateTime.Now}");
    string operationId = Guid.NewGuid().ToString("N");
 
    var availability = new AvailabilityTelemetry
    {
        Id = operationId,
        Name = testName,
        RunLocation = location,
        Success = false
    };
 
    var stopwatch = new Stopwatch();
    stopwatch.Start();
 
    try
    {
        await RunAvailbiltyTestAsync(log);
        availability.Success = true;
    }
    catch (Exception ex)
    {
        availability.Message = ex.Message;
 
        var exceptionTelemetry = new ExceptionTelemetry(ex);
        exceptionTelemetry.Context.Operation.Id = operationId;
        exceptionTelemetry.Properties.Add("TestName", testName);
        exceptionTelemetry.Properties.Add("TestLocation", location);
        telemetryClient.TrackException(exceptionTelemetry);
    }
    finally
    {
        stopwatch.Stop();
        availability.Duration = stopwatch.Elapsed;
        availability.Timestamp = DateTimeOffset.UtcNow;
 
        telemetryClient.TrackAvailability(availability);
        // call flush to ensure telemetry is sent
        telemetryClient.Flush();
    }
}

在“视图文件”下的右侧,选择“添加”。On the right under view files, select Add. 将新文件命名为“function.proj”,其中包含以下配置。Call the new file function.proj with the following configuration.

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.8.2" /> <!-- Ensure you’re using the latest version -->
    </ItemGroup>
</Project>

在右侧选择“添加”。On the right select, add. 将文件命名为“function.proj”Name the file function.proj

在“视图文件”下的右侧,选择“添加”。On the right under view files, select Add. 将新文件命名为“runAvailabilityTest.csx”,其中包含以下配置。Call the new file runAvailabilityTest.csx with the following configuration.

public async static Task RunAvailbiltyTestAsync(ILogger log)
{
    // Add your business logic here.
    throw new NotImplementedException();
}

检查可用性Check availability

为了确保一切正常工作,可以查看 Application Insights 资源的“可用性”选项卡中的图。To make sure everything is working, you can look at the graph in the Availability tab of your Application Insights resource.

备注

如果在 runAvailabilityTest.csx 中实现了自己的业务逻辑,那么你将看到成功结果(如下面的屏幕截图所示);如果未实现,那么你将看到失败结果。If you implemented your own business logic in runAvailabilityTest.csx then you will see successful results like in the screenshots below, if you did not then you will see failed results. 使用 TrackAvailability() 创建的测试显示时会在测试名称旁边带有“CUSTOM”字样。Tests created with TrackAvailability() will appear with CUSTOM next to the test name.

显示成功结果的“可用性”选项卡Availability tab with successful results

若要查看端到端事务详细信息,请在“深入钻取”下选择“成功”或“失败”,然后选择一个示例。To see the end-to-end transaction details, select Successful or Failed under drill into, then select a sample. 还可以通过选择图上的数据点来访问端到端事务详细信息。You can also get to the end-to-end transaction details by selecting a data point on the graph.

选择示例可用性测试Select a sample availability test

端到端事务详细信息End-to-end transaction details

如果按原样运行所有代码(不添加业务逻辑),则会看到测试失败。If you ran everything as is (without adding business logic), then you will see that the test failed.

在“日志(分析)”中查询Query in Logs (Analytics)

可以使用“日志(分析)”查看可用性结果、依赖关系等。You can use Logs(analytics) to view you availability results, dependencies, and more. 若要详细了解“日志”,请访问日志查询概述To learn more about Logs, visit Log query overview.

可用性结果Availability results

依赖项Dependencies

后续步骤Next steps