我遇到了一个我不熟悉的问题。
因此,我正在尝试记录来自测试 Azure 函数的异常,但是当我抛出异常并返回 400 错误请求时,应用程序洞察将日志注册为成功请求。
据我了解,它可能是注册函数的成功运行,但我不明白的是我应该如何记录异常。
所以到目前为止我所做的就是这个。
(从现在开始,我将把 Application Insights 称为 AI)
我首先创建了一个 AI 资源。
然后我拿起仪器键并将其应用于我的功能的应用程序设置。
之后,我将 AI NUGET 安装到我的函数 bu 创建 Projet.json 文件,然后粘贴类似这样的东西,它安装了必要的程序集等。
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.ApplicationInsights": "2.4.0"
}
}
}
}
在此之后,我在函数中初始化 TelemetryClient 并尝试在捕获中记录和异常:
引发:
string key = TelemetryConfiguration.Active.InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
TelemetryClient telemetry = new TelemetryClient() {
InstrumentationKey = key
};
抓住:
catch (Exception e)
{
Dictionary<string,string> properties = new Dictionary<string,string>();
properties.Add("Function Payload", data.ToString());
properties.Add("Function Exception", e.ToString());
telemetry.TrackException(e, properties);
return req.CreateResponse(HttpStatusCode.BadRequest, e);
}
测试运行我得到的功能:
2018-03-07T14:24:36.171 [Info] Function started (Id=0292b455-314d-4c4c-872a-2b8137a72305)
2018-03-07T14:24:37.092 [Info] Function completed (Success, Id=0292b455-314d-4c4c-872a-2b8137a72305, Duration=931ms)
在应用程序洞察中,我只能看到 StatusCode 的错误请求:500 但 400 个错误请求被记录为成功请求。
而且 TrackException 功能不记录任何自定义属性......
那么我错过了什么?
有关异常记录的更多详细信息:
@Mikhail 是对的,我们将其视为成功,因为该功能是成功的。我们不想使用状态码来猜测是否有成功的操作,所以我们寻找函数是否抛出异常。
Your exception isn't appearing in that screen because it hasn't been property correlated with this function execution. If you go to App Insights Analytics and query for that ExceptionTelemetry
, you should see it.
In order to correlate it with a specific function, you'd need to set the OperationId
, which is the same as the function's InvocationId
. There is a sample that shows how to do this with Events, Metrics, and Dependencies, but doing it for Exceptions is the same (you can ignore the User.Id
assignment): https://docs.microsoft.com/en-us/azure/azure-functions/functions-monitoring#custom-telemetry-in-c-functions
Update: From what you've shown of your function above, you may be able to get away with doing something like:
catch (Exception e)
{
log.Error("Function Payload " + data.ToString());
throw;
}
这将返回 500(而不是 400),Functions 会将跟踪记录到 Application Insights,然后记录异常以及请求失败。如果您没有TelemetryClient
在其他任何地方使用您的代码,则可以将其从代码中删除。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句