LoginSignup
10

More than 3 years have passed since last update.

SentryとVueの組み合わせでイベントログを収集

Last updated at Posted at 2019-07-21

目的

circleCIでデプロイ時の通知はできたものの、今度はerrorの時に何がおきているのかを知りたくなったので、sentryを突っ込みます。
Sentry自体はエラーに限るわけではないですが、今回の目的はエラーが起きた時にログを追うために実装をします。

Sentryとは

https://sentry.io/welcome/
Sentryはイベントログを収集してくれるツールです。
2019年7月現在では以下のプログラミング環境下で使用ができます。

sentry.io_platforms_.png

JSのフレームワークでは、Reactをはじめ、今回実装するVueやAngularなどで使用ができます。

sentry.io_for_javascript_.png

登録

まずはSentryに登録をします。

2019年7月現在では登録方法としては現在以下があります。

  • github
  • Azure DevOps
  • Emailなどを入力

今回はgithubで登録を行います。
「Sign up with Github」をクリックし認証を行います。

プロジェクト登録

登録が完了したらProjectを作成します。
今回はvueを選択し、project nameを設定してやります。

今回は名前を「blog」にしました。
sentry.io_organizations_tomopict_projects_new_ (3).png

Vueのプロジェクトの追加する

以前はraven-jsだったようですが、今は変わっているようです。
基本的には@sentry/browser@sentry/integrationsをインストールすれば問題なさそう。

# Using yarn
$ yarn add @sentry/browser

# Using npm
$ npm install @sentry/browser

# Using yarn
$ yarn add @sentry/integrations

# Using npm
$ npm install @sentry/integrations

Vueのなかで呼び出し

インストールが済んだら、極力早い段階でSentry.initでinitializeを行います。
denのio/xxxxxxxの箇所には固有のidが入ります。

import * as Sentry from '@sentry/browser';
import * as Integrations from '@sentry/integrations';
Sentry.init({
  dsn: 'https://b360938dff664cdf9166f2d92f1f5976@sentry.io/xxxxxxx',
  integrations: [new Integrations.Vue({Vue, attachProps: true})]
});

ここまで準備が終われば、あとは実際にSentryにイベントを送って見ます。

ブラウザからエラーを確認

イベントを送りたい箇所に以下のコードを入れるとクライアントからイベントがSentryに向けて送信されます。

https://docs.sentry.io/platforms/javascript/

Sentry.captureException(new Error("Something broke"));

なおユーザー情報を追加した状態でイベントレポートを送信したい場合は以下のようにして設定できます。

https://docs.sentry.io/enriching-error-data/scopes/?platform=javascript

    Sentry.configureScope((scope) => {
      scope.setTag("test-tag", "test-value");
      scope.setUser({
        id: 42,
        email: "john.doe@example.com"
      });
    });

管理画面でイベントを確認

該当のプロジェクトの画面に移動して、作成したプロジェクトでイベントを確認します。

スクリーンショット 2019-07-21 23.15.18.png

ユーザー情報を付与した場合は該当のイベントログに、ユーザー情報もきちんと入っています。

スクリーンショット 2019-07-21 23.15.44.png

まとめ

まずは導入までというところですが、簡単にイベントを送信することができました。
実際にはエラーが起きた際にslackに通知したり、どのようなデータが入っていたのかstoreの中のデータを送信したり工夫は必要そうです。
slack通知などを導入したらまた追記したいと思います。

参考にさせていただいた記事

Sentryでイベントログ収集をしよう! - Vue.js編 -

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10