c# - C#.NET 项目中我们真的需要 ApplicationInsights.config 文件吗?

标签 c# azure azure-application-insights

为了记录错误、信息、警告等信息,我们使用了 log4NET 库并记录在本地文件中。但我们的新要求是,我们需要将此信息与文件一起记录到 Azure Application Insights 中。

我们正在使用 .NET C# 库,

.NET C# 项目确实需要 ApplicationInsights.config 文件吗?如果不是,解决此问题的最佳方法是什么。

缓存applicationInsights.config是instrumentKey吗?如果是的话解决方案是什么?

场景 1:尝试不添加 ApplicationInsights.config 文件 输出:Log4Net 日志未添加到 Azure Application Insights 中

场景 2:尝试添加 ApplicationInsights.config 文件 输出:Log4Net 日志即将到来

场景 3:当我为 ApplicationInsights.Log4NetAppender 添加 Nuget API 时,它会创建 log4Net 部分并包含 AIAppender。我们有单独的 log4Net.config,它只有 File Appender。我们只想使用 log4Net.config 并从 App.Config 文件中删除 log4net 部分。 输出:我从 App.Config 中删除了 log4Net 部分,并将其添加到 log4Net.config 中并进行了测试,但日志未添加到 Application Insights 中。

场景 4:通过 C# 代码实现 TelemetryClient,ApplicationInsights.config 日志将出现在 Application Insights 中

TelemetryClient telemetryClient = new TelemetryClient();
telemetryClient.InstrumentKey =<Your Instrument Key>;

// To test
telemetryClient.TrackTrace("Test through code");

最佳答案

Application Insights 的配置可以通过配置文件和代码的任意组合来完成:仅其中之一,或另一个,或两者。

如果您在项目中找到 ApplicationInsights.config 文件,则它很可能是通过安装 Application Insights (AI) Nuget 包之一创建的,但您可以将其删除并进行相同的配置通过代码。

为了允许通过配置文件和代码混合配置,AI 客户端和配置类具有 GetDefault()Active 静态成员,用于访问以下对象:可以在全局范围内使用。例如,您可以看到 Log4Net appender TelemetryClient.cs 使用主动遥测配置:

public TelemetryClient() : this(TelemetryConfiguration.Active)

如果您检查 TelemetryConfiguration.Active 的文档你会看到这个:

Gets the active TelemetryConfiguration instance loaded from the ApplicationInsights.config file. If the configuration file does not exist, the active configuration instance is initialized with minimum defaults needed to send telemetry to Application Insights.

注意:根据平台的不同,情况会略有不同。例如在.NET Core中更建议使用依赖注入(inject)。在 Code-base monitoring 下查看您的案例.

例如,如果您有这样的配置文件:

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <InstrumentationKey>exxxxxxe-axxf-4xx6-bxx2-7xxxxxxxxxx3</InstrumentationKey>

这将从其中获取仪器 key :

  _configuration = TelemetryConfiguration.CreateDefault();

如果删除配置文件,这不会失败,但您需要在代码中设置检测 key :

_configuration.InstrumentationKey = "exxxxxxe-axxf-4xx6-bxx2-7xxxxxxxxxx3";

如果您的配置文件包含初始化程序、模块或其他内容,您也可以通过代码配置它们。例如:

 <TelemetryInitializers>
        <Add Type="...MyInitializer, ..." />
    </TelemetryInitializers>
    

可以在如下代码中设置:

  _configuration.TelemetryInitializers.Add(new MyInitializer(...));

关于c# - C#.NET 项目中我们真的需要 ApplicationInsights.config 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653213/

相关文章:

azure - 如何将默认的 Azure 工作簿组状态设置为展开?

c# - RadioButtonList OnSelectedIndexChanged

c# - C#如何获取员工的总休假数

c# - 任务WhenAll异常处理

azure-application-insights - 如何在键/值对的json数组上使用mvexpand

azure - 机器人抛出异常时没有日志

c# - ASP.NET Web API DELETE 方法错误

asp.net - Windows Azure PaaS(Web 角色)的真正替代品?

node.js - SQLITE_BUSY Node.js 的 Azure 只读问题

azure - 如何将现有的 azure 函数导出到 VS Code