如何为 Azure Function 中的 Application Insight 中的请求设置 user_AuthenticatedId?

发布于 2025-01-11 18:57:02 字数 1115 浏览 0 评论 0原文

我使用 Azure Functions 为移动客户端提供服务,在它们之间有一个 Azure API 管理。我还使用 Application Insights 来监视传入后端的请求。默认日志记录会在 AppInsights 中创建请求,但某些字段(例如 user_AuthenticatedId)为空,这对我来说可能有用。另外,在 AppInsights 的“用户”页面上,我只能看到一个 id 为“<未定义>”的用户

Application Insight 中的请求如下所示

在 Azure Function 中,我获得一个访问令牌,其中包含用户的 id,我想将其设置为 user_AuthenticatedId。我尝试配置 TelemetryClient 并启动一个新的 Operation,其中设置了 operation.Telemetry.Context.User.AuthenticatedUserId = _userID; 但使用此请求在 AppInsights 上重复。

是否可以从Azure函数的代码中设置默认创建的请求遥测的属性?

我的函数方法如下所示:

[FunctionName("TestFunction")]
public async Task<IActionResult> RunAsync(
        [HttpTrigger(AuthorizationLevel.Anonymous, HttpMethod.Get)] HttpRequest req, ILogger log)
{
    try
    {
        //do some stuff
        return new OkObjectResult(<result>);
    }
    catch (Exception ex)
    {
        //handle exception
        return new ObjectResult(<result>);
    }
}

I'm using Azure Functions to serve mobile clients and between them, there is an Azure API Management. I also use Application Insights to monitor requests coming to the backend. The default logging creates requests in AppInsights but some field (for example user_AuthenticatedId) is empty which could be useful for me. Also on the Users page in AppInsights I can only see one user where the id is "<undefined>"

Requests in Application Insight look like this

In the Azure Function, I get an access token that contains the id of the user and I want to set this as the user_AuthenticatedId. I tried to configure a TelemetryClient and start a new Operation where I set the operation.Telemetry.Context.User.AuthenticatedUserId = _userID; but with this, the request was duplicated on AppInsights.

Is it possible from the code of the Azure Function to set the properties of the request telemetry which is created by default?

My Function methods look like this:

[FunctionName("TestFunction")]
public async Task<IActionResult> RunAsync(
        [HttpTrigger(AuthorizationLevel.Anonymous, HttpMethod.Get)] HttpRequest req, ILogger log)
{
    try
    {
        //do some stuff
        return new OkObjectResult(<result>);
    }
    catch (Exception ex)
    {
        //handle exception
        return new ObjectResult(<result>);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听不够的曲调 2025-01-18 18:57:02

要在日志终端中查看,请使用以下代码片段:

log.LogInformation(tc.Context.User.AuthenticatedUserId);

要在应用程序洞察中查看,请使用 TrackTraceTrackEvent

tc.TrackEvent("---------track-event" + tc.Context.User.AuthenticatedUserId);
tc.TrackTrace("---------track-trace" + tc.Context.User.AuthenticatedUserId);

这里tc是遥测客户端。
例如,这是我的示例代码:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using System.Security.Claims;
using ikvm.runtime;
using Microsoft.Azure.WebJobs.Hosting;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace SuryaFunctionApp3
{
    public class Function1
    {
        private readonly TelemetryClient tc;

        public Function1(TelemetryConfiguration config)
        {
            this.tc = new TelemetryClient(config);
        }

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ClaimsPrincipal claimsPrincipal)
        {

            tc.Context.User.AuthenticatedUserId = "---userid---";

            log.LogInformation(tc.Context.User.AuthenticatedUserId);
            tc.TrackEvent("---------track-event" + tc.Context.User.AuthenticatedUserId);
            tc.TrackTrace("---------track-trace" + tc.Context.User.AuthenticatedUserId);

            string responseMessage = "This HTTP triggered function executed successfully";

            return new OkObjectResult(responseMessage);
        }

        public class MyStartup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder)
            {
                var configDescriptor = builder.Services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));
                if (configDescriptor?.ImplementationFactory != null)
                {
                    var implFactory = configDescriptor.ImplementationFactory;
                    builder.Services.Remove(configDescriptor);
                    builder.Services.AddSingleton(provider =>
                    {
                        if (implFactory.Invoke(provider) is TelemetryConfiguration config)
                        {
                            var newConfig = TelemetryConfiguration.CreateDefault();
                            newConfig.ApplicationIdProvider = config.ApplicationIdProvider;
                            newConfig.InstrumentationKey = config.InstrumentationKey;

                            return newConfig;
                        }
                        return null;
                    });
                }
            }
        }

To see in the logs terminal, use below code snippet :

log.LogInformation(tc.Context.User.AuthenticatedUserId);

To see it in application insights, use TrackTrace or TrackEvent:

tc.TrackEvent("---------track-event" + tc.Context.User.AuthenticatedUserId);
tc.TrackTrace("---------track-trace" + tc.Context.User.AuthenticatedUserId);

Here tc is Telemetry Client.
For example, here is the sample code I have :

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using System.Security.Claims;
using ikvm.runtime;
using Microsoft.Azure.WebJobs.Hosting;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace SuryaFunctionApp3
{
    public class Function1
    {
        private readonly TelemetryClient tc;

        public Function1(TelemetryConfiguration config)
        {
            this.tc = new TelemetryClient(config);
        }

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ClaimsPrincipal claimsPrincipal)
        {

            tc.Context.User.AuthenticatedUserId = "---userid---";

            log.LogInformation(tc.Context.User.AuthenticatedUserId);
            tc.TrackEvent("---------track-event" + tc.Context.User.AuthenticatedUserId);
            tc.TrackTrace("---------track-trace" + tc.Context.User.AuthenticatedUserId);

            string responseMessage = "This HTTP triggered function executed successfully";

            return new OkObjectResult(responseMessage);
        }

        public class MyStartup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder)
            {
                var configDescriptor = builder.Services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));
                if (configDescriptor?.ImplementationFactory != null)
                {
                    var implFactory = configDescriptor.ImplementationFactory;
                    builder.Services.Remove(configDescriptor);
                    builder.Services.AddSingleton(provider =>
                    {
                        if (implFactory.Invoke(provider) is TelemetryConfiguration config)
                        {
                            var newConfig = TelemetryConfiguration.CreateDefault();
                            newConfig.ApplicationIdProvider = config.ApplicationIdProvider;
                            newConfig.InstrumentationKey = config.InstrumentationKey;

                            return newConfig;
                        }
                        return null;
                    });
                }
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文