c# - Visual Studio 中类库的 Application Insights

标签 c# azure-application-insights

我正在尝试设置和使用 application insights在类库项目中。我想在 visual studio 中调试时以离线模式使用它。

在遵循一些指南之后,我得到了这个:

(在 Engine.cs 的构造函数中——我的库的“主”类)

_telemetryClient = new TelemetryClient();

// Set session data:
_telemetryClient.Context.User.Id = Environment.UserName;
_telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
_telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();

然后在类的主要方法中:

var metrics = new Dictionary<string, double>();
var properties = new Dictionary<string, string>();
try
{
    // Do stuff and track metrics code...

    telemetryClient?.TrackEvent("Some Event", properties, metrics);
    _telemetryClient?.Flush();
    System.Threading.Thread.Sleep(1000);
}
catch (Exception exception)
{
    _telemetryClient?.TrackException(exception, properties, metrics);
    _telemetryClient?.Flush();
    throw;
}

由于我希望在使用库的调用代码中配置日志记录(例如 Azure key 等),因此该项目没有其他配置,也没有 applicationinsights.config。

但是,当我在 VS 中对此进行调试时,在选择“选择 Application Insights 资源”-> 上次调试 session 后,“Application Insights 搜索没有数据”。

最佳答案

为了让 VS 知道您的应用程序正在使用 application insights 并让调试器监视 AI 数据,您需要在项目即启动项目。

当调试器启动时,我们会查看启动的调试器类型是否是我们识别的类型,启动项目是否有任何 AI 配置。如果我们没有检测到 AI,AI 服务就会停止监视调试器,以防止它在没有 AI 的项目中无缘无故地减慢速度。

所以只需将 ApplicationInsights.config 文件添加到启动项目,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
    <!-- this file should NOT be set to copy output, it is here to allow the AI tools in Visual Studio to watch this project when debugging -->
</ApplicationInsights>

并在项目设置中将文件设置为“不复制”。它只需要在启动项目中存在,而不是在项目输出中。由于该文件未复制到输出目录,AI SDK 不会加载该文件,并且使用您在代码中用于配置 TelemetryClient 的任何设置。

此外,如果您在调试时使用 AI,我非常好确定您不需要Flush调用,我相信在 Debug模式下,我们寻找的输出是在记录遥测时写入的,而不是在发生刷新调用时写入的。

如果上述方法有效,当您调试时,Application Insights 工具栏按钮也应该显示它所看到的事件数量,即使调试搜索仅显示最近的 250 个事件。

关于c# - Visual Studio 中类库的 Application Insights,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41464771/

相关文章:

c# - RelativeSource 绑定(bind)适用于 Style 但不适用于 ControlTemplate

c# - 返回 HttpResponseMessage 并且配置了 Application Insights 时,WebAPI 响应永远不会完成

c# - WCF ServiceHost 似乎为每条消息调用 CustomCertificateValidator

c# - 使用 C# 和 Mono : IdentityMapper being used incorrectly 的 Hadoop 流式传输

c# - 如何强制在 maskedtextbox 中只允许数值?

asp.net - 应用程序洞察 : Filter website health checks?

c# - 如何配置 Application Insights 以从 .net 4.8 应用程序发送遥测数据

c# - C# 中的 ValueType 数组是堆还是栈?

azure - 使用 Application Insight (Microsoft Azure) 创建针对特定异常的警报

c# - 跟踪 Azure Functions 中的传出请求