首页 > 解决方案 > 如何将 Elastic APM 集成到 Vuejs SPA?

问题描述

Elastic APM我如下集成到我的 Vue.js 应用程序中。它成功记录到 Elastic APM。

但是,它没有在日志中正确显示当前页面名称。它似乎总是显示应用程序在 APM 中安装的第一页。

我希望始终看到当前页面链接到相应的 APM 事件。任何建议如何实现这一目标?

文档说要设置pageLoadTransactionName. 但是,它似乎没有在路线更改时更新此内容: https ://www.elastic.co/guide/en/apm/agent/rum-js/current/custom-transaction-name.html

应用程序.js

  mounted() {
    this.initializeApm();
  },
  methods: {
    initializeApm() {
      const currentPage =
        this.$route.name || window.location.href.split('#/')[1];
      // initialize elastic apm
      const apm = initApm({
        serviceName: this.config.apm.serviceName,
        serverUrl: this.config.apm.serverUrl,
        serviceVersion: this.config.version,
        pageLoadTransactionName: currentPage,
        distributedTracingOrigins: [
          'https://xxx.de',

        ],
        environment: this.config.stage
      });
      apm.setUserContext({
        id: this.getUserIdFromSession,
        username: this.getUserNameFromSession,
        email: this.getUserEmail
      });
    }
  }

标签: vue.jskibanavue-routerelastic-stackelastic-apm

解决方案


当路由到不同的子页面时,您必须手动设置路由名称。您可以通过“更改路线”类型的过滤器来实现此目的。请参阅apm.addFilter() 文档:https ://www.elastic.co/guide/en/apm/agent/rum-js/current/agent-api.html#apm-add-filter

像这样的东西应该工作:

apm.addFilter(payload => {
  if (payload.data) {
    const mappedData = [];
    payload.data.forEach(tr => {
      if (tr.type === 'route-change')
        mappedData.push({
          ...tr,
          name: this.$route.name // overwrite unknown with the current route name
        });
      else mappedData.push(tr);
    });
    payload.data = mappedData;
  }
  return payload;
});

推荐阅读