问题描述
我们在 Azure App Insights 中使用智能检测器在我们的应用出现异常时生成一些警报。但是,在我们的代码中存在一些故意的故障,我们抛出 403。有没有办法在 Application Insights 中修改这些“智能警报”,以便可以在其检测逻辑中排除这些已知故障?我们有一个与这些预期失败相关的特定异常类型,如果有办法做到这一点,我们可以轻松地使用它在异常检测中排除这些,但我在 UI 上找不到执行此操作的选项。
感谢您的指点。
解决方法
您不能直接从 Azure 门户执行此操作,但您需要实现一个 Telemetry Processor,它可以帮助您覆盖遥测属性集。
如果请求标志为失败,响应代码 = 403。但如果您想将其视为成功,您可以提供设置成功属性的遥测初始值设定项。
定义初始化程序
C#
using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
namespace MvcWebRole.Telemetry
{
/*
* Custom TelemetryInitializer that overrides the default SDK
* behavior of treating response codes >= 400 as failed requests
*
*/
public class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var requestTelemetry = telemetry as RequestTelemetry;
// Is this a TrackRequest() ?
if (requestTelemetry == null) return;
int code;
bool parsed = Int32.TryParse(requestTelemetry.ResponseCode,out code);
if (!parsed) return;
if (code >= 400 && code < 500)
{
// If we set the Success property,the SDK won't change it:
requestTelemetry.Success = true;
// Allow us to filter these requests in the portal:
requestTelemetry.Properties["Overridden400s"] = "true";
}
// else leave the SDK to set the Success property
}
}
}
在 ApplicationInsights.config 中:
XML 复制
<ApplicationInsights>
<TelemetryInitializers>
<!-- Fully qualified type name,assembly name: -->
<Add Type="MvcWebRole.Telemetry.MyTelemetryInitializer,MvcWebRole"/>
...
</TelemetryInitializers>
</ApplicationInsights>
有关详细信息,您可以参考此Document。