简体   繁体   English

动态禁用/启用 ApplicationInsights 遥测

[英]Disable/Enable ApplicationInsights Telemetry dynamically

I implemented Application Insigths in the frontend applciation and I want to disable/enable it based on a variable that can change over the lifetime of the applications.我在前端应用程序中实现了 Application Insigths,我想根据一个可以在应用程序生命周期内改变的变量来禁用/启用它。 (eg user declined Application Insights consent => Disable Telemetry) (例如,用户拒绝 Application Insights 同意 => 禁用遥测)

What I tried is:我试过的是:

appInsights.appInsights.config.disableTelemetry = true

however if I try to enable it back setting disableTelemetry =false this is not working anymore.但是,如果我尝试重新启用它,设置disableTelemetry =false这将不再起作用。

Is anything else that I need to make to persist this change or is there another way of doing this?我还需要做些什么来坚持这种改变,还是有另一种方法可以做到这一点?

You could use a telemetry filter for that:您可以为此使用遥测过滤器

var filteringFunction = (envelope) => {
  if (condition) {
      return false; // Do not send telemetry
  }

  return true; // Do send the telemetry
};

Register the filter like this:像这样注册过滤器:

appInsights.addTelemetryInitializer(filteringFunction);
  • While Peter's answer is correct, I have different approach where instead of using telemetry filters we can stop the application insights object itself from starting to log to app insights.虽然 Peter 的回答是正确的,但我有不同的方法,而不是使用遥测过滤器,我们可以阻止应用程序见解 object 本身开始记录到应用程序见解。

  • Here in the following code based on the value of the variable a it will start the app insight service.在下面的代码中,它会根据变量a的值启动应用洞察服务。

  • So, we will run appInsights.start();所以,我们将运行appInsights.start(); only for a particular for value of variable a .仅针对变量a的特定值。

import { createRequire } from  "module";
const  require = createRequire(import.meta.url);

let  appInsights = require('applicationinsights');

appInsights.setup("<Your connection String>")
    .setAutoCollectConsole(true, true);

var  a = 10 ;
if(a==10)
{appInsights.start();}

console.log("Hello World ");

Here I am running the code twice but with different value of variable a .在这里,我运行了两次代码,但变量a值不同。

在此处输入图像描述

Here in application insights one log appear.在 application insights 中会出现一个日志。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM