サイトのトップへ戻る

Google App Engine ドキュメント日本語訳

Google Analyticsを組み込む

Google Analytics プラットフォームによって 様々なデバイスや環境にまたがって、ユーザーとあなたのサービスとのやり取りを計測することができるようになります。 このプラットフォームでは、そうしたユーザー操作を収集、保存、処理、報告するためのコンピューティングリソースを提供します。

Analytics collectionはクライアント側とサーバ側の両方で行うことができます。 Google Analytics では、API とSDK を使って簡単にデータを Google Analyticsに送信することができます。 これらに加えて我々は、App Engine アプリケーション内で使用してサーバ側の分析を簡単にGoogle Analyticsへ送信できるコードを開発しました。



クライアント側での分析収集

収集APIs と SDKsを使用することで、ユーザーがあなたのコンテンツ上でどのような行動をしているかやマーケティングの動向を調べることができます。 実装すると、ユーザーの行動データをGoogle Analytics上で、またはレポートAPIを通して参照することができます。 クライアント側での分析収集の詳細情報については、あなたのクライアントの種類に基づいて以下のリンクをクリックしてください。:

  • Web Tracking (analytics.js) - ウェブサイドやウェブアプリケーションでのユーザーの行動を計測します。
  • Android - Android アプリケーションでのユーザーの行動を計測します。
  • iOS - iOS アプリケーションでのユーザーの行動を計測します。
  • Measurement Protocol - 低水準プロトコル環境でのユーザーの行動を計測します。


App Engine サーバ側での分析収集

App Engine では既にアプリケーションでのロギングイベントメカニズムが実装されていますが、 Google Analyticsで特定のサーバ側イベントを追跡する方が効果的です。以下のようないくつかのメリットがあります:

  • 過去データの分析 - App Engineでは、ログファイルの最大日数や最大サイズを設定することができます。 その期間が過ぎたらこれらログファイルへアクセスすることができません。 Google Analyticsのトラッキングイベントでは、はるかに長い期間の過去のイベントを見ることができます。
  • トラックキーイベント - Log files can be verbose with various components of your application writing data to them. イベントトラッキングを使用することで、あなたが監視したいイベントだけをピンポイントで指定し、いくつかの追加メタデータを付けて追跡することができます。
  • 強力なユーザーインタフェース - サーバ側イベントの見える化、報告、エクスポートをするには、Google Analyticsが提供するリッチユーザーインタフェースを使用してください。

以下のサンプルコードをApp Engineアプリケーションに組み込むことで、これらは簡単に達成できます。 この手法の詳細情報については、 Google Analytics 開発者ガイドのイベントトラッキング を参照してください。



サンプルソースコード

Java

ファイルを見る プロジェクトを見る プロジェクトのZIPをダウンロード
package com.google.appengine.analytics.tracking;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

public class GoogleAnalyticsTracking {

 
private static final URL GA_URL_ENDPOINT = getGoogleAnalyticsEndpoint();
 
private static final HTTPHeader CONTENT_TYPE_HEADER =
     
new HTTPHeader("Content-Type", "application/x-www-form-urlencoded");

 
private final String gaTrackingId;  // Tracking ID / Web property / Property ID
 
private String gaClientId = "555";  // Anonymous Client ID.
 
// Used to override the existing factory with perhaps a mock one for testing.
 
private URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();

 
private static URL getGoogleAnalyticsEndpoint() {
   
try {
     
return new URL("http", "www.google-analytics.com", "/collect");
   
} catch (MalformedURLException e) {
     
throw new RuntimeException(e);
   
}
 
}

 
public GoogleAnalyticsTracking(String gaTrackingId) throws IOException {
   
if (gaTrackingId == null) {
     
throw new IllegalArgumentException("Can't set gaTrackingId to a null value.");
   
}
   
this.gaTrackingId = gaTrackingId;
 
}

 
public GoogleAnalyticsTracking setGoogleAnalyticsClientId(String gaClientId)
     
throws IOException {
   
if (gaClientId == null) {
     
throw new IllegalArgumentException("Can't set gaClientId to a null value.");
   
}
   
this.gaClientId = gaClientId;
   
return this;
 
}

 
public GoogleAnalyticsTracking setUrlFetchService(URLFetchService urlFetchService)
     
throws IOException {
   
if (urlFetchService == null) {
     
throw new IllegalArgumentException("Can't set urlFetchService to a null value.");
   
}
   
this.urlFetchService = urlFetchService;
   
return this;
 
}

 
/**
   * Posts an Event Tracking message to Google Analytics.
   *
   * @param category the required event category
   * @param action the required event action
   * @param label the optional event label
   * @param value the optional value
   * @return true if the call succeeded, otherwise false
   * @exception IOException if the URL could not be posted to
   */

 
public int trackEventToGoogleAnalytics(
     
String category, String action, String label, String value) throws IOException {
   
Map<String, String> map = new LinkedHashMap<>();
    map
.put("v", "1");             // Version.
    map
.put("tid", gaTrackingId);
    map
.put("cid", gaClientId);
    map
.put("t", "event");         // Event hit type.
    map
.put("ec", encode(category, true));
    map
.put("ea", encode(action, true));
    map
.put("el", encode(label, false));
    map
.put("ev", encode(value, false));

   
HTTPRequest request = new HTTPRequest(GA_URL_ENDPOINT, HTTPMethod.POST);
    request
.addHeader(CONTENT_TYPE_HEADER);
    request
.setPayload(getPostData(map));

   
HTTPResponse httpResponse = urlFetchService.fetch(request);
   
// Return True if the call was successful.
   
return httpResponse.getResponseCode();
 
}

 
private static byte[] getPostData(Map<String, String> map) {
   
StringBuilder sb = new StringBuilder();
   
for (Map.Entry<String, String> entry : map.entrySet()) {
      sb
.append(entry.getKey());
      sb
.append('=');
      sb
.append(entry.getValue());
      sb
.append('&');
   
}
   
if (sb.length() > 0) {
      sb
.setLength(sb.length() - 1); // Remove the trailing &.
   
}
   
return sb.toString().getBytes(StandardCharsets.UTF_8);
 
}

 
private static String encode(String value, boolean required)
     
throws UnsupportedEncodingException {
   
if (value == null) {
     
if (required) {
       
throw new IllegalArgumentException("Required parameter not set.");
     
}
     
return "";
   
}
   
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
 
}
}


Python

ファイルを見る プロジェクトを見る プロジェクトのZIPをダウンロード
"""A function that posts a tracking event to Google Analytics."""

import urllib
from google.appengine.api import urlfetch

# Set this to the specific Google Analytics Tracking Id for your application.
GA_TRACKING_ID
= "UA-XXXX-Y"
GA_CLIENT_ID
= "555"

def track_event_to_ga(category, action, label=None, value=None):
 
""" Posts an Event Tracking message to Google Analytics. """
  form_fields
= {
   
"v": "1",               # Version.
   
"tid": GA_TRACKING_ID,  # Tracking ID / Web property / Property ID.
   
"cid": GA_CLIENT_ID,    # Anonymous Client ID.
   
"t": "event",           # Event hit type.
   
"ec": category,         # Event Category. Required.
   
"ea": action,           # Event Action. Required.
   
"el": label,            # Event label.
   
"ev": value,            # Event value.
 
}
  form_data
= urllib.urlencode(form_fields)
  result
= urlfetch.fetch(url="http://www.google-analytics.com/collect",
      payload
=form_data,
      method
=urlfetch.POST,
      headers
={"Content-Type": "application/x-www-form-urlencoded"})
 
return result.status_code