如何为 Application Insights Log4Net Appender 设置遥测通道?

How to set Telemetry Channel for Application Insights Log4Net Appender?

我将这些 Nuget 包添加到我的 WPF 应用程序中:

记录器正在记录一个有效的文件。但没有数据传输到 Azure。 我收到此错误:

我的问题:我应该在哪里(在代码中)初始化遥测通道?为什么我必须这样做?如果我无论如何都必须添加遥测客户端(带配置),appender 有什么用?

更新 0603:

我的app.config:

调试 visual studio:

更新:请按照下面的截图,尝试找到您发送的信息。如果您仍然找不到信息,请提供详细代码(删除 personal/important 数据,如检测密钥,并向我们提供您正在使用的 nuget 包和版本)。

1.click 概览页面中的搜索按钮:

2.in搜索界面,正确设置本地时间和事件类型,然后尝试搜索消息:


你最好提供设置log4net和app insights key的代码。

我用 wpf 项目做了一个简单的测试,下面的代码工作正常:

public partial class MainWindow : Window
{

    private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
    public MainWindow()
    {
        TelemetryConfiguration.Active.InstrumentationKey = "the key";
        log4net.Config.XmlConfigurator.Configure();

        log.Info("wpf aaaa11111");


        InitializeComponent();
    }
 }

您收到错误 "AI: Server telemetry channel was not initialized",可能是由于某些不正确的配置,例如在上面的工作代码中使用以下代码:

//when add the code, it will cause the error you mentioned.
TelemetryConfiguration.Active.TelemetryChannel = new ServerTelemetryChannel();

如果您必须添加遥测客户端(带配置),并且配置正确,则 log4net 和遥测客户端都可以将数据发送到 application insights。代码如下:

public partial class MainWindow : Window
{
    private readonly TelemetryClient telemetryClient;
    private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
    public MainWindow()
    {
        //configure the key here for log4net
        TelemetryConfiguration.Active.InstrumentationKey = "the key";
        log4net.Config.XmlConfigurator.Configure();

        var config = new TelemetryConfiguration();

        //configure the key here for telemetry client
        config.InstrumentationKey = "the key";
        telemetryClient = new TelemetryClient(config);

        log.Info("wpf aaaa333");
        log.Info(TelemetryConfiguration.Active.TelemetryChannel.ToString());

        telemetryClient.TrackTrace("it is going to start!");

        InitializeComponent();
    }
}

所以,最后一切正常。我在这里再次提供所需的步骤:

  1. 添加 Nuget 包: log4net、Microsoft.ApplicationInsights、Microsoft.ApplicationInsights.Log4NetAppender 和 Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel 到项目

  2. 在MainWindow.xaml.cs:

    private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
    public MainWindow()
    {
        TelemetryConfiguration.Active.InstrumentationKey = "the key";
        log4net.Config.XmlConfigurator.Configure();
    
        log.Info("wpf aaaa11111");
    
    
        InitializeComponent();
    }
    }    
    
  3. 在App.config中:

  4. 完成

非常感谢@Ivan Yang 的解决方案和他花时间帮助我!