node.js - 配置 Azure AppInsights for Node.js 应用程序

标签 node.js azure logging appinsights

即使在配置了 Azure AppInsights for 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:'
  },

代码: 索引.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.log("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.log('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.log('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.log(`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;

最佳答案

  • 配置 Azure AppInsights for 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.log('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.log('console: ' + errStr + '\n');
// Track the custom event
appInsights.defaultClient.trackEvent({  name:  'stderr',  properties:  {  log:  errStr  }  });
res.send('Received\n');
});
app.listen(port,  ()  =>  console.log(`Example app listening on port ${port}!`));

  • 安装npm install applicationinsights express querystring url

  • 您遇到的行为,enableAutoCollectConsoleenableAutoDependencyCorrelation 等某些属性在 中显示为 undefined由于 applicationinsights 包在内部处理这些配置的方式,NodeClient 对象是预期的。

  • 遥测跟踪正在按预期工作,并且您会看到 Azure 门户中正在收集数据,您可以放心,您的设置运行正常,尽管属性在中显示为未定义 NodeClient 对象。

  • 您观察到的行为不是问题,您可以放心地继续操作,因为您的 Azure AppInsights 设置正在按预期工作。查看 Azure 门户中收集的遥测数据并且您的应用程序运行正常,无需担心 NodeClient 对象中这些属性的 未定义 值。

输出:

enter image description here

enter image description here

enter image description here

enter image description here

关于node.js - 配置 Azure AppInsights for Node.js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76859541/

相关文章:

javascript - 使用 Q.Promises 递归地从 DynamoDB 获取记录

javascript - 更新 Electron 问题 : Uncaught ReferenceError: global is not defined

grails - 在DEBUG级别记录我的应用程序的类,在WARN记录所有其他类

node.js - 谷歌云存储: file system limitations

node.js - SailsJs 无效模块错误

azure - 在 ARM 模板部署输出中获取 Azure 数据工厂的 ObjectId

mysql - 访问 Azure MySQL 服务

表示 TFS 服务 Hook 事件的 C# 对象

Windows Azure 日志记录 : WADLogsTable as Application logs?

c# - Fluent ConfigurationSourceBuilder 导致 InvalidOperationException