发送用户上下文 ID 以启用 Azure Application Insights 中的使用体验Send user context IDs to enable usage experiences in Azure Application Insights

跟踪用户Tracking users

Application Insights 通过一套产品使用工具监视并跟踪用户:Application Insights enables you to monitor and track your users through a set of product usage tools:

为了跟踪用户在各个时间进行的操作,Application Insights 需要每个用户或会话的 ID。In order to track what a user does over time, Application Insights needs an ID for each user or session. 在每个自定义事件或页面视图中包含以下 ID。Include the following IDs in every custom event or page view.

  • 用户、漏斗图、保留和队列:包括用户 ID。Users, Funnels, Retention, and Cohorts: Include user ID.
  • 会话:包括会话 ID。Sessions: Include session ID.

备注

这是一篇高级文章,概述了使用 Application Insights 跟踪用户活动的手动步骤。This is an advanced article outlining the manual steps for tracking user activity with Application Insights. 对于许多 Web 应用程序,可能不需要这些步骤,因为默认的服务器端 SDK 与客户端/浏览器端 JavaScript SDK 结合使用,通常足以自动跟踪用户活动。With many web applications these steps may not be required, as the default server-side SDKs in conjunction with the Client/Browser-side JavaScript SDK, are often sufficient to automatically track user activity. 如果除了服务器端 SDK 之外还没有配置客户端监视,请先执行该操作并测试用户行为分析工具是否按预期执行。If you haven't configured client-side monitoring in addition to the server-side SDK, do that first and test to see if the user behavior analytics tools are performing as expected.

选择用户 IDChoosing user IDs

应在各用户会话中保留用户 ID,以便跟踪各个时间的用户行为。User IDs should persist across user sessions to track how users behave over time. 可通过多种方法保留 ID。There are various approaches for persisting the ID.

  • 服务中已有的用户定义。A definition of a user that you already have in your service.
  • 如果服务有权访问浏览器,那么它可以向浏览器传递包含 ID 的 cookie。If the service has access to a browser, it can pass the browser a cookie with an ID in it. 只要 cookie 保留在用户的浏览器中,ID 将会保留。The ID will persist for as long as the cookie remains in the user's browser.
  • 如有必要,每个会话都可以使用一个新 ID,但是会限制有关用户的结果。If necessary, you can use a new ID each session, but the results about users will be limited. 例如,不能查看用户各个时间的行为变化。For example, you won't be able to see how a user's behavior changes over time.

ID 必须是 GUID 或另一个复杂程度足以唯一地标识每个用户的字符串。The ID should be a Guid or another string complex enough to identify each user uniquely. 例如,可能是一长串随机数。For example, it could be a long random number.

如果 ID 包含用户的个人标识信息,则不适合将该值作为用户 ID 发送到 Application Insights。If the ID contains personally identifying information about the user, it is not an appropriate value to send to Application Insights as a user ID. 可以将该 ID 作为已经过身份验证的用户 ID 进行发送,但是这不满足使用方案的用户 ID 要求。You can send such an ID as an authenticated user ID, but it does not fulfill the user ID requirement for usage scenarios.

ASP.NET 应用:在 ITelemetryInitializer 中设置用户上下文ASP.NET apps: Setting the user context in an ITelemetryInitializer

创建遥测初始化程序,详见此处Create a telemetry initializer, as described in detail here. 通过请求遥测传递会话 ID,并设置 Context.User.Id 和 Context.Session.Id。Pass the session ID through the request telemetry, and set the Context.User.Id and the Context.Session.Id.

此示例将用户 ID 设置为在会话后过期的标识符。This example sets the user ID to an identifier that expires after the session. 如果可能,请使用在各会话中保留的用户 ID。If possible, use a user ID that persists across sessions.

遥测初始化程序Telemetry initializer

using System;
using System.Web;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;

namespace MvcWebRole.Telemetry
{
  /*
   * Custom TelemetryInitializer that sets the user ID.
   *
   */
  public class MyTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        var ctx = HttpContext.Current;

        // If telemetry initializer is called as part of request execution and not from some async thread
        if (ctx != null)
        {
            var requestTelemetry = ctx.GetRequestTelemetry();
 
            // Set the user and session ids from requestTelemetry.Context.User.Id, which is populated in Application_PostAcquireRequestState in Global.asax.cs.
            if (requestTelemetry != null && !string.IsNullOrEmpty(requestTelemetry.Context.User.Id) &&
                (string.IsNullOrEmpty(telemetry.Context.User.Id) || string.IsNullOrEmpty(telemetry.Context.Session.Id)))
            {
                // Set the user id on the Application Insights telemetry item.
                telemetry.Context.User.Id = requestTelemetry.Context.User.Id;
 
                // Set the session id on the Application Insights telemetry item.
                telemetry.Context.Session.Id = requestTelemetry.Context.User.Id;
            }
        }
    }
  }
}

Global.asax.csGlobal.asax.cs

using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MvcWebRole.Telemetry
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
 
        protected void Application_PostAcquireRequestState()
        {
            var requestTelemetry = Context.GetRequestTelemetry();
 
            if (HttpContext.Current.Session != null && requestTelemetry != null && string.IsNullOrEmpty(requestTelemetry.Context.User.Id))
            {
                requestTelemetry.Context.User.Id = Session.SessionID;
            }
        }
    }
}

后续步骤Next steps