以编程方式创建流分析作业监视器Programmatically create a Stream Analytics job monitor

本文说明如何对流分析作业启用监视功能。This article demonstrates how to enable monitoring for a Stream Analytics job. 通过 REST API、Azure SDK 或 PowerShell 创建的流分析作业默认不启用监视功能。Stream Analytics jobs that are created via REST APIs, Azure SDK, or PowerShell do not have monitoring enabled by default. 可以在 Azure 门户中手动启用此功能,只需转到作业的“监视”页并单击“启用”按钮即可;也可以按本文中所述步骤自动执行此过程。You can manually enable it in the Azure portal by going to the job's Monitor page and clicking the Enable button or you can automate this process by following the steps in this article. 流分析作业的监视数据会显示在 Azure 门户的“指标”区域。The monitoring data will show up in the Metrics area of the Azure portal for your Stream Analytics job.

先决条件Prerequisites

在开始此过程之前,必须具有以下必备组件:Before you begin this process, you must have the following prerequisites:

  • Visual Studio 2019 或 2015Visual Studio 2019 or 2015
  • 已下载并安装了 Azure.NET SDKAzure .NET SDK downloaded and installed
  • 需要已启用监视功能的现有流分析作业An existing Stream Analytics job that needs to have monitoring enabled

创建一个项目Create a project

  1. 创建 Visual Studio C# .NET 控制台应用程序。Create a Visual Studio C# .NET console application.

  2. 在程序包管理器控制台中运行以下命令来安装 NuGet 包。In the Package Manager Console, run the following commands to install the NuGet packages. 第一个是 Azure 流分析管理 .NET SDK。The first one is the Azure Stream Analytics Management .NET SDK. 第二个是 Azure Monitor SDK,将用于启用监视功能。The second one is the Azure Monitor SDK that will be used to enable monitoring. 最后一个是用于进行身份验证的 Azure Active Directory 客户端。The last one is the Azure Active Directory client that will be used for authentication.

    Install-Package Microsoft.Azure.Management.StreamAnalytics
    Install-Package Microsoft.Azure.Insights -Pre
    Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
    
  3. 将下面的 appSettings 部分添加到 App.config 文件。Add the following appSettings section to the App.config file.

    <appSettings>
      <!--CSM Prod related values-->
      <add key="ResourceGroupName" value="RESOURCE GROUP NAME" />
      <add key="JobName" value="YOUR JOB NAME" />
      <add key="StorageAccountName" value="YOUR STORAGE ACCOUNT"/>
      <add key="ActiveDirectoryEndpoint" value="https://login.partner.microsoftonline.cn/" />
      <add key="ResourceManagerEndpoint" value="https://management.chinacloudapi.cn/" />
      <add key="WindowsManagementUri" value="https://management.core.chinacloudapi.cn/" />
      <add key="AsaClientId" value="1950a258-227b-4e31-a9cf-717495945fc2" />
      <add key="RedirectUri" value="urn:ietf:wg:oauth:2.0:oob" />
      <add key="SubscriptionId" value="YOUR AZURE SUBSCRIPTION ID" />
      <add key="ActiveDirectoryTenantId" value="YOUR TENANT ID" />
    </appSettings>
    

    SubscriptionIdActiveDirectoryTenantId 的值替换为 Azure 订阅 ID 和租户 ID。Replace values for SubscriptionId and ActiveDirectoryTenantId with your Azure subscription and tenant IDs. 可以通过运行以下 PowerShell cmdlet 来获取这些值:You can get these values by running the following PowerShell cmdlet:

    Get-AzureAccount
    
  4. 将以下 using 语句添加到项目中的源文件 (Program.cs)。Add the following using statements to the source file (Program.cs) in the project.

      using System;
      using System.Configuration;
      using System.Threading;
      using Microsoft.Azure;
      using Microsoft.Azure.Management.Insights;
      using Microsoft.Azure.Management.Insights.Models;
      using Microsoft.Azure.Management.StreamAnalytics;
      using Microsoft.Azure.Management.StreamAnalytics.Models;
      using Microsoft.IdentityModel.Clients.ActiveDirectory;
    
  5. 添加一个身份验证帮助器方法。Add an authentication helper method.

    public static string GetAuthorizationHeader()
    {
       AuthenticationResult result = null;
       var thread = new Thread(() =>
       {
          try
          {
              var context = new AuthenticationContext(
                 ConfigurationManager.AppSettings["ActiveDirectoryEndpoint"] +
                 ConfigurationManager.AppSettings["ActiveDirectoryTenantId"]);
              result = context.AcquireToken(
                  resource: ConfigurationManager.AppSettings["WindowsManagementUri"],
                  clientId: ConfigurationManager.AppSettings["AsaClientId"],
                  redirectUri: new Uri(ConfigurationManager.AppSettings["RedirectUri"]),
                  promptBehavior: PromptBehavior.Always);
          }
          catch (Exception threadEx)
          {
              Console.WriteLine(threadEx.Message);
          }
      });
    
      thread.SetApartmentState(ApartmentState.STA);
      thread.Name = "AcquireTokenThread";
      thread.Start();
      thread.Join();
    
      if (result != null)
      {
          return result.AccessToken;
      }
          throw new InvalidOperationException("Failed to acquire token");
    }
    

