我正在开发 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 和查询跟踪(全部)时,我没有看到我正在设置的跟踪消息。
我做错了什么吗?
我用相同的代码重现并得到了预期的结果,如下:
[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);
}
应用见解:
查询轨迹:
您不应该使用无参数构造函数实例化
TelemetryClient
。请改用依赖注入。
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.");
[..]
}
请仔细阅读文档中的本节。