ASP.NET Core中如何按需启停Azure Application Insights的EventCounterCollectionModule
可运行时动态控制EventCounterCollectionModule启停的实现方案
存在无需修改Startup.cs、无需重新部署的运行时控制方案,具体实现如下:
核心实现逻辑
EventCounterCollectionModule在Application Insights服务注册阶段会以单例形式注入到DI容器中,你可以在任意支持依赖注入的代码位置(包括控制器、中间件、自定义业务服务)直接获取该实例进行操作,无需在ConfigureServices阶段固定配置。
两种常用控制方式
方式1:轻量调整采集指标范围(无需启停模块)
如果仅需要按需开启/关闭指定指标上报,不需要完全停用采集模块,可直接修改实例的Counters属性动态调整采集列表,运行时即时生效:
// 控制器中示例代码 using Microsoft.ApplicationInsights.EventCounterCollector; using Microsoft.AspNetCore.Mvc; public class CounterConfigController : ControllerBase { private readonly EventCounterCollectionModule _counterModule; // 构造函数注入单例实例 public CounterConfigController(EventCounterCollectionModule counterModule) { _counterModule = counterModule; } [HttpPost("disable-runtime-counters")] public IActionResult DisableRuntimeCounters() { // 移除所有System.Runtime相关指标的采集配置 var runtimeCounterConfig = _counterModule.Counters.FirstOrDefault(c => c.EventSourceName == "System.Runtime"); if (runtimeCounterConfig != null) { _counterModule.Counters.Remove(runtimeCounterConfig); } return Ok(); } [HttpPost("enable-runtime-counters")] public IActionResult EnableRuntimeCounters() { // 避免重复添加先判断是否已存在配置 if (!_counterModule.Counters.Any(c => c.EventSourceName == "System.Runtime")) { // 按需添加需要采集的指标 _counterModule.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "cpu-usage")); _counterModule.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-0-size")); _counterModule.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "gen-1-size")); // 其他需要的指标可依次添加 } return Ok(); } }
方式2:完全启停采集模块
如果需要彻底停止所有EventCounter的采集和上报,可直接调用实例的Dispose方法,需要恢复时重新初始化实例即可:
// 停用模块 _counterModule.Dispose(); // 重新启用模块:初始化新实例、补充配置后即可正常工作 var newModule = new EventCounterCollectionModule(); newModule.Counters.Add(new EventCounterCollectionRequest("System.Runtime", "cpu-usage")); // 其他配置补充完成即生效
注意事项
- 所有操作均为运行时即时生效,无需重启应用、无需修改启动代码、无需重新部署
- 上述操作仅对当前实例生效,多实例部署场景下如果需要全集群统一控制,可配合分布式配置监听逻辑,所有实例收到配置变更信号时统一执行对应操作即可
内容的提问来源于stack exchange,提问作者AmrutRayabagi
相关产品推荐
相关产品推荐

