【问题标题】:How to set session id or create custom field into ApplicationInsights from FunctionApp如何从 FunctionApp 设置会话 ID 或在 ApplicationInsights 中创建自定义字段
【发布时间】:2026-01-03 07:50:02
【问题描述】:

功能应用如下:

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# azure azure-functions azure-application-insights telemetry


    【解决方案1】:

    您需要使用 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属性下添加属性

    你也可以refer here

    【讨论】:

    • 此记录两个请求。默认情况下已经创建了一个请求。可能是因为配置了instrumentKey。通过执行上述操作,它会创建另一个请求。任何解决方案,只有一个“请求”并具有 sessionId ?
    • 另外,我们是否可以在“请求”中添加类似于 session_id 的附加列。比如,userCorelateId 列?
    • @user3711357 这里的两个请求是什么意思?我只能看到一个请求,它是由appInsights.TrackRequest 创建的
    • @user3711357 我已经通过添加自定义属性更新了我的答案。希望这会有所帮助
    • 是否需要调用 appInsights.Flush() 或不需要?