Настройте приложение Azure AppInsights для Node.js

Даже после настройки приложения Azure AppInsights для Node.js я получаю NodeClient со свойствами, такими как enableAutoCollectConsole, enableAutoDependencyCorrelation и т. д., как неопределенными. Пожалуйста, скажите мне, что не так? Ссылка на ссылку: https://github.com/microsoft/ApplicationInsights-node.js/issues/560

appInsights.defaultClient NodeClient {
  _telemetryProcessors: [],
  config: Config {
    _endpointBase: 'https://dc.services.visualstudio.com',
    _connectionString: undefined,
    _instrumentationKey: '3e9532',
    correlationHeaderExcludedDomains: [
      '*.core.windows.net',
      '*.core.chinacloudapi.cn',
      '*.core.cloudapi.de',
      '*.core.usgovcloudapi.net',
      '*.core.microsoft.scloud',
      '*.core.eaglex.ic.gov'
    ],
    correlationIdRetryIntervalMs: 30000,
    disableAllExtendedMetrics: false,
    disableAppInsights: false,
    disableStatsbeat: false,
    distributedTracingMode: undefined,
    enableAutoCollectConsole: undefined,
    enableLoggerErrorToTrace: undefined,
    enableAutoCollectDependencies: undefined,
    enableAutoCollectIncomingRequestAzureFunctions: undefined,
    enableAutoCollectExceptions: undefined,
    enableAutoCollectExtendedMetrics: undefined,
    enableAutoCollectExternalLoggers: undefined,
    enableAutoCollectHeartbeat: undefined,
    enableAutoCollectPerformance: undefined,
    enableAutoCollectPreAggregatedMetrics: undefined,
    enableAutoCollectRequests: undefined,
    enableAutoDependencyCorrelation: undefined,
    enableInternalDebugLogging: undefined,
    enableInternalWarningLogging: undefined,
    enableResendInterval: undefined,
    enableMaxBytesOnDisk: undefined,
    enableSendLiveMetrics: undefined,
    enableUseAsyncHooks: undefined,
    enableUseDiskRetryCaching: undefined,
    endpointUrl: 'https://centralindia-0.in.applicationinsights.azure.com/v2.1/track',
    extendedMetricDisablers: undefined,
    ignoreLegacyHeaders: false,
    maxBatchIntervalMs: 15000,
    maxBatchSize: 250,
    proxyHttpUrl: undefined,
    proxyHttpsUrl: undefined,
    quickPulseHost: 'centralindia.livediagnostics.monitor.azure.com',
    samplingPercentage: 100,
    enableWebInstrumentation: false,
    _webInstrumentationConnectionString: '',
    webInstrumentationConfig: null,
    webInstrumentationSrc: '',
    enableAutoWebSnippetInjection: false,
    _profileQueryEndpoint: 'https://centralindia-0.in.applicationinsights.azure.com/',
    correlationId: 'cid-v1:'
  },

Код: index.js


const express = require('express');
const querystring = require('querystring');
const url = require('url');
const appInsights = require('./appInsightsSetup'); // Import the appInsights setup from the separate file

const app = express();
const port = 3000;

app.get('/', (req, res) => {
    console.info("appInsights.defaultClient", appInsights.defaultClient)
    // Track the incoming request
    appInsights.defaultClient.trackRequest({
        name: req.path,
        url: req.url,
        duration: Date.now() - req.startTime,
        resultCode: res.statusCode,
        success: true
    });

    res.send('Hello World!');
});

app.get('/stdout', (req, res) => {
    let logStr = querystring.parse(url.parse(req.url).query).log;
    // logStr = "logging stdout"
    process.stdout.write(logStr + '\n');
    console.info('console: ' + logStr + '\n');

    // Track the custom event
    appInsights.defaultClient.trackEvent({ name: 'stdout', properties: { log: logStr } });

    res.send('Received\n');
});

app.get('/stderr', (req, res) => {
    let errStr = querystring.parse(url.parse(req.url).query).log;
    process.stderr.write(errStr + '\n');
    console.info('console: ' + errStr + '\n');

    // Track the custom event
    appInsights.defaultClient.trackEvent({ name: 'stderr', properties: { log: errStr } });

    res.send('Received\n');
});

// Middleware to record request start time
app.use((req, res, next) => {
    req.startTime = Date.now();
    next();
});

app.listen(port, () => console.info(`Example app listening on port ${port}!`));

appInsightsSetup.js

const appInsights = require('applicationinsights');

appInsights.setup("InstrumentationKey=;IngestionEndpoint = ")
    .setAutoDependencyCorrelation(false)
    .setAutoCollectRequests(true)
    .setAutoCollectPerformance(false)
    .setAutoCollectExceptions(false)
    .setAutoCollectDependencies(false)
    .setAutoCollectConsole(true, true)
    .setUseDiskRetryCaching(true)
    .setSendLiveMetrics(false)
    .setInternalLogging(true)
    .start();

module.exports = appInsights;

Поместите файлы в одну папку

Sampath 09.08.2023 10:23
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
1
50
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий
  • Настройте приложение Azure AppInsights для Node.js.

appInsightsSetup.js:

const  appInsights = require('applicationinsights');
// Replace 'YOUR_INSTRUMENTATION_KEY' with your actual Application Insights instrumentation key
const  instrumentationKey = '886e0430-1007-4bc';
appInsights.setup(instrumentationKey)
.setAutoDependencyCorrelation(false)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(false)
.setAutoCollectExceptions(false)
.setAutoCollectDependencies(false)
.setAutoCollectConsole(true)
.setUseDiskRetryCaching(true)
.setSendLiveMetrics(false)
.setInternalLogging(true)
.start();
module.exports = appInsights;

index.js/main.js:

const  express = require('express');
const  querystring = require('querystring');
const  url = require('url');
const  appInsights = require('./appInsightsSetup');
const  app = express();
const  port = 3000;
// Middleware to record request start time
app.use((req,  res,  next)  =>  {
req.startTime = Date.now();
next();
});
app.get('/',  (req,  res)  =>  {
// Track the incoming request
appInsights.defaultClient.trackRequest({
name:  req.path,
url:  req.url,
duration:  Date.now() - req.startTime,
resultCode:  res.statusCode,
success:  true
});
res.send('Hello World!');
});
app.get('/stdout',  (req,  res)  =>  {
let  logStr = querystring.parse(url.parse(req.url).query).log;
process.stdout.write(logStr + '\n');
console.info('console: ' + logStr + '\n');
// Track the custom event
appInsights.defaultClient.trackEvent({  name:  'stdout',  properties:  {  log:  logStr  }  });
res.send('Received\n');
});
app.get('/stderr',  (req,  res)  =>  {
let  errStr = querystring.parse(url.parse(req.url).query).log;
process.stderr.write(errStr + '\n');
console.info('console: ' + errStr + '\n');
// Track the custom event
appInsights.defaultClient.trackEvent({  name:  'stderr',  properties:  {  log:  errStr  }  });
res.send('Received\n');
});
app.listen(port,  ()  =>  console.info(`Example app listening on port ${port}!`));

  • Установить npm install applicationinsights express querystring url .

  • Поведение, которое вы испытываете, когда определенные свойства, такие как enableAutoCollectConsole и enableAutoDependencyCorrelation, отображаются как undefined в объекте NodeClient, ожидается из-за того, как пакет applicationinsights обрабатывает эти конфигурации внутри.

  • Отслеживание телеметрии работает должным образом, и вы видите, что данные собираются на портале Azure, вы можете быть уверены, что ваша установка работает правильно, несмотря на то, что свойства отображаются как undefined в объекте NodeClient.

  • Поведение, которое вы наблюдаете, не является проблемой, и вы можете быть уверены, что ваша установка Azure AppInsights работает должным образом. Видя, что данные телеметрии собираются на портале Azure, и ваше приложение работает правильно, вам не нужно беспокоиться о значениях undefined для этих свойств в NodeClient объекте.

Выход:

Другие вопросы по теме