您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Application Insights 在 Service Fabric 上监视和诊断 ASP.NET Core 应用程序Tutorial: Monitor and diagnose an ASP.NET Core application on Service Fabric using Application Insights

本教程是系列教程的第五部分,This tutorial is part five of a series. 介绍了使用 Application Insights 针对 Service Fabric 群集上运行的 ASP.NET Core 应用程序设置监视和诊断的步骤。It goes through the steps to set up monitoring and diagnostics for an ASP.NET Core application running on a Service Fabric cluster using Application Insights. 我们会从本教程第一部分(即构建 .NET Service Fabric 应用程序)开发的应用程序中收集遥测数据。We will collect telemetry from the application developed in the first part of the tutorial, Build a .NET Service Fabric application.

此教程系列的第四部分介绍如何:In part four of the tutorial series, you learn how to:

  • 为应用程序配置 Application InsightsConfigure Application Insights for your application
  • 收集响应遥测数据,跟踪服务之间基于 HTTP 的通信Collect response telemetry to trace HTTP-based communication between services
  • 使用 Application Insights 中的应用映射功能Use the App Map feature in Application Insights
  • 使用 Application Insights API 添加自定义事件Add custom events using the Application Insights API

在此系列教程中,你会学习如何:In this tutorial series you learn how to:

先决条件Prerequisites

在开始学习本教程之前:Before you begin this tutorial:

下载投票示例应用程序Download the Voting sample application

如果未生成本教程系列的第一部分中的投票示例应用程序,还可以下载它。If you did not build the Voting sample application in part one of this tutorial series, you can download it. 在命令窗口或终端中运行以下命令,将示例应用存储库克隆到本地计算机。In a command window or terminal, run the following command to clone the sample app repository to your local machine.

git clone https://github.com/Azure-Samples/service-fabric-dotnet-quickstart

设置 Application Insights 资源Set up an Application Insights resource

Application Insights 是 Azure 的应用程序性能管理平台,也是 Service Fabric 建议用于应用程序监视和诊断的平台。Application Insights is Azure's application performance management platform, and Service Fabric's recommended platform for application monitoring and diagnostics.

若要创建 Application Insights 资源,请导航到 Azure 门户To create an Application Insights resource, navigate to Azure portal. 单击左侧导航菜单中的“创建资源”,打开 Azure 市场。 Click Create a resource on the left navigation menu to open up Azure Marketplace. 单击“监视 + 管理”,然后单击“Application Insights”。 Click on Monitoring + Management and then Application Insights.

创建新的 AI 资源

此时需填写要创建的资源的必要属性信息。You will now need to fill out required information about the attributes of the resource to be created. 输入适当的“名称”、“资源组”和“订阅”。 Enter an appropriate Name, Resource Group, and Subscription. 设置“位置”,以便在将来部署 Service Fabric 群集。 Set the Location to where you would deploy your Service Fabric cluster in the future. 在本教程中,需将应用部署到本地群集,因此与“位置”字段无关。 In this tutorial, we will deploy the app to a local cluster so the Location field is irrelevant. “应用程序类型”应保留为“ASP.NET Web 应用程序”。 The Application Type should be left as "ASP.NET web application."

AI 资源属性

填充所需信息以后,请单击“创建”对资源进行预配 - 大约需一分钟。 Once you've filled out the required information, click Create to provision the resource - it should take about a minute.

将 Application Insights 添加到应用程序的服务Add Application Insights to the application's services

使用提升的权限启动 Visual Studio 2019,方法是:右键单击“开始”菜单中的 Visual Studio 图标,然后选择“以管理员身份运行” 。Launch Visual Studio 2019 with elevated privileges by right-clicking the Visual Studio icon in the Start Menu and choosing Run as administrator. 单击“文件” > “打开” > “项目/解决方案”,导航到 Voting 应用程序(在本教程第一部分创建,也可以进行 Git 克隆)。Click File > Open > Project/Solution and navigate to the Voting application (either created in part one of the tutorial or git cloned). 打开 Voting.slnOpen Voting.sln. 如果系统提示你还原应用程序的 NuGet 包,请单击“是”。 If prompted to restore the application's NuGet packages, click Yes.

