首页 > 解决方案 > 我们真的需要 C#.NET 项目中的 ApplicationInsights.config 文件吗?

问题描述

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

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

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

正在缓存 applicationInsights.config 工具键吗?如果是,那么解决方案是什么?

场景 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");

标签: c#azureazure-application-insights

解决方案


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

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

为了允许通过配置文件和代码混合配置,AI 客户端和配置类具有GetDefault()Active静态成员,可以访问可以全局使用的对象。例如,您可以看到Log4Net 附加程序 TelemetryClient.cs 使用活动遥测配置:

public TelemetryClient() : this(TelemetryConfiguration.Active)

如果您查看TelemetryConfiguration.Active的文档,您会看到:

获取从 ApplicationInsights.config 文件加载的活动 TelemetryConfiguration 实例。如果配置文件不存在,则使用将遥测数据发送到 Application Insights 所需的最小默认值初始化活动配置实例。

注意:根据平台的不同,情况会有所不同。例如,在 .NET Core 中更建议使用依赖注入。在代码库监控下查看您的案例。

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

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

这将从其中获取检测密钥:

  _configuration = TelemetryConfiguration.CreateDefault();

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

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

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

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

可以像这样在代码中设置:

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

推荐阅读