.NET Core下使用Application Insights 2.x SDK启用Live Stream的最简配置问询
我来一步步解答你的问题,都是基于最新的Application Insights 2.x SDK在.NET Core环境下的实践:
一、最低最简配置
要启用Live Stream,核心只需要两个关键步骤:
- 安装必要的NuGet包:
你需要安装Microsoft.ApplicationInsights.AspNetCore包(这是ASP.NET Core项目的核心包,已包含Live Stream所需的全部依赖),可以通过NuGet包管理器或命令行安装:
或者用.NET CLI:Install-Package Microsoft.ApplicationInsights.AspNetCore -Version 2.xdotnet add package Microsoft.ApplicationInsights.AspNetCore --version 2.x - 配置Instrumentation Key:
这是连接到你的Application Insights资源的唯一标识,必须正确配置。你可以通过两种常用方式设置:- 在
appsettings.json中添加:{ "ApplicationInsights": { "InstrumentationKey": "你的InstrumentationKey" } } - 或者通过环境变量
APPINSIGHTS_INSTRUMENTATIONKEY设置,这种方式更适合生产部署场景。
- 在
完成这两步后启动应用,访问Azure门户的Application Insights资源,就能在「实时流」(Live Stream)标签页看到实时遥测数据了。
二、是否需要部署appinsights.config文件?
不需要。在.NET Core环境中,Application Insights SDK已完全适配.NET Core原生配置系统(依赖Microsoft.Extensions.Configuration),默认会从appsettings.json、环境变量、命令行参数等来源读取配置。传统的appinsights.config是.NET Framework项目的配置方式,在.NET Core中并非必需。
如果出于特殊原因一定要使用appinsights.config,文件中至少需要包含你的Instrumentation Key:
<?xml version="1.0" encoding="utf-8"?> <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings"> <InstrumentationKey>你的InstrumentationKey</InstrumentationKey> </ApplicationInsights>
但更推荐使用.NET Core原生配置方式,更符合生态习惯。
三、是否支持代码优先的实现方式?
当然支持,而且在动态配置Instrumentation Key、自定义遥测行为等场景下非常实用。具体操作步骤如下:
安装NuGet包:
同样先安装Microsoft.ApplicationInsights.AspNetCore包。在Program.cs中配置Application Insights:
在.NET 6+的最小API或ASP.NET Core项目中,直接在Program.cs中配置:var builder = WebApplication.CreateBuilder(args); // 添加Application Insights服务,默认已启用Live Stream builder.Services.AddApplicationInsightsTelemetry(options => { options.InstrumentationKey = "你的InstrumentationKey"; // 如需自定义Live Stream相关配置,可在此调整TelemetryChannel // 比如设置遥测发送间隔等,默认配置已足够支持Live Stream }); var app = builder.Build(); // 你的应用中间件和路由配置... app.Run();如果你使用的是.NET 5及更早的项目(基于Startup.cs),则在
ConfigureServices方法中配置:public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(options => { options.InstrumentationKey = "你的InstrumentationKey"; }); // 其他服务配置... }验证Live Stream:
启动应用后发送一些请求(比如访问API或页面),然后到Azure门户的Application Insights资源中打开「实时流」,就能看到实时的请求、异常等数据了。
需要注意的是,Live Stream依赖遥测数据的实时发送,默认的TelemetryChannel配置已满足需求,无需额外调整。如果应用部署在防火墙后,需确保能访问Application Insights的终结点(通常是https://dc.services.visualstudio.com/v2/track)。
内容的提问来源于stack exchange,提问作者Isaac Abraham

