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

标签 c# azure azure-functions azure-application-insights

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

Requests in Application Insight look like this

在 Azure 函数中,我获得了一个包含用户 ID 的访问 token ,我想将其设置为 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>);
    }
}

最佳答案

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

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;
                    });
                }
            }
        }

关于c# - 如何为 Azure Function 中的 Application Insight 中的请求设置 user_AuthenticatedId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71350545/

相关文章:

c# - C# 中的 BitmapSource 对象出现问题

c# - 使用内部集合创建 where 谓词的动态查询

c# - MSBuild 后期构建

azure - ServiceInsight Azure 连接到 VM

function - Azure 函数 Blob 存储日期时间输出路径

Azure 函数失败和警告

c# - 查找 JSON 条目并添加嵌套元素

.net - 应用服务中的内存利用率是否可​​以提高

javascript - Angular websocket 无法在生产环境中与 Azure VM nginx 配合使用,但可以在本地使用

azure - 如何将 HttpTrigger 连接到设计器