适用于 Azure 云服务的 Application InsightsApplication Insights for Azure cloud services

Application Insights 可以通过将 Application Insights SDK 提供的数据与云服务提供的 Azure 诊断数据合并,来监视 Azure 云服务应用的可用性、性能、故障和使用情况。Application Insights can monitor Azure cloud service apps for availability, performance, failures, and usage by combining data from Application Insights SDKs with Azure Diagnostics data from your cloud services. 通过收到的有关应用在现实中的性能和有效性的反馈,可以针对每个开发生命周期确定合理的设计方向。With the feedback you get about the performance and effectiveness of your app in the wild, you can make informed choices about the direction of the design in each development lifecycle.

“概述”仪表板

先决条件Prerequisites

开始前,需要具备:Before you begin, you need:

  • 一个 Azure 订阅。An Azure subscription. 使用 Windows、XBox Live 或其他 Azure 云服务的 Azure 帐户登录。Sign in with your Azure account for Windows, Xbox Live, or other Azure cloud services.
  • Azure Tools 2.9 或更高版本。Azure tools 2.9 or later.
  • Developer Analytics Tools 7.10 或更高版本。Developer Analytics Tools 7.10 or later.

快速入门Get started quickly

使用 Application Insights 监视云服务的最快、最简单方法是将服务发布到 Azure 时选择 Application Insights 选项。The quickest and easiest way to monitor your cloud service with Application Insights is to choose that option when you publish your service to Azure.

示例“诊断设置”页

此选项可在运行时检测应用,提供监视请求所需的全部遥测数据、Web 角色中的异常和依赖项。This option instruments your app at runtime, giving you all the telemetry that you need to monitor requests, exceptions, and dependencies in your web role. 它还可以辅助角色中的性能计数器。It also monitors performance counters from your worker roles. 应用生成的所有诊断跟踪也会发送到 Application Insights。Any diagnostics traces generated by your app are also sent to Application Insights.

如果只需此选项,则操作到此完成。If this option is all you need, you're done.

后续步骤是通过应用查看指标使用 Analytics 查询数据Your next steps are viewing metrics from your app, querying your data with Analytics.

若要在浏览器中监视性能,还可能需要设置可用性测试将代码添加到网页To monitor performance in the browser, you might also want to set up availability tests and add code to your webpages.

下一部分将介绍以下附加选项:The next sections discuss the following additional options:

  • 通过不同的组件发送数据,以及在单独的资源上生成配置。Send data from various components and build configurations to separate resources.
  • 通过应用添加自定义遥测。Add custom telemetry from your app.

使用 Application Insights 检测的示例应用Sample app instrumented with Application Insights

在此示例应用中,Application Insights 已添加到某个云服务,该服务包含 Azure 中托管的两个辅助角色。In this sample app, Application Insights is added to a cloud service with two worker roles hosted in Azure.

下一部分介绍如何以相同的方式改编你自己的云服务项目。In the next section, you learn how to adapt your own cloud service project in the same way.

规划资源和资源组Plan resources and resource groups

应用中的遥测数据在 Application Insights 类型的 Azure 资源中进行存储、分析和显示。The telemetry from your app is stored, analyzed, and displayed in an Azure resource of type Application Insights.

每个资源属于一个资源组。Each resource belongs to a resource group. 资源组用于管理成本、向团队成员授予访问权限,以及在单个协调式事务中部署更新。Resource groups are used to manage costs, to grant access to team members, and to deploy updates in a single coordinated transaction. 例如,可以编写一个脚本,以通过一个操作部署 Azure 云服务及其 Application Insights 监视资源。For example, you could write a script to deploy an Azure cloud service and its Application Insights monitoring resources all in one operation.

组件的资源Resources for components

我们建议为应用的每个组件单独创建一个资源。We recommend that you create a separate resource for each component of your app. 即,为每个 Web 角色和辅助角色创建一个资源。That is, you create a resource for each web role and worker role. 可以单独分析每个组件,但也可以创建一个仪表板,用于将所有组件中的关键图表汇总到一起,以便可以在一个视图中比较和监视资源。You can analyze each component separately, but you create a dashboard that brings together the key charts from all the components, so that you can compare and monitor them together in a single view.

