处于调试模式时的 Application Insights

Application Insights when in debug mode

我刚刚在我的 MVC 应用程序中启用了 Application Insights,并注意到在本地调试时,跟踪信息正在我的 Azure Application Insight 中捕获。

在调试模式下,我想阻止我的应用程序在我的 Azure Application Insight 中记录事件,但仍会在 Visual Studio 中的诊断工具 > 事件 window 中显示事件和日志记录信息.

我已经尝试了以下方法,虽然这会阻止在我的 Azure AI 中捕获事件,Visual Studio 不再在事件 window 中显示调试信息。

 protected void Application_Start()
 {
        #if DEBUG
        TelemetryConfiguration.Active.DisableTelemetry = true;
        #endif
 }

我上网找答案无果。希望有人能帮忙。

最便宜的方法是将 Instrumentation Key 设置为全 0。没有 NULL iKey,因此它实际上只会删除消息。

00000000-0000-0000-0000-000000000000

如果您想使用 Application_Start(),您可以使用 #DEBUG 指令或使用 System.Diagnostics.Debugger.IsAttached 属性。然而,这种方法并不完全可靠。您可以尝试,但您的体验可能不一致。

如果你有时间,你应该制作一个 TelemetryInitializer,它会根据是否连接调试器来更改 Instrumentation Key。这将确保仅当您在调试会话中时才会发生这种情况。这样,如果您不小心将 Debug 发布到生产环境中,您就不会丢失遥测数据。

public class CustomeWebRequestTelemetryModule :  Microsoft.ApplicationInsights.Extensibility.ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if (telemetry != null && System.Diagnostics.Debugger.IsAttached)
        {
            telemetry.Context.InstrumentationKey = "00000000-0000-0000-0000-000000000000";
        }
    }
}

您在 Application Insights 中发送遥测数据有什么顾虑?例如,您可以有一个单独的 Application Insights 资源(由检测密钥标识)仅用于您的调试体验,而在生产中,将检测密钥切换为指向生产资源。

或者,我们最近推出了 "local mode" - 无需连接到 Azure 即可在 Visual Studio 中使用 Application Insights 的功能。在这种情况下,上次调试会话的遥测数据将保留在您的本地计算机上,并可用于搜索和集成到 Diagnostics Hub 中。看这里:https://azure.microsoft.com/en-us/documentation/articles/app-insights-release-notes-vsix/#version-43

我认为,为了实现这一点,您需要从 applicationinsights.xml 中删除检测密钥,但我不是 100% 确定。将要求我的同事在此处添加更多信息......让我们知道这是否是您正在寻找的。 奥列格

@DebugThings 的回答将(大部分)起作用,尽管如果你使用 0 作为 ikey,你 可能 仍在发送遥测,但它 可能 也被 AI 后端拒绝为无效的 ikey。

就个人而言,最好的解决方案是创建一个单独的 "debug" iKey,并在以调试模式构建的代码中改用该 iKey。

protected void Application_Start()
{
    #if DEBUG
    TelemetryConfiguration.Active.InstrumentationKey = "your debug ikey";
    #endif
}

这样,您可以 "debug" 您发送的任何遥测数据都不会污染您的生产环境,并且在发布版本中,您的配置文件中的 iKey 仍将被使用。这可让您确保发送正确的自定义属性/指标,而不会用完此时允许的固定数量。

这里有一篇博客post关于使用配置根据环境等将数据发送到不同的地方:

https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions/

这里有一个类似的问题,答案也类似: