Application Insights 使用分析Usage analysis with Application Insights

Web 或移动应用有哪些最热门的功能?Which features of your web or mobile app are most popular? 用户是否使用应用实现了其目标?Do your users achieve their goals with your app? 他们是否中途放弃应用,后来又回头使用了吗?Do they drop out at particular points, and do they return later? Azure Application Insights 可帮助你有效地深入分析人们如何使用应用。Azure Application Insights helps you gain powerful insights into how people use your app. 每次更新应用时,都可以评估它在用户那里的运行状况。Every time you update your app, you can assess how well it works for users. 了解这些信息后,可以针对下一个开发周期做出数据驱动的决策。With this knowledge, you can make data driven decisions about your next development cycles.

从应用发送遥测数据Send telemetry from your app

通过在应用服务器代码和网页中安装 Application Insights 来获得最佳体验。The best experience is obtained by installing Application Insights both in your app server code, and in your web pages. 应用的客户端和服务器组件将遥测发送回 Azure 门户进行分析。The client and server components of your app send telemetry back to the Azure portal for analysis.

  1. 服务器代码:ASP.NETAzureJavaNode.js其他应用安装适当的模块。Server code: Install the appropriate module for your ASP.NET, Azure, Java, Node.js, or other app.

  2. 网页代码 :将以下脚本添加到网页的结束标记 </head> 之前。Web page code: Add the following script to your web page before the closing </head>. 将检测密钥替换为 Application Insights 资源的相应值:Replace instrumentation key with the appropriate value for your Application Insights resource:

    <script type="text/javascript">
    var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var s="Track"+r[0];if(n("start"+s),n("stop"+s),n("setAuthenticatedUserContext"),n("clearAuthenticatedUserContext"),n("flush"),!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("_"+(r="onerror"));var o=a[r];a[r]=function(e,n,i,a,s){var c=o&&o(e,n,i,a,s);return!0!==c&&t["_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:s}),c},e.autoExceptionInstrumented=!0}return t}(
    {
      instrumentationKey:"INSTRUMENTATION_KEY",
      endpointUrl: "TelemetryChannel_Endpoint_Address"
    }
    );window[aiName]=aisdk,aisdk.queue&&0===aisdk.queue.length&&aisdk.trackPageView({});
    </script>
    

    若要了解更多用于监视网站的高级配置,请查看 JavaScript SDK 参考一文。To learn more advanced configurations for monitoring websites, check out the JavaScript SDK reference article.

  3. 移动应用代码: 通过 按照此指南操作,使用 App Center SDK 收集应用中的事件,然后将这些事件的副本发送到 Application Insights 进行分析。Mobile app code: Use the App Center SDK to collect events from your app, then send copies of these events to Application Insights for analysis by following this guide.

  4. 获取遥测: 在调试模式下运行项目几分钟,并在“Application Insights”中的“概述”边栏选项卡中查找结果。Get telemetry: Run your project in debug mode for a few minutes, and then look for results in the Overview blade in Application Insights.

    发布应用以监视应用性能,并查看用户使用该应用在执行哪些操作。Publish your app to monitor your app's performance and find out what your users are doing with your app.

备注

可以将 TelemetryChannel_Endpoint_Address 的占位符值替换为此文档中 Azure 中国区的实际终结点地址。You can replace the placeholder value for TelemetryChannel_Endpoint_Address with the actual endpoint address for Azure China region in this doc.

在遥测中包括用户和会话 IDInclude user and session ID in your telemetry

若要持续跟踪用户,Application Insights 需要识别用户的方法。To track users over time, Application Insights requires a way to identify them. 事件工具是唯一不需要用户 ID 或会话 ID 的使用情况工具。The Events tool is the only Usage tool that does not require a user ID or a session ID.

开始使用此过程发送用户 ID 和会话 ID。Start sending user and session IDs using this process.

浏览用户人口和统计信息Explore usage demographics and statistics

查明人们何时使用应用,他们对哪些页面最感兴趣,用户在哪里以及他们使用什么浏览器和操作系统。Find out when people use your app, what pages they're most interested in, where your users are located, what browsers and operating systems they use.

“用户和会话”报告按页面或自定义事件筛选数据,并按位置、环境和页面等属性将数据分段。The Users and Sessions reports filter your data by pages or custom events, and segment them by properties such as location, environment, and page. 也可以添加自己的筛选器。You can also add your own filters.

屏幕截图,显示虚构公司的“用户概述”页。

右侧的见解指出了数据集中的相关模式。Insights on the right point out interesting patterns in the set of data.

  • “用户”报告统计所选时间段内访问页面的唯一用户数目。The Users report counts the numbers of unique users that access your pages within your chosen time periods. 对于 Web 应用,将使用 Cookie 统计用户。For web apps, users are counted by using cookies. 如果某个用户使用不同的浏览器或客户端计算机访问站点或者清除了其 Cookie,该用户会被统计多次。If someone accesses your site with different browsers or client machines, or clears their cookies, then they will be counted more than once.
  • “会话”报告统计访问站点的用户会话数。The Sessions report counts the number of user sessions that access your site. 会话是指某个用户的活动时段,如果有半个小时以上处于非活动状态,会话会被终止。A session is a period of activity by a user, terminated by a period of inactivity of more than half an hour.

有关用户、会话和事件工具的详细信息More about the Users, Sessions, and Events tools

保留 - 有多少个回头用户?Retention - how many users come back?

保留可帮助你根据特定时间桶内执行某个业务操作的用户队列,了解用户回头使用其应用的频率。Retention helps you understand how often your users return to use their app, based on cohorts of users that performed some business action during a certain time bucket.

  • 了解哪些特定的功能导致某些用户比其他用户回来得更频繁Understand what specific features cause users to come back more than others
  • 基于真实的用户数据构成假设Form hypotheses based on real user data
  • 确定产品中是否存在保留问题Determine whether retention is a problem in your product

屏幕截图,显示“保留概述”页,其中显示了有关用户返回使用其应用的频率的信息。

使用顶部的保留控件可以定义特定的事件和时间范围来计算保留。The retention controls on top allow you to define specific events and time range to calculate retention. 中间的图表根据指定的时间范围提供总体保留百分比的视觉表示形式。The graph in the middle gives a visual representation of the overall retention percentage by the time range specified. 底部的图表显示给定时间段内的各个保留。The graph on the bottom represents individual retention in a given time period. 这种详细程度可让你更细致地了解用户正在做什么,以及哪些因素可能会影响用户回头。This level of detail allows you to understand what your users are doing and what might affect returning users on a more detailed granularity.

有关保留工具的详细信息More about the Retention tool

自定义业务事件Custom business events

要明确了解用户将应用用于什么目的,可以插入代码行来记录自定义事件。To get a clear understanding of what users do with your app, it's useful to insert lines of code to log custom events. 这些事件可以跟踪任何活动,包括详细的用户操作(例如单击特定的按钮),以及更重要的业务活动(例如购买活动或游戏获胜)。These events can track anything from detailed user actions such as clicking specific buttons, to more significant business events such as making a purchase or winning a game.

尽管在某些情况下页面视图可呈现有用的事件,但一般情况下这些事件并不真实。Although in some cases, page views can represent useful events, it isn't true in general. 用户无需购买产品即可打开产品页面。A user can open a product page without buying the product.

使用特定的业务事件可以绘制用户在站点中的进度图表。With specific business events, you can chart your users' progress through your site. 可以了解用户对不同选项的偏好,以及他们在哪个位置放弃了应用或者遇到了问题。You can find out their preferences for different options, and where they drop out or have difficulties. 了解这些信息后,可以针对开发积压工作的优先级做出明智的决策。With this knowledge, you can make informed decisions about the priorities in your development backlog.

可以在应用的客户端记录事件:Events can be logged from the client side of the app:


    appInsights.trackEvent("ExpandDetailTab", {DetailTab: tabName});

也可以在服务器端进行记录:Or from the server side:

    var tc = new Microsoft.ApplicationInsights.TelemetryClient();
    tc.TrackEvent("CreatedAccount", new Dictionary<string,string> {"AccountType":account.Type}, null);
    ...
    tc.TrackEvent("AddedItemToCart", new Dictionary<string,string> {"Item":item.Name}, null);
    ...
    tc.TrackEvent("CompletedPurchase");

可将属性值附加到这些事件,以便在门户检查事件时可以筛选或拆分事件。You can attach property values to these events, so that you can filter or split the events when you inspect them in the portal. 此外,已将一组标准属性(例如匿名用户 ID)附加到每个事件,以便你跟踪单个用户的活动序列。In addition, a standard set of properties is attached to each event, such as anonymous user ID, which allows you to trace the sequence of activities of an individual user.

详细了解自定义事件属性Learn more about custom events and properties.

分解事件Slice and dice events

在“用户”、“会话”和“事件”工具中,可按用户、事件名称和属性分解自定义事件。In the Users, Sessions, and Events tools, you can slice and dice custom events by user, event name, and properties. 屏幕截图,显示虚构公司的“用户概述”页。Screen capture shows the Users Overview page for a fictitious company.

在应用中设计遥测Design the telemetry with the app

设计应用的每项功能时,请考虑如何衡量它在用户那里取得的成功。When you are designing each feature of your app, consider how you are going to measure its success with your users. 决定需要记录哪些事件,并一开始就在应用中针对这些事件编写跟踪调用。Decide what business events you need to record, and code the tracking calls for those events into your app from the start.

A | B 测试A | B Testing

如果不知道哪个功能变体将更有成效,可同时发布这两项,使不同用户都能访问它们。If you don't know which variant of a feature will be more successful, release both of them, making each accessible to different users. 评估每个项的成效,并移至统一的版本。Measure the success of each, and then move to a unified version.

对于此技术,可将不同的属性值附加到应用的每个版本所发送的所有遥测数据。For this technique, you attach distinct property values to all the telemetry that is sent by each version of your app. 为此,可以在活动的 TelemetryContext 中定义属性。You can do that by defining properties in the active TelemetryContext. 这些默认属性将添加到应用程序发送的每个遥测消息(并非仅自定义消息),不过标准遥测也是这样。These default properties are added to every telemetry message that the application sends - not just your custom messages, but the standard telemetry as well.

在 Application Insights 门户中根据属性值筛选和拆分数据,以便比较不同的版本。In the Application Insights portal, filter and split your data on the property values, so as to compare the different versions.

为此,请设置遥测初始值设定项To do this, set up a telemetry initializer:

ASP.NET 应用ASP.NET apps

    // Telemetry initializer class
    public class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry item)
            {
                var itemProperties = item as ISupportProperties;
                if (itemProperties != null && !itemProperties.Properties.ContainsKey("AppVersion"))
                {
                    itemProperties.Properties["AppVersion"] = "v2.1";
                }
            }
    }