备选方法是将多个角色中的遥测数据发送到同一个资源,但将维度属性添加到标识其源角色的每个遥测项An alternative approach is to send the telemetry from more than one role to the same resource, but add a dimension property to each telemetry item that identifies its source role. 在此方法中,异常等指标图表通常显示不同角色的计数汇总,但你可根据需要按角色标识符将图表分段。In this approach, metric charts, such as exceptions, normally show an aggregation of the counts from the various roles, but you can segment the chart by the role identifier, as necessary. 还可以按同一个维度筛选搜索结果。You can also filter searches by the same dimension. 使用这种备选方法可以方便一次性查看所有信息,但同时可能导致在角色之间产生一定的混淆。This alternative makes it a bit easier to view everything at the same time, but it could also lead to some confusion between the roles.

浏览器遥测数据通常包含在与服务器端 Web 角色相同的资源中。Browser telemetry is usually included in the same resource as its server-side web role.

可将不同组件的 Application Insights 资源放在一个资源组中。Put the Application Insights resources for the various components in one resource group. 使用此方法可以轻松统一管理这些资源。This approach makes it easy to manage them together.

将开发、测试和生产隔开Separate development, test, and production

要开发适合下一功能的自定义事件但上一版本仍有效,可将开发遥测数据发送到独立的 Application Insights 资源。If you are developing custom events for your next feature while the previous version is live, you want to send the development telemetry to a separate Application Insights resource. 否则,可能很难在实时站点的所有流量中找到测试遥测数据。Otherwise, it can be hard to find your test telemetry among all the traffic from the live site.

为了避免这种情况,可以单独为系统的每个生成配置或“堆栈”(开发、测试、生产等)创建资源。To avoid this situation, create separate resources for each build configuration or "stamp" (development, test, production, and so on) of your system. 将每个生成配置的资源放在独立的资源组中。Put the resources for each build configuration in a separate resource group.

若要将遥测数据发送到相应的资源,可以设置 Application Insights SDK,使其根据生成配置选择不同的检测密钥。To send the telemetry to the appropriate resources, you can set up the Application Insights SDK so that it picks up a different instrumentation key, depending on the build configuration.

为每个角色创建 Application Insights 资源Create an Application Insights resource for each role

如果你决定为每个角色单独创建资源(也许是为每个生成配置单独创建资源集),最简单的方法是在 Application Insights 门户中创建这些资源。If you've decided to create a separate resource for each role, and perhaps a separate set for each build configuration, it's easiest to create them all in the Application Insights portal. 若要创建大量的资源,可将创建过程自动化If you create resources a lot, you can automate the process.

  1. Azure 门户中,选择“新建” > “开发人员服务” > “Application Insights”。 In the Azure portal, select New > Developer Services > Application Insights.

    “Application Insights”窗格

  2. 在“应用程序类型”下拉列表中,选择“ASP.NET Web 应用程序” 。In the Application Type drop-down list, select ASP.NET web application.

每个资源由检测密钥标识。Each resource is identified by an instrumentation key. 以后若要手动配置或验证 SDK 的配置,可能需要使用此密钥。You might need this key later if you want to manually configure or verify the configuration of the SDK.

为每个角色设置 Azure 诊断Set up Azure Diagnostics for each role

设置此选项可以使用 Application Insights 监视应用。Set this option to monitor your app with Application Insights. 对于 Web 角色,此选项可提供性能监视、警报、诊断以及使用情况分析。For web roles, this option provides performance monitoring, alerts, diagnostics, and usage analysis. 对于其他角色,可以搜索和监视 Azure 诊断信息,例如重启、性能计数器和对 System.Diagnostics.Trace 的调用。For other roles, you can search and monitor Azure Diagnostics such as restart, performance counters, and calls to System.Diagnostics.Trace.

  1. 在 Visual Studio 解决方案资源管理器中的“<YourCloudService>” > “角色”下面,打开每个角色的属性。 In Visual Studio Solution Explorer, under <YourCloudService> > Roles, open the properties of each role.

  2. 在“配置”中,选中“将诊断数据发送到 Application Insights”复选框,然后选择前面创建的 Application Insights 资源。 In Configuration, select the Send diagnostics data to Application Insights check box, and then select the Application Insights resource that you created earlier.

如果决定对每个生成配置使用不同的 Application Insights 资源,请先选择该配置。If you have decided to use a separate Application Insights resource for each build configuration, select the configuration first.

配置 Application Insights

这相当于将 Application Insights 检测密钥插入到名为 ServiceConfiguration.*.cscfg 的文件。This has the effect of inserting your Application Insights instrumentation keys into the files named ServiceConfiguration.*.cscfg. 下面是示例代码Here is the Sample code.