执行以下步骤,为 VotingWeb 和 VotingData 服务配置 Application Insights:Follow these steps to configure Application Insights for both the VotingWeb and VotingData services:

  1. 右键单击服务的名称,然后单击“添加”>“连接的服务”>“使用 Application Insights 进行监视”。 Right-click on the name of the service, and click Add > Connected Services > Monitoring with Application Insights.

    配置 AI

备注

根据项目类型,在右键单击服务名称时,可能需要单击“添加”->“Application Insights 遥测...”Depending on the project type, when you Right-click on the name of the service, you may need to click Add-> Application Insights Telemetry ...

  1. 单击“入门”。 Click Get started.

  2. 登录到用于设置 Azure 订阅的帐户,选择在其中创建了 Application Insights 资源的订阅。Sign in to the account you used to set up your Azure subscription and select the subscription in which you created the Application Insights resource. 在“资源”下拉列表的“现有的 Application Insights 资源”下找到该资源。 Find the resource under Existing Application Insights resource in the "Resource" dropdown. 单击“注册”将 Application Insights 添加到服务。 Click Register to add Application Insights to your service.

    注册 AI

  3. 在弹出的对话框完成操作后,单击“完成”。 Click Finish once the dialog box that pops up completes the action.

备注

请确保针对应用程序中的这两项服务执行上述步骤,完成应用程序的 Application Insights 配置。 Make sure to do the above steps for both of the services in the application to finish configuring Application Insights for the application. 将相同的 Application Insights 资源用于这两项服务是为了查看服务之间的传入和传出请求和通信。The same Application Insights resource is used for both of the services in order to see incoming and outgoing requests and communication between the services.

将 Microsoft.ApplicationInsights.ServiceFabric.Native NuGet 添加到服务Add the Microsoft.ApplicationInsights.ServiceFabric.Native NuGet to the services

Application Insights 有两个特定于 Service Fabric 的 NuGet,可以根据方案使用。Application Insights has two Service Fabric specific NuGets that can be used depending on the scenario. 一个用于 Service Fabric 的本机服务,另一个用于容器和来宾可执行文件。One is used with Service Fabric's native services, and the other with containers and guest executables. 在这种情况下,我们将使用 Microsoft.ApplicationInsights.ServiceFabric.Native NuGet,以便充分利用对其自带的服务上下文的理解。In this case, we'll be using the Microsoft.ApplicationInsights.ServiceFabric.Native NuGet to leverage the understanding of service context that it brings. 若要详细了解 Application Insights SDK 和特定于 Service Fabric 的 NuGet,请参阅 Microsoft Application Insights for Service Fabric(适用于 Service Fabric 的 Microsoft Application Insights)。To read more about the Application Insights SDK and the Service Fabric specific NuGets, see Microsoft Application Insights for Service Fabric.

下面是设置 NuGet 包的步骤:Here are the steps to set up the NuGet package:

  1. 右键单击解决方案资源管理器顶部的“解决方案 'Voting'”,然后单击“为解决方案管理 NuGet 包...” 。Right-click on Solution 'Voting' at the very top of your Solution Explorer, and click Manage NuGet Packages for Solution....
  2. 单击“NuGet - 解决方案”窗口顶部浏览菜单中的“浏览”,然后勾选搜索栏旁边的“包括预发行版”框。 Click Browse on the top navigation menu of the "NuGet - Solution" window, and check the Include prerelease box next to the search bar.

备注