创建管理客户端Create management clients

以下代码可设置必需变量和管理客户端。The following code will set up the necessary variables and management clients.

 string resourceGroupName = "<YOUR AZURE RESOURCE GROUP NAME>";
 string streamAnalyticsJobName = "<YOUR STREAM ANALYTICS JOB NAME>";

 // Get authentication token
 TokenCloudCredentials aadTokenCredentials =
     new TokenCloudCredentials(
         ConfigurationManager.AppSettings["SubscriptionId"],
         GetAuthorizationHeader());

 Uri resourceManagerUri = new
 Uri(ConfigurationManager.AppSettings["ResourceManagerEndpoint"]);

 // Create Stream Analytics and Insights management client
 StreamAnalyticsManagementClient streamAnalyticsClient = new
 StreamAnalyticsManagementClient(aadTokenCredentials, resourceManagerUri);
 InsightsManagementClient insightsClient = new
 InsightsManagementClient(aadTokenCredentials, resourceManagerUri);

为现有流分析作业启用监视功能Enable monitoring for an existing Stream Analytics job

以下代码为现有流分析作业启用监视功能。The following code enables monitoring for an existing Stream Analytics job. 代码的第一部分针对流分析服务执行 GET 请求,目的是检索特定流分析作业的信息。The first part of the code performs a GET request against the Stream Analytics service to retrieve information about the particular Stream Analytics job. 它使用“ID”属性(从 GET 请求检索而得)作为代码第二部分中 Put 方法的参数,该方法将 PUT 请求发送到 Insights 服务以为流分析作业启用监视功能。It uses the ID property (retrieved from the GET request) as a parameter for the Put method in the second half of the code, which sends a PUT request to the Insights service to enable monitoring for the Stream Analytics job.

警告

如果此前为其他流分析作业启用了监视功能,那么不管是通过 Azure 门户进行还是通过以下代码以编程方式完成,我们都建议提供在之前启用监视功能时所使用的同一个存储帐户名称。If you have previously enabled monitoring for a different Stream Analytics job, either through the Azure portal or programmatically via the below code, we recommend that you provide the same storage account name that you used when you previously enabled monitoring.

存储帐户将链接到创建流分析作业时所在的区域,并不特定于作业本身。The storage account is linked to the region that you created your Stream Analytics job in, not specifically to the job itself.

该同一区域中的所有流分析作业(以及所有其他 Azure 资源)在存储监视数据时将共享此存储帐户。All Stream Analytics jobs (and all other Azure resources) in that same region share this storage account to store monitoring data. 如果提供其他存储帐户,则可能会产生意想不到的副作用,这将影响对其他流分析作业或其他 Azure 资源的监视。If you provide a different storage account, it might cause unintended side effects in the monitoring of your other Stream Analytics jobs or other Azure resources.

用于替换以下代码中的 <YOUR STORAGE ACCOUNT NAME> 的存储帐户名称应该是为其启用监视功能的流分析作业所在的同一订阅中的存储帐户。The storage account name that you use to replace <YOUR STORAGE ACCOUNT NAME> in the following code should be a storage account that is in the same subscription as the Stream Analytics job that you are enabling monitoring for.

// Get an existing Stream Analytics job
 JobGetParameters jobGetParameters = new JobGetParameters()
 {
     PropertiesToExpand = "inputs,transformation,outputs"
 };
 JobGetResponse jobGetResponse = streamAnalyticsClient.StreamingJobs.Get(resourceGroupName, streamAnalyticsJobName, jobGetParameters);

// Enable monitoring
ServiceDiagnosticSettingsPutParameters insightPutParameters = new ServiceDiagnosticSettingsPutParameters()
{
        Properties = new ServiceDiagnosticSettings()
       {
           StorageAccountName = "<YOUR STORAGE ACCOUNT NAME>"
       }
};
insightsClient.ServiceDiagnosticSettingsOperations.Put(jobGetResponse.Job.Id, insightPutParameters);

获取支持Get support

如需获取进一步的帮助,可前往有关 Azure 流分析的 Microsoft 问答页For further assistance, try Microsoft Q&A question page for Azure Stream Analytics.

后续步骤Next steps