若要改变发送到 Application Insights 的诊断信息级别,可以直接编辑 .cscfg 文件If you want to vary the level of diagnostics information that's sent to Application Insights, you can do so by editing the .cscfg files directly.

在每个项目中安装 SDKInstall the SDK in each project

使用此选项可将自定义的业务遥测添加到任何角色。With this option, you can add custom business telemetry to any role. 使用该选项可以更细致地分析应用的用法和性能。The option provides a closer analysis of how your app is used and performs.

在 Visual Studio 中,为每个云应用项目配置 Application Insights SDK。In Visual Studio, configure the Application Insights SDK for each cloud app project.

  1. 若要配置 Web 角色,请右键单击项目,并选择“配置 Application Insights”或“添加”>“Application Insights 遥测” 。To configure web roles, right-click the project, and then select Configure Application Insights or Add > Application Insights telemetry.

  2. 配置辅助角色To configure worker roles:

    a.a. 右键单击项目,并选择“管理 NuGet 包”。Right-click the project, and then select Manage NuGet Packages.

    b.b. 添加适用于 Windows Server 的 Application InsightsAdd Application Insights for Windows Servers.

    搜索“Application Insights”

  3. 将 SDK 配置为向 Application Insights 资源发送数据:To configure the SDK to send data to the Application Insights resource:

    a.a. 在适当的启动函数中,通过 .cscfg 文件中的配置设置指定检测密钥:In a suitable startup function, set the instrumentation key from the configuration setting in the .cscfg file:

    
     TelemetryConfiguration.Active.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("APPINSIGHTS_INSTRUMENTATIONKEY");
    

    b.b. 针对应用中的每个角色重复“步骤 a”。Repeat "step a" for each role in your app. 参阅示例:See the examples:

  4. ApplicationInsights.config 文件设置为始终复制到输出目录。Set the ApplicationInsights.config file to be copied always to the output directory.

    .config 文件中的消息会询问是否要将检测密钥放在该处。A message in the .config file asks you to place the instrumentation key there. 但是,对于云应用,最好是通过 .cscfg 文件设置检测密钥。However, for cloud apps, it's better to set it from the .cscfg file. 此方法可确保在门户中正确识别角色。This approach ensures that the role is correctly identified in the portal.

设置状态监视器以收集完整的 SQL 查询(可选)Set up Status Monitor to collect full SQL Queries (optional)

仅当你希望在 .NET Framework 上捕获完整的 SQL 查询时,才需要此步骤。This step is only needed if you want to capture full SQL queries on .NET Framework.

  1. \*.csdef 文件中为每个角色添加启动任务,如下所示In \*.csdef file Add startup task for each role similar to

    <Startup>
      <Task commandLine="AppInsightsAgent\InstallAgent.bat" executionContext="elevated" taskType="simple">
        <Environment>
          <Variable name="ApplicationInsightsAgent.DownloadLink" value="http://go.microsoft.com/fwlink/?LinkID=522371" />
          <Variable name="RoleEnvironment.IsEmulated">
            <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
          </Variable>
        </Environment>
      </Task>
    </Startup>
    
  2. 下载 InstallAgent.batInstallAgent.ps1,将它们放入每个角色项目的 AppInsightsAgent 文件夹中。Download InstallAgent.bat and InstallAgent.ps1, put them into the AppInsightsAgent folder on each role project. 确保通过 Visual Studio 文件属性或生成脚本将它们复制到输出目录。Make sure to copy them to the output directory through Visual Studio file properties or build scripts.

  3. 在所有辅助角色上添加环境变量:On all Worker Roles, add environment variables:

      <Environment>
        <Variable name="COR_ENABLE_PROFILING" value="1" />
        <Variable name="COR_PROFILER" value="{324F817A-7420-4E6D-B3C1-143FBED6D855}" />
        <Variable name="MicrosoftInstrumentationEngine_Host" value="{CA487940-57D2-10BF-11B2-A3AD5A13CBC0}" />
      </Environment>
    

运行并发布应用Run and publish the app

  1. 运行应用并登录到 Azure。Run your app, and sign in to Azure.

  2. 打开前面创建的 Application Insights 资源。Open the Application Insights resources that you created.

    搜索中会显示每个数据点,指标资源管理器中会显示聚合数据。Individual data points are displayed in Search, and aggregated data is displayed in Metric Explorer.

  3. 添加更多遥测数据(请参阅以下部分),然后发布应用以获取实时诊断和使用情况反馈。Add more telemetry (see the next sections) and then publish your app to get live diagnostics and usage feedback.