可能需要采用类似的方式安装 Microsoft.ServiceFabric.Diagnostics.Internal 包,前提是此包在安装 Application Insights 包之前未预先安装You may need to install the Microsoft.ServiceFabric.Diagnostics.Internal package in a similar fashion if not preinstalled before installing the Application Insights package

  1. 搜索 Microsoft.ApplicationInsights.ServiceFabric.Native,然后单击相应的 NuGet 包。Search for Microsoft.ApplicationInsights.ServiceFabric.Native and click on the appropriate NuGet package.

  2. 在右侧单击应用程序中两项服务旁边的复选框“VotingWeb”和“VotingData”,然后单击“安装”。 On the right, click on the two check boxes next to the two services in the application, VotingWeb and VotingData and click Install. AI sdk NugetAI sdk Nuget

  3. 在显示的“审阅更改”对话框中单击“确定”,接受“接受许可证”中的条款。 Click OK on the Preview Changes dialog box that appears, and accept the License Acceptance. 这样即可将 NuGet 添加到服务。This will complete adding the NuGet to the services.

  4. 现在需在两个服务中设置遥测初始值设定项。You now need to set up the telemetry initializer in the two services. 为此,请打开“VotingWeb.cs”和“VotingData.cs”。 To do this, open up VotingWeb.cs and VotingData.cs. 对这两个文件执行下述两项步骤:For both of them, do the following two steps:

    1. 在每个 <ServiceName>.cs 顶部的现有 using 语句之后添加下面这两个 using 语句:Add these two using statements at the top of each <ServiceName>.cs, after the existing using statements:
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.ServiceFabric;
    
    1. 在两个文件的 CreateServiceInstanceListeners() 或 CreateServiceReplicaListeners() 的嵌套式 return 语句中,在已声明其他单一实例服务的 ConfigureServices > services 下添加:In both files, in the nested return statement of CreateServiceInstanceListeners() or CreateServiceReplicaListeners(), under ConfigureServices > services, with the other singleton services declared, add:
    .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext))
    

    此时会向遥测添加服务上下文, 方便用户更好地理解 Application Insights 中遥测的源代码。This will add the Service Context to your telemetry, allowing you to better understand the source of your telemetry in Application Insights. VotingWeb.cs 中的嵌套式 return 语句应如下所示:Your nested return statement in VotingWeb.cs should look like this:

    return new WebHostBuilder()
        .UseKestrel()
        .ConfigureServices(
            services => services
                .AddSingleton<HttpClient>(new HttpClient())
                .AddSingleton<FabricClient>(new FabricClient())
                .AddSingleton<StatelessServiceContext>(serviceContext)
                .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext)))
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
        .UseUrls(url)
        .Build();
    

    同样, VotingData.cs 中的内容应如下所示:Similarly, in VotingData.cs, you should have:

    return new WebHostBuilder()
        .UseKestrel()
        .ConfigureServices(
            services => services
                .AddSingleton<StatefulServiceContext>(serviceContext)
                .AddSingleton<IReliableStateManager>(this.StateManager)
                .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext)))
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
        .UseUrls(url)
        .Build();
    

仔细进行检查,确保在 VotingWeb.csVotingData.cs 中调用 UseApplicationInsights() 方法,如上所示。Double check that the UseApplicationInsights() method is called in both VotingWeb.cs and VotingData.cs as shown above.

备注

此示例应用使用 http 供服务通信。This sample app uses http for the services to communicate. 如果使用 Service Remoting V2 来开发应用,则需在以前添加代码的位置添加以下代码行If you develop an app with Service Remoting V2 you'd need to add the following lines of code as well in the same place as you did above

ConfigureServices(services => services
    ...
    .AddSingleton<ITelemetryModule>(new ServiceRemotingDependencyTrackingTelemetryModule())
    .AddSingleton<ITelemetryModule>(new ServiceRemotingRequestTrackingTelemetryModule())
)

此时可以部署应用程序了。At this point, you are ready to deploy the application. 单击顶部的“开始” (或 F5),Visual Studio 就会生成应用程序并将其打包,设置本地群集,然后向其部署应用程序。Click Start at the top (or F5), and Visual Studio will build and package the application, set up your local cluster, and deploy the application to it.

备注

如果未安装 .NET Core SDK 的最新版本,可能会出现生成错误。You may get a build error if you do not have an up-to-date version of the .NET Core SDK installed.

应用程序部署完以后,请访问 localhost:8080,其中应该可以看到 Voting 单页应用程序示例。Once the application is done deploying, head over to localhost:8080, where you should be able to see the Voting Sample single page application. 投票选择各种不同的项目,以便创建一些示例数据和遥测 - 我投票选择甜点!Vote for a few different items of your choice to create some sample data and telemetry - I went for desserts!

AI 示例投票

添加完投票选项后,也可以随意删除部分投票选项。 Feel free to Remove some of the voting options as well when you're done adding a few votes.

在 Application Insights 中查看遥测和应用映射View telemetry and the App map in Application Insights

在 Azure 门户中转到 Application Insights 资源。Head over to your Application Insights resource in Azure portal.

