从 Azure Function App 将自定义跟踪消息写入 Application Insight

问题描述 投票:0回答:3

我正在开发 Azure Function App,希望添加自定义消息/跟踪,以帮助调试和提高性能。这是我正在使用的代码:

var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackTrace("Alert Button Pressed by Device ->" + CloudObject.A, SeverityLevel.Warning, new Dictionary<string, string> { { "IoT Object", IOTMESSAGE } });

但是当我转到 Application Insight 和查询跟踪(全部)时,我没有看到我正在设置的跟踪消息。

我做错了什么吗?

azure azure-functions azure-application-insights azure-monitoring
3个回答
0
投票

我用相同的代码重现并得到了预期的结果,如下:

 [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            string name = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                .Value;
            var telemetry = new TelemetryClient();
            telemetry.TrackEvent("Loading HomeController-Index View");          
            telemetry.TrackTrace("Alert Button Pressed by Device ->" + CloudObject.A, SeverityLevel.Warning, new Dictionary<string, string> { { "IoT Object", IOTMESSAGE } });
            if (name == null)
            {
                // Get request body
                dynamic data = await req.Content.ReadAsAsync<object>();
                name = data?.name;
            }

            return name == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
        }

应用见解:

https://i.imgur.com/vWEqPNu.png

查询轨迹:

enter image description here


0
投票

还是不行。我收到此警告,这可能是一个问题吗?

我已经在应用程序洞察上设置了采样和数据 ap,我希望自定义跟踪消息忽略这些设置的限制

enter image description here


0
投票

您不应该使用无参数构造函数实例化

TelemetryClient
。请改用依赖注入。

  1. 确保您已添加 Microsoft.Azure.WebJobs.Logging.ApplicationInsights NuGet 包
  2. 确保设置了检测密钥 (APPINSIGHTS_INSTRUMENTATIONKEY)
  3. 在函数的构造函数中创建实例,例如:
       public HttpTrigger2(TelemetryConfiguration telemetryConfiguration)
       {
           this.telemetryClient = new TelemetryClient(telemetryConfiguration);
       }

完成 1 和 2 后,您还可以使用

ILogger
界面在应用程序洞察中创建跟踪遥测。您可以像这样注入记录器:

        [FunctionName("HttpTrigger2")]
        public Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
            HttpRequest req, ExecutionContext context, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            [..]
        }

请仔细阅读文档中的本节

© www.soinside.com 2019 - 2024. All rights reserved.