New Relic Vue.js統合ガイド - Vue.jsアプリケーションの効果的な監視

Vue.jsは、そのリアクティブデータシステムと柔軟なアーキテクチャにより、開発者に優れた体験を提供しますが、その独特なライフサイクルとデータフローは監視において特別な考慮が必要です。New Relic Browser AgentとVue.jsの統合により、リアクティブシステムの動作、コンポーネントのパフォーマンス、ユーザーインタラクションを詳細に追跡できます。

Vue.js監視の特徴

Vue.jsアプリケーションの監視では、そのアーキテクチャ固有の要素を理解することが重要です。

リアクティブシステムの監視

Vue.jsのリアクティブシステムは、データの変更を検知して自動的にDOMを更新しますが、この過程でのパフォーマンス影響を監視することが重要です。

データ変更の追跡では、プロパティの更新頻度と再レンダリングの関係を分析します。ウォッチャーの効率性では、watchcomputedプロパティの実行時間を測定して最適化の機会を特定します。

Vue Routerとの統合

Vue Routerを使用するアプリケーションでは、SPA特有のルーティング監視が必要です。

javascript
// Vue Router 4でのルート監視
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/products', component: Products }
  ]
});

// ルート変更の監視
router.afterEach((to, from) => {
  if (typeof newrelic !== 'undefined') {
    newrelic.addPageAction('vue_route_change', {
      toPath: to.path,
      fromPath: from.path
    });
  }
});

Vue.js プラグインとしての実装

New RelicをVue.jsプラグインとして実装することで、アプリケーション全体で一貫した監視を実現できます。

基本的なプラグイン実装

javascript
// 基本的なVueプラグイン実装
const NewRelicVuePlugin = {
  install(app, options = {}) {
    // エラーハンドラー
    app.config.errorHandler = (err, instance, info) => {
      if (typeof newrelic !== 'undefined') {
        newrelic.noticeError(err, {
          vueComponent: instance?.$options.name || 'Anonymous',
          vueInfo: info
        });
      }
    };
    
    // グローバルメソッド
    app.config.globalProperties.$newrelic = {
      trackEvent: (eventName, attributes = {}) => {
        if (typeof newrelic !== 'undefined') {
          newrelic.addPageAction(eventName, attributes);
        }
      }
    };
  }
};

プラグインの使用

VueアプリケーションでNew Relicプラグインを使用する基本的な方法です。

javascript
// main.jsでのプラグイン登録
import { createApp } from 'vue';
import NewRelicVuePlugin from './plugins/new-relic-vue-plugin';

const app = createApp(App);
app.use(NewRelicVuePlugin);
app.mount('#app');

Composition APIとの統合

Vue 3のComposition APIを活用して、コンポーネントレベルでの詳細な監視を実装します。

パフォーマンス追跡のComposable

javascript
// API追跡Composable
export function useApiTracking() {
  const trackApiCall = async (apiName, apiFunction) => {
    const startTime = performance.now();
    
    try {
      const result = await apiFunction();
      const duration = performance.now() - startTime;
      
      if (typeof newrelic !== 'undefined') {
        newrelic.addPageAction('vue_api_success', {
          apiName,
          duration
        });
      }
      
      return result;
    } catch (error) {
      if (typeof newrelic !== 'undefined') {
        newrelic.noticeError(error, {
          apiCall: true,
          apiName
        });
      }
      throw error;
    }
  };
  
  return { trackApiCall };
}

使用例

Composition APIでの基本的な使用方法です。

vue
<!-- ProductList.vue -->
<template>
  <div>
    <h2>商品一覧</h2>
    <div v-if="!products.length">読み込み中...</div>
    <div v-else>
      <div v-for="product in products" :key="product.id">
        {{ product.name }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useApiTracking } from '@/composables/useNewRelicTracking';

const props = defineProps(['category']);
const products = ref([]);
const { trackApiCall } = useApiTracking();

onMounted(async () => {
  try {
    const result = await trackApiCall(
      'fetchProducts',
      () => fetch(`/api/products?category=${props.category}`).then(r => r.json())
    );
    products.value = result;
  } catch (error) {
    console.error('商品取得エラー:', error);
  }
});
</script>

Vuex/Pinia状態管理との統合

Vue.jsの状態管理ライブラリとの統合により、アプリケーションの状態変更を詳細に監視できます。

Vuex統合

VuexストアとNew Relicの統合では、ミューテーションやアクションの実行を監視できます。

javascript
// Vuexプラグイン
const newRelicPlugin = (store) => {
  store.subscribe((mutation, state) => {
    if (typeof newrelic !== 'undefined') {
      newrelic.addPageAction('vuex_mutation', {
        type: mutation.type
      });
    }
  });
};

const store = createStore({
  plugins: [newRelicPlugin]
});

Pinia統合

Piniaストアでのアクション実行を監視し、API呼び出しのパフォーマンスやエラーを追跡できます。

javascript
// Piniaストアでの監視
export const useProductsStore = defineStore('products', {
  actions: {
    async fetchProducts(category) {
      const startTime = performance.now();
      
      try {
        const response = await fetch(`/api/products?category=${category}`);
        const products = await response.json();
        const duration = performance.now() - startTime;
        
        if (typeof newrelic !== 'undefined') {
          newrelic.addPageAction('pinia_action_success', {
            action: 'fetchProducts',
            duration
          });
        }
        
        return products;
      } catch (error) {
        if (typeof newrelic !== 'undefined') {
          newrelic.noticeError(error, { store: 'products' });
        }
        throw error;
      }
    }
  }
});

カスタムディレクティブでの監視

Vue.jsのカスタムディレクティブを使用して、DOM要素レベルでの監視を実装できます。

javascript
// トラッキング用ディレクティブ
export const trackDirective = {
  mounted(el, binding) {
    const trackEvent = (event) => {
      if (typeof newrelic !== 'undefined') {
        newrelic.addPageAction('vue_user_interaction', {
          element: el.tagName.toLowerCase(),
          eventType: event.type,
          value: binding.value
        });
      }
    };
    
    el.addEventListener('click', trackEvent);
  }
};

// 使用例: <button v-track="'purchase_button'">購入</button>

実装のベストプラクティス

Vue.js環境でのNew Relic監視を最適化するための推奨事項をまとめます。

パフォーマンス最適化

リアクティブシステムとの調和により、Vue.jsのリアクティブシステムに過度な負荷をかけないよう、監視データの収集と送信を適切に最適化します。

非同期処理の活用では、nextTickを使用してDOM更新後のタイミングで監視データを収集し、レンダリングをブロックしないよう配慮します。

開発体験の向上

開発用と本番用の設定分離により、開発環境では詳細な監視を行い、本番環境では必要最小限のデータのみを収集します。

TypeScript統合では、Composition APIとTypeScriptを組み合わせて、型安全な監視コードを作成します。

まとめ

New RelicとVue.jsの統合により、リアクティブシステムの動作から状態管理、ユーザーインタラクションまで、Vue.jsアプリケーションの全体像を詳細に監視できるようになります。Composition APIとプラグインシステムを活用することで、保守性が高く効率的な監視システムを構築できます。

次のステップでは、Angularアプリケーションでの統合方法について詳しく解説します。Angular特有のアーキテクチャと監視手法を学んでいきましょう。


関連記事: Angular統合ガイド関連記事: React統合ガイド