如何使用应用程序洞察跟踪azure函数中经过身份验证的用户?

时间:2018-02-16 12:11:52

标签: azure-functions azure-application-insights

我遵循了本指南(https://blogs.msdn.microsoft.com/visualstudioalmrangers/2017/10/10/azure-function-integrating-monitoring-with-application-insights/)以启用应用程序洞察。我还配置了我的功能应用程序,以使用Facebook,azure广告等的身份验证构建。但在应用程序洞察中,我没有看到任何经过身份验证的用户被开箱即用。当你有一个功能强大的app作为c#类库实现时,人们应该如何做到这一点?

1 个答案:

答案 0 :(得分:1)

我不确定您实施的内置身份验证究竟是如何运作的。 如果您想要the telemetry you send to App Insights in Azure Functions to have context - 例如Authenticated User - 我认为您现在无法获得这种开箱即用的功能。你需要自己添加它。

如果此UserId作为请求的一部分发送,您可以像这样添加它:

以某种方式从请求中获取经过身份验证的用户ID

[FunctionName("MyFunc")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "MyFunc")] HttpRequestMessage req, 
TraceWriter log, 
ExecutionContext context)
{
    var userId = ? // Somehow get the user from the request
    var tracer = new ApplicationInsightsTracer(userId);
    ...
}

App Insights包装器看起来应该是这样的

public class ApplicationInsightsTracer 
{
   private static readonly Lazy TelemetryClient = new 
                                     Lazy(InitTelemetryClient);

   public string UserId { get; set; }

   private static TelemetryClient InitTelemetryClient()
   {
            var telemetryClient = new 
                    TelemetryClient(TelemetryConfiguration.Active)
            {
                InstrumentationKey = ConfigurationManager.AppSettings
                                   ["APPINSIGHTS_INSTRUMENTATIONKEY"]
            };
            return telemetryClient;
        }
   }

   public ApplicationInsightsTracer(string userId) 
   {
       this.UserId = userId();
   }   

   public void TrackEvent(string name)
   {
      var eventTelemetry = new EventTelemetry(name);

      // Add context to the telemetry
      telemetry.Context.User.AuthenticatedUserId = UserId;

      TelemetryClient.Value.TrackEvent(eventTelemetry);
   }

}