You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法运行简单的AppInsights Hello World程序求助

解决AppInsights Hello World程序无法运行的问题

我之前开发控制台程序接入AppInsights时也踩过类似的坑,结合你的代码来看,主要有几个关键点需要调整:

1. 调整InstrumentationKey的配置时机

你当前是先初始化TelemetryClient再设置InstrumentationKey,这可能导致配置未生效。建议先配置全局设置,再创建客户端:

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

namespace azure {
    class Program {
        static void Main(string[] args) {
            // 先配置全局InstrumentationKey
            TelemetryConfiguration.Active.InstrumentationKey = "***MY KEY IS HERE***";
            var tc = new TelemetryClient();
            
            tc.TrackTrace("Hello World!");
            tc.Flush();
            // 控制台程序需要等待发送完成,否则进程会直接退出
            System.Threading.Thread.Sleep(5000);
        }
    }
}

2. 必须等待Flush操作完成

Flush()是异步执行的,控制台程序执行完该方法后会立刻终止进程,导致遥测数据还没来得及发送到AppInsights服务器。所以一定要添加一段等待时间,比如上面代码里的5秒休眠,足够覆盖大部分场景的发送耗时。

3. 确保依赖包完整且版本合适

你的packages.config内容被截断了,要保证安装了完整的AppInsights依赖。针对.NET Framework 4.5.2,至少需要以下包(建议升级到较新的稳定版,旧版本可能存在发送问题):

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ApplicationInsights" version="2.21.0" targetFramework="net452" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.21.0" targetFramework="net452" />
  <package id="System.Diagnostics.DiagnosticSource" version="6.0.1" targetFramework="net452" />
</packages>

4. 更推荐的配置方式:使用App.config

硬编码InstrumentationKey不是最佳实践,建议通过配置文件管理:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ApplicationInsights:InstrumentationKey" value="***MY KEY IS HERE***" />
  </appSettings>
  <system.diagnostics>
    <trace autoflush="true" />
  </system.diagnostics>
</configuration>

此时代码无需手动设置InstrumentationKey,TelemetryClient会自动读取配置:

using Microsoft.ApplicationInsights;

namespace azure {
    class Program {
        static void Main(string[] args) {
            var tc = new TelemetryClient();
            tc.TrackTrace("Hello World!");
            tc.Flush();
            System.Threading.Thread.Sleep(5000);
        }
    }
}

调整完这些后,运行程序并等待几秒再关闭,然后去AppInsights门户的「跟踪」模块,就能看到你的Hello World日志了。

内容的提问来源于stack exchange,提问作者mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:52:17