如果没有数据,请执行以下操作:If there is no data, do the following:

  1. 若要查看各个事件,请打开搜索磁贴。To view individual events, open the Search tile.
  2. 在应用中打开各个页面,以生成一些遥测数据。In the app, open various pages so that it generates some telemetry.
  3. 等待几秒,然后单击“刷新”。Wait a few seconds, and then click Refresh.

有关详细信息,请参阅 故障排除For more information, see Troubleshooting.

查看 Azure 诊断事件View Azure Diagnostics events

可以在 Application Insights 中的以下位置找到 Azure 诊断信息:You can find the Azure Diagnostics information in Application Insights in the following locations:

  • 性能计数器显示为自定义指标。Performance counters are displayed as custom metrics.
  • Windows 事件日志显示为跟踪和自定义事件。Windows event logs are shown as traces and custom events.
  • 应用程序日志、ETW 日志和所有诊断基础结构日志均显示为跟踪。Application logs, ETW logs, and any diagnostics infrastructure logs appear as traces.

若要查看性能计数器和事件计数,请打开指标资源管理器并添加以下图表:To view performance counters and counts of events, open Metrics Explorer and add the following chart:

Azure 诊断数据

若要在 Azure 诊断发送的各种跟踪日志中进行搜索,请使用搜索Analytics 查询To search across the various trace logs that are sent by Azure Diagnostics, use Search or an Analytics query. 例如,假设某个未经处理的异常导致角色崩溃和回收。For example, suppose you have an unhandled exception that has caused a role to crash and recycle. 该信息会在应用程序通道的 Windows 事件日志中显示。That information would show up in the Application channel of Windows Event Log. 可使用搜索来查看 Windows 事件日志错误,并获取异常的完整堆栈跟踪。You can use Search to view the Windows Event Log error and get the full stack trace for the exception. 这样有助于找到问题的根本原因。Doing so helps you find the root cause of the issue.

Azure 诊断搜索

其他遥测数据More telemetry

以下部分从应用的不同层面介绍如何获取其他遥测数据。The next sections discuss how to get additional telemetry from various aspects of your app.

从辅助角色跟踪请求Track requests from worker roles

在 Web 角色中,请求模块会自动收集有关 HTTP 请求的数据。In web roles, the requests module automatically collects data about HTTP requests. 有关如何覆盖默认收集行为的示例,请参阅示例 MVCWebRoleFor examples of how you can override the default collection behavior, see the sample MVCWebRole.

可以像跟踪 HTTP 请求一样捕获辅助角色调用的性能。You can capture the performance of calls to worker roles by tracking them in the same way as HTTP requests. 在 Application Insights 中,请求遥测类型用于测量一个单位的可计时且可独立成功/失败的命名服务器端工作。In Application Insights, the Request telemetry type measures a unit of named server-side work that can be timed and can independently succeed or fail. 尽管 SDK 可以自动捕获 HTTP 请求,但你也可以插入自己的代码来跟踪针对辅助角色发出的请求。Although HTTP requests are captured automatically by the SDK, you can insert your own code to track requests to worker roles.

请参阅报告请求的两个检测示例辅助角色:See the two sample worker roles instrumented to report requests:

异常Exceptions

有关如何从不同的 Web 应用类型收集未经处理的异常的信息,请参阅在 Application Insights 中监视异常For information about how to collect unhandled exceptions from various web app types, see Monitoring exceptions in Application Insights.

该示例 Web 角色包含 MVC5 和 Web API 2 控制器。The sample web role has MVC5 and Web API 2 controllers. 可使用以下处理程序捕获这两个控制器的未经处理的异常:The unhandled exceptions from the two are captured with the following handlers:

对于辅助角色,可通过两种方式跟踪异常:For worker roles, you can track exceptions in two ways:

  • 使用 TrackException(ex)。Use TrackException(ex).
  • 如果已添加 Application Insights 跟踪侦听程序 NuGet 包,可按此示例所示,使用 System.Diagnostics.Trace 来记录异常。If you have added the Application Insights trace listener NuGet package, you can use System.Diagnostics.Trace to log exceptions as shown in this example.

性能计数器Performance counters

