首页 > 解决方案 > 如何从 FunctionApp 设置会话 ID 或在 ApplicationInsights 中创建自定义字段

问题描述

功能应用程序如下:

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, ILogger log)
    {
     log.LogInformation("Information", infoOBject);
    }

local.json 文件有 applicationInstrument 键。

如何在应用程序洞察中为“请求”条目添加附加字段并设置“Session_Id”。

标签: c#azureazure-functionsazure-application-insightstelemetry

解决方案


您需要使用 Application Insights 中的一些自定义日志记录

一、安装Nuget包

Install-Package Microsoft.ApplicationInsights -Version 2.7.2

然后像下面一样更改上面的代码

public static class Function1
    {
        private static TelemetryClient GetTelemetryClient()
        {
            var telemetryClient = new TelemetryClient();
            telemetryClient.InstrumentationKey = "<your actual insight instrumentkey>";
            telemetryClient.Context.Session.Id = "124556";
            //update 1-Custom properties- Start
            telemetry.Context.Properties["tags"] = "PROD";
            telemetry.Context.Properties["userCorelateId"]="1234"; 
            //update 1-Custom properties- Ends                
            return telemetryClient;
            }       


        [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
        {
            var appInsights = GetTelemetryClient();           
            appInsights.TrackRequest(req.RequestUri.ToString(), DateTime.Now, Stopwatch.StartNew().Elapsed, "200", true);
            return req.CreateResponse(HttpStatusCode.OK, "message");

        }


    }

终于在appinsights

在此处输入图像描述

更新 1

您还可以在请求中添加您自己的其他属性。

E.g,
telemetry.Context.Properties["tags"] = "PROD";

这将在属性下添加customDimension属性

在此处输入图像描述

你也可以参考这里


推荐阅读