【问题标题】:Application Insights can't track request in node middlewareApplication Insights 无法跟踪节点中间件中的请求
【发布时间】:2019-09-27 08:56:50
【问题描述】:

我正在为我的 CMS 使用 Strapi(构建在 Koa 之上)。我添加了一个中间件,它会在对服务器的每个请求时触发。此中间件初始化 appInsights。

我可以从下面的代码中获取跟踪日志,但对于我来说,我没有得到任何请求结果。我在 Nuxt SPA 上使用了相同 AppInsights 资源的密钥,该资源从这个 Strapi 后端获取数据,为此,我可以看到所有发出的请求。所以资源应该设置正确。

这是中间件的代码。所有跟踪消息和控制台日志都按预期注册。

const appInsights = require('applicationinsights');
module.exports = () => {
  let isInit = false;
  return {
    initialize: function(cb) {
      strapi.app.use(async (ctx, next) => {
        if (!isInit) {
          appInsights.setup().start();
          appInsights.defaultClient.trackTrace({
            message: 'STRAPI: trace on init'
          });
          console.log('app insights setup');
          isInit = true;
        }
        await next();
        appInsights.defaultClient.trackNodeHttpRequest({
          request: ctx.request,
          response: ctx.response
        });
        appInsights.defaultClient.trackTrace({
          message: 'STRAPI: trace on all http calls'
        });
        console.log('track node http request');
      });
      cb();
    }
  };
};

【问题讨论】:

  • 对于在 2021 年看到此内容的任何人,您必须使用 ctx.req 和 ctx.res,因为它们是 trackNodeHttpRequest 所需的原始 Node 请求和响应对象

标签: node.js azure-application-insights koa strapi


【解决方案1】:

你必须把你的

appInsights.setup().start();
appInsights.defaultClient.trackTrace({
  message: 'STRAPI: trace on init'
});
console.log('app insights setup');

在你的strapi.app.use之外

module.exports = () => {
  return {
    initialize: function(cb) {
      appInsights.setup().start();

      appInsights.defaultClient.trackTrace({
        message: 'STRAPI: trace on init'
      });

      console.log('app insights setup');

      strapi.app.use(async (ctx, next) => {
        await next();

        appInsights.defaultClient.trackNodeHttpRequest({
          request: ctx.request,
          response: ctx.response
        });

        appInsights.defaultClient.trackTrace({
          message: 'STRAPI: trace on all http calls'
        });

        console.log('track node http request');
      });

      cb();
    }
  };
};

通过这种方式,您的start 将在服务器启动时被调用一次。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2023-01-09
    • 2015-10-28
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多