默认收集以下计数器:The following counters are collected by default:

  • \Process(??APP_WIN32_PROC??)%处理器时间\Process(??APP_WIN32_PROC??)% Processor Time
  • \Memory\Available Bytes\Memory\Available Bytes
  • .NET CLR Exceptions(??APP_CLR_PROC??)# of Exceps Thrown / sec.NET CLR Exceptions(??APP_CLR_PROC??)# of Exceps Thrown / sec
  • \Process(??APP_WIN32_PROC??)\Private Bytes\Process(??APP_WIN32_PROC??)\Private Bytes
  • \Process(??APP_WIN32_PROC??)\IO Data Bytes/sec\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec
  • \Processor(_Total)% 处理器时间\Processor(_Total)% Processor Time

对于 Web 角色,还将收集以下计数器:For web roles, these counters are also collected:

  • \ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec
  • \ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time
  • \ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue

按此示例所示,通过编辑 ApplicationInsights.config 来指定其他自定义性能计数器或其他 Windows 性能计数器。You can specify additional custom or other Windows performance counters by editing ApplicationInsights.config as shown in this example.

性能计数器

辅助角色的关联遥测数据Correlated telemetry for worker roles

若要获得丰富的诊断体验,可以查看请求失败或长时间延迟的原因。For a rich diagnostics experience, you can view what led to a failed or high latency request. 使用 Web 角色,SDK 可在相关遥测数据之间自动设置关联。With web roles, the SDK automatically sets up a correlation between related telemetry.

若要获取辅助角色的此视图,可以使用自定义遥测初始值设定项为所有遥测设置一个通用的 Operation.Id 上下文属性。To achieve this view for worker roles, you can use a custom telemetry initializer to set a common Operation.Id context attribute for all the telemetry. 这样,延迟或失败问题是否由依赖项或代码造成便一目了然。Doing so lets you view at a glance whether the latency or failure issue was caused by a dependency or your code.

方法如下:Here's how:

  • 按此示例所示,将 correlationId 设置到 CallContext 中。Set the correlationId into a CallContext as shown in this example. 本例使用请求 ID 作为 correlationId。In this case, we are using the Request ID as the correlationId.
  • 添加自定义 TelemetryInitializer 实现,将 Operation.Id 设置为前面所设置的 correlationId。Add a custom TelemetryInitializer implementation, to set the Operation.Id to the correlationId that was set previously. 有关示例,请参阅 ItemCorrelationTelemetryInitializerFor an example, see ItemCorrelationTelemetryInitializer.
  • 添加自定义遥测初始值设定项。Add the custom telemetry initializer. 按此示例所示,在 ApplicationInsights.config 文件或代码中执行此操作。You could do so in the ApplicationInsights.config file or in code as shown in this example.

客户端遥测数据Client telemetry

若要获取基于浏览器的遥测数据(例如页面查看次数、页面加载时间或脚本异常)以及在页面脚本中编写自定义遥测,请参阅将 JavaScript SDK 添加到网页To get browser-based telemetry, such as page view counts, page load times, or script exceptions, and to write custom telemetry in your page scripts, see Add the JavaScript SDK to your webpages.

可用性测试Availability tests

为确保应用处于活动状态且能够做出响应,请设置 Web 测试To make sure your app stays live and responsive, Set up web tests.

统一显示所有信息Display everything together

若要获得系统的整体视图,可在一个仪表板中将关键的监视图表一起显示。For an overall picture of your system, you can display the key monitoring charts together on one dashboard. 例如,可以固定每个角色的请求和失败次数。For example, you could pin the request and failure counts of each role.

如果系统使用其他 Azure 服务(例如流分析),也可以包含这些服务的监视图表。If your system uses other Azure services, such as Stream Analytics, include their monitoring charts as well.

Analytics 中创建查询来显示事件计数,并将事件固定到仪表板。Create queries in Analytics to display the event counts, and pin them to the dashboard.

示例Example

该示例监视包含一个 Web 角色和两个辅助角色的服务。The example monitors a service that has a web role and two worker roles.

在 Azure 云服务中运行时发生“找不到方法”异常Exception "method not found" on running in Azure cloud services

生成的项目是否面向 .NET 4.6?Did you build for .NET 4.6? Azure 云服务角色不能现成地支持 .NET 4.6。.NET 4.6 is not automatically supported in Azure cloud services roles. 运行应用之前,请先在每个角色上安装 .NET 4.6Install .NET 4.6 on each role before running your app.

后续步骤Next steps