单击“概览”,回到资源的登陆页。 Click Overview to go back to the landing page of your resource. 然后单击顶部的“搜索”,查看传入的跟踪。 Then click Search in the top to see the traces coming in. 跟踪显示在 Application Insights 中需要数分钟。It takes a few minutes for traces to appear in Application Insights. 如果看不到任何内容,请等待一会儿,然后单击顶部的“刷新”按钮。 In the case that you do not see any, wait a minute and hit the Refresh button at the top. AI 查看跟踪AI see traces

在“搜索”窗口中向下滚动就会看到 Application Insights 自带的所有传入遥测。 Scrolling down on the Search window will show you all the incoming telemetry you get out-of-the-box with Application Insights. 在 Voting 应用程序中每执行一个操作,就会有一个来自 VotingWeb 的传出 PUT 请求(PUT 投票/Put [名称])、一个来自 VotingData 的传入 PUT 请求(PUT VoteData/Put [名称]),后跟一对用于刷新所显示数据的 GET 请求。For each action that you took in the Voting application, there should be an outgoing PUT request from VotingWeb (PUT Votes/Put [name]), an incoming PUT request from VotingData (PUT VoteData/Put [name]), followed by a pair of GET requests for refreshing the data being displayed. 此外还会在 localhost 上有一个针对 HTTP 的依赖项跟踪,因为这些请求是 HTTP 请求。There will also be a dependency trace for HTTP on localhost, since these are HTTP requests. 下面是一个示例,显示了添加一个投票后的情况:Here is an example of what you will see for how one vote is added:

AI 示例请求跟踪

单击其中一个跟踪即可查看其详细信息。You can click on one of the traces to view more details about it. Application Insights 提供了该请求的有用信息,其中包括“响应时间”和“请求 URL”。 There is useful information about the request that is provided by Application Insights, including the Response time and the Request URL. 另外,由于添加了特定于 Service Fabric 的 NuGet,因此还会在底部的“自定义数据”部分提供 Service Fabric 群集上下文中的应用程序数据。 In addition, since you added the Service Fabric specific NuGet, you will also get data about your application in the context of a Service Fabric cluster in the Custom Data section below. 这其中包括服务上下文,因此可以查看请求源的“PartitionID”和“ReplicaId”。在对应用程序中的错误进行诊断时,这样能够更好地查找问题。 This includes the service context, so you can see the PartitionID and ReplicaId of the source of the request, and better localize issues when diagnosing errors in your application.

AI 跟踪详细信息

另外,可以单击“概览”页中左侧菜单上的“应用程序映射” ,或者单击“应用映射”图标,转到显示两个服务已连接的应用映射。 Additionally, you can click Application map on the left menu on the Overview page, or click on the App map icon to take you to the App Map showing your two services connected.

AI 跟踪详细信息

可以通过应用映射更好地了解应用程序拓扑,尤其是在开始添加多个不同的一起运行的服务时。The App map can help you understand your application topology better, especially as you start adding multiple different services that work together. 也可通过它来获取有关请求成功率的基本数据,对失败的请求进行诊断,了解问题之所在。It also gives you basic data on request success rates, and can help you diagnose failed request to understand where things may have gone wrong. 若要详细了解如何使用应用映射,请参阅 Application Insights 中的应用程序映射To learn more about using the App map, see Application Map in Application Insights.

将自定义检测添加到应用程序Add custom instrumentation to your application

虽然 Application Insights 提供了许多现成的遥测,但你可能需要添加更多的自定义检测。Though Application Insights provides a lot of telemetry out of the box, you may want to add further custom instrumentation. 这可能取决于业务需求,或者在应用程序出错时对诊断进行改进的需求。This could be based on your business needs or to improve diagnostics when things go wrong in your application. Application Insights 有一个用于引入自定义事件和指标的 API,详见此文Application Insights has an API to ingest custom events and metrics, which you can read more about here.

