【问题标题】:Application insights in Console/WPF application with DependencyTracking具有 DependencyTracking 的控制台/WPF 应用程序中的应用程序洞察力
【发布时间】:2021-04-08 05:22:45
【问题描述】:

我有一个应用程序洞察配置,我正在尝试在 .NET 4.8 WPF 应用程序中工作。一切似乎都可以正常传输(包括实时指标数据),但不幸的是,我无法成功让系统传输我的 SQL 查询以及 EntityFramework6 正在执行的依赖信息。

我注意到following link 上提到了

对于 ASP.NET 应用程序,完整的 SQL 查询文本是通过 字节码检测的帮助,这需要使用 检测引擎或使用 Microsoft.Data.SqlClient NuGet 包而不是 System.Data.SqlClient 库。

鉴于我正在使用 EntityFramework(取决于 System.Data.SqlClient)但我已经安装了 Microsoft.ApplicationInsights.Agent_**,这显然对我来说是不可能的(我不认为?)这个问题正如上面的链接所暗示的那样。

当我进一步查看 Azure 中提供的数据时,我注意到它被标记为 rddf:2.17.0-32,这表明代理无法正常工作。

我的初始化代码如下所示:

public static TelemetryConfiguration CreateConfig(string instrumentationKey, string authenticationApiKey)
{
    var config = new TelemetryConfiguration()
    {
        ConnectionString = $"InstrumentationKey={instrumentationKey};IngestionEndpoint=https://australiaeast-0.in.applicationinsights.azure.com/",
        TelemetryChannel = new ServerTelemetryChannel()
        {
            DeveloperMode = true
        },
               
    };

    var dependencyTrackingModule = new DependencyTrackingTelemetryModule()
    {
        EnableSqlCommandTextInstrumentation = true
    };

    // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
    dependencyTrackingModule.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");

    // enable known dependency tracking, note that in future versions, we will extend this list. 
    dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
    dependencyTrackingModule.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

    // initialize the module
    dependencyTrackingModule.Initialize(config);

    QuickPulseTelemetryProcessor quickPulseProcessor = null;
    config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
        .Use((next) =>
        {
            quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
            return quickPulseProcessor;
        })
        .Build();

    var quickPulseModule = new QuickPulseTelemetryModule()
    {
        AuthenticationApiKey = authenticationApiKey
    };

    quickPulseModule.Initialize(config);
    quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);

    config.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
    config.TelemetryInitializers.Add(new BuildInfoConfigComponentVersionTelemetryInitializer());

    return config;
}

任何人都可以就我可能做错的事情提供任何意见吗?

【问题讨论】:

  • 看看this issue,看看有没有帮助。
  • 嗨@IvanYang,感谢您提供的信息,看来这可能是我的问题,但我实际上使用了应该解决问题的版本。我已经在github上发布了,看看会发生什么。
  • 您的问题中似乎没有任何实际关于 WPF的内容。请不要包含没有严格描述问题的标签关于。
  • @PeterDuniho 看起来这是一个公平的电话,但我的反驳是,我与 WPF 相关的特定情况可能存在一些限制,所以虽然是的,但我的代码都没有与 WPF 直接相关,但似乎仍然合理标记它。例如,如果见解对 WPF 和 EF6 有一些限制怎么办?
  • 这个论点几乎可以用于任何个问题。 IE。 “我不知道我的问题的答案,所以我不能排除这是因为它是一个 WPF 程序”。不,不会飞。您不是在询问 WPF 本身。您需要的专家是了解 Insights 的专家,而不是 WPF。使用 WPF 进行标记只会使想要回答 WPF 问题但对 Insights 一无所知的 WPF 专家的提要变得混乱。您在问题(甚至标题)中提到了 WPF,这完全足以解决涉及 WPF 的可能性很小。

标签: c# entity-framework azure-application-insights appinsights


【解决方案1】:

当我们都在等待洞察团队的潜在解决方案时,我想我会分享我的解决方案。

我主要关心的是在跟踪数据库操作时更好地控制所提供的数据。我能够在 EntityFramework 中找到一个名为 DbInterception 的简洁小功能。

此单例允许您注册拦截器,这些拦截器可以跟踪和分析提供给 EntityFramework 的查询。

最终实现就这么简单:

internal class InsightsOperation 
{
    public InsightsOperation(DbCommand command, Stopwatch stopwatch)
    {
        this.Command = command;
        this.Stopwatch = stopwatch;
    }

    public DbCommand Command { get; }
    public Stopwatch Stopwatch { get; }
    public DateTime StartTime { get; } = DateTime.UtcNow;
}

public class AppInsightsInterceptor : IDbCommandInterceptor
{

    private ConcurrentDictionary<Guid, InsightsOperation> _pendingOperations = new ConcurrentDictionary<Guid, InsightsOperation>();
    private ITelemetryManager _telemetryManager;

    public AppInsightsInterceptor(ITelemetryManager telemetryManager)
    {
        this._telemetryManager = telemetryManager ?? throw new ArgumentNullException(nameof(telemetryManager));
    }

    private void StartTimingOperation<T>(DbCommand command, DbCommandInterceptionContext<T> interceptionContext)
    {
        if (!(command is SQLiteCommand))
        {
            var id = Guid.NewGuid();
            var stopwatch = Stopwatch.StartNew();

            interceptionContext.SetUserState(nameof(AppInsightsInterceptor), id);
            this._pendingOperations.TryAdd(id, new InsightsOperation(command, stopwatch));
        }
    }

    private void StopTimingOperation<T>(DbCommand command, DbCommandInterceptionContext<T> interceptionContext)
    {
        if (!(command is SQLiteCommand))
        {
            var id = (Guid)interceptionContext.FindUserState(nameof(AppInsightsInterceptor));
            if (this._pendingOperations.TryRemove(id, out InsightsOperation operation))
            {
                operation.Stopwatch.Stop();
                this._telemetryManager.TrackDependency(command.CommandType.ToString(),
                    "SQL",
                    command.CommandText,
                    new DateTimeOffset(operation.StartTime),
                    operation.Stopwatch.Elapsed,
                    interceptionContext.Exception == null);
            }
        }
    }

    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        this.StopTimingOperation(command, interceptionContext);
    }

    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        this.StartTimingOperation(command, interceptionContext);            
    }

    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        this.StopTimingOperation(command, interceptionContext);
    }

    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        
        this.StartTimingOperation(command, interceptionContext);
            
    }

    public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        this.StopTimingOperation(command, interceptionContext);
    }

    public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        this.StartTimingOperation(command, interceptionContext);
    }
}

请注意,此注册是单例的,如果您想排除数据,您需要了解所有 DbContext 实例都会命中拦截器。

在我的例子中,我想排除代码中看到的 SQLite 查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多