首页 > 解决方案 > 将 APM 添加到 NuxtJS 项目的最佳方法是什么

问题描述

在 Nuxtjs 项目中配置/启用 Elastic APM 代理的正确方法是什么?

我为自定义 NodeJS 应用程序引用了此文档。关键的收获是:

重要的是,在您需要 Node.js 应用程序中的任何其他模块之前启动代理 - 即在 http 之前和路由器之前等。

我在 nuxt.config.js 中添加了以下代码段,但 APM 代理没有启动或工作。我在应用程序日志中看不到任何错误。

var apm = require('elastic-apm-node').start({
  serviceName: 'nuxt-app',
  serverUrl: 'http://ELK_APM_SERVER:8200'
})

有没有其他方法可以做到这一点?

标签: javascriptvue.jsnuxt.jselastic-stackelastic-apm

解决方案


我们设法使用自定义 Nuxt 模块来实现这一点,该模块明确要求 Node 模块在启动 APM 模块后进行检测。

modules/elastic-apm.js

    const apm = require('elastic-apm-node');
    const defu = require('defu');
    
    module.exports = function() {
      this.nuxt.hook('ready', async(nuxt) => {
        const runtimeConfig = defu(nuxt.options.privateRuntimeConfig, nuxt.options.publicRuntimeConfig);
        const config = (runtimeConfig.elastic && runtimeConfig.elastic.apm) || {};
    
        if (!config.serverUrl) {
          return;
        }
    
        if (!apm.isStarted())  {
          await apm.start(config);
    
          // Now explicitly require the modules we want APM to hook into, as otherwise
          // they would not be instrumented.
          //
          // Docs: https://www.elastic.co/guide/en/apm/agent/nodejs/master/custom-stack.html
          // Modules: https://github.com/elastic/apm-agent-nodejs/tree/master/lib/instrumentation/modules
          require('http');
          require('http2');
          require('https');
        }
      });
    }

nuxt.config.js

    module.exports = {
      // Must be in modules, not buildModules
      modules: ['~/modules/elastic-apm'],
      
      publicRuntimeConfig: {
        elastic: {
          apm: {
            serverUrl: process.env.ELASTIC_APM_SERVER_URL,
            serviceName: 'my-nuxt-app',
            usePathAsTransactionName: true // prevent "GET unknown route" transactions
          }
        }
      }
    };

推荐阅读