在 Global.asax.cs 等 Web 应用初始值设定项中:In the web app initializer such as Global.asax.cs:


    protected void Application_Start()
    {
        // ...
        TelemetryConfiguration.Active.TelemetryInitializers
         .Add(new MyTelemetryInitializer());
    }

ASP.NET Core 应用ASP.NET Core apps

备注

使用 ApplicationInsights.config 或使用 TelemetryConfiguration.Active 添加初始值对 ASP.NET Core 应用程序无效。Adding initializer using ApplicationInsights.config or using TelemetryConfiguration.Active is not valid for ASP.NET Core applications.

对于 ASP.NET Core 应用程序,添加新的 TelemetryInitializer 是通过将其添加到依赖关系注入容器来完成的,如下所示。For ASP.NET Core applications, adding a new TelemetryInitializer is done by adding it to the Dependency Injection container, as shown below. 这是在 Startup.cs 类的 ConfigureServices 方法中完成的。This is done in ConfigureServices method of your Startup.cs class.

 using Microsoft.ApplicationInsights.Extensibility;
 using CustomInitializer.Telemetry;
 public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
}

所有新的 TelemetryClient 会自动添加指定的属性值。All new TelemetryClients automatically add the property value you specify. 单个遥测事件可以替代默认值。Individual telemetry events can override the default values.

后续步骤Next steps