让我们向 VoteDataController.cs(位于“VotingData” > “控制器”下)添加一些自定义事件,以便跟踪在基础 votesDictionary 中添加和删除投票的时间。Let's add some custom events to VoteDataController.cs (under VotingData > Controllers) to track when votes are being added and deleted from the underlying votesDictionary.

  1. 在其他 using 语句末尾添加 using Microsoft.ApplicationInsights;Add using Microsoft.ApplicationInsights; at the end of the other using statements.
  2. 在创建 IReliableStateManager 时,在类的开头声明新的 TelemetryClient :private TelemetryClient telemetry = new TelemetryClient();Declare a new TelemetryClient at the start of the class, under the creation of the IReliableStateManager: private TelemetryClient telemetry = new TelemetryClient();.
  3. 在 Put() 函数中添加一个事件,对已添加的投票进行确认。In the Put() function, add an event that confirms a vote has been added. 在事务完成后将 telemetry.TrackEvent($"Added a vote for {name}"); 直接添加到 return OkResult 语句前面。Add telemetry.TrackEvent($"Added a vote for {name}"); after the transaction has completed, right before the return OkResult statement.
  4. 在 Delete() 中有一个基于特定条件(即 votesDictionary 包含给定投票选项的投票)的“if/else”。In Delete(), there is an "if/else" based on the condition that the votesDictionary contains votes for a given voting option.
    1. 在 if 语句中的 await tx.CommitAsync() 后添加一个确认投票已删除的事件:telemetry.TrackEvent($"Deleted votes for {name}");Add an event that confirms the deletion of a vote in the if statement, after the await tx.CommitAsync(): telemetry.TrackEvent($"Deleted votes for {name}");
    2. 在 else 语句中的 return 语句之前添加一个表明没有进行删除的事件:telemetry.TrackEvent($"Unable to delete votes for {name}, voting option not found");Add an event to show that the deletion did not take place in the else statement, before the return statement: telemetry.TrackEvent($"Unable to delete votes for {name}, voting option not found");

下面是一个示例,显示在添加事件后 Put() 和 Delete() 函数的情况:Here's an example of what your Put() and Delete() functions may look like after adding the events:

// PUT api/VoteData/name
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name)
{
    var votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");

    using (ITransaction tx = this.stateManager.CreateTransaction())
    {
        await votesDictionary.AddOrUpdateAsync(tx, name, 1, (key, oldvalue) => oldvalue + 1);
        await tx.CommitAsync();
    }

    telemetry.TrackEvent($"Added a vote for {name}");
    return new OkResult();
}

// DELETE api/VoteData/name
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
    var votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");

    using (ITransaction tx = this.stateManager.CreateTransaction())
    {
        if (await votesDictionary.ContainsKeyAsync(tx, name))
        {
            await votesDictionary.TryRemoveAsync(tx, name);
            await tx.CommitAsync();
            telemetry.TrackEvent($"Deleted votes for {name}");
            return new OkResult();
        }
        else
        {
            telemetry.TrackEvent($"Unable to delete votes for {name}, voting option not found");
            return new NotFoundResult();
        }
    }
}

进行这些更改以后,请启动应用程序,以便生成和部署最新版本。 Once you're done making these changes, Start the application so that it builds and deploys the latest version of it. 应用程序部署完以后,请访问 localhost:8080,添加和删除一些投票选项。Once the application is done deploying, head over to localhost:8080, and add and delete some voting options. 然后回到 Application Insights 资源,查看最新运行的跟踪(与前面一样,跟踪可能需要 1-2 分钟才会显示在 Application Insights 中)。Then, go back to your Application Insights resource to see the traces for the latest run (as before, traces can take 1-2 min to show up in Application Insights). 不管是添加的还是删除的投票,此时都会看到一个“自定义事件”*,以及所有响应遥测。For all the votes you added and deleted, you should now see a "Custom Event* along with all the response telemetry.

自定义事件

后续步骤Next steps

本教程介绍了以下操作:In this tutorial, you learned how to:

  • 为应用程序配置 Application InsightsConfigure Application Insights for your application
  • 收集响应遥测数据,跟踪服务之间基于 HTTP 的通信Collect response telemetry to trace HTTP-based communication between services
  • 使用 Application Insights 中的应用映射功能Use the App Map feature in Application Insights
  • 使用 Application Insights API 添加自定义事件Add custom events using the Application Insights API

设置完 ASP.NET 应用程序的监视和诊断以后,请尝试以下操作:Now that you have completed setting up monitoring and diagnostics for your ASP.NET application, try the following: