読者です 読者をやめる 読者になる 読者になる

Spring Boot + kotlinでGoogle Analytics APIを使ってみた

Googleアナリテクスの設定は本家情報を参照

https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-java?hl=ja

手順まとめ
  1. Google API Consoleでサービスアカウントを作成して認証する鍵を作成(今回はp12ファイルを使う)
  2. Googleアナリティクスのユーザ追加でAPI Consoleで作成したアクアンとを追加する

※ 2のConsoleで作ったアカウントをGoogleアナリティクスにユーザ追加が抜けていたため、ハマってしまった。

ビルドツールはgraldeを使う

compile "com.google.apis:google-api-services-analytics:$google_api_version"

versionは4.7を使う。

Configurationのインスタンス

@Configuration
open class GoogleAnalyticsConfig {

    val applicationName = "googleAnalytics"
    val jsonFactory = JacksonFactory.getDefaultInstance()!!
    val serviceAccountEmail = "xxxxx@xxxxx.iam.gserviceaccount.com"
    val keyFileLocation = "/credential.p12"

    @Bean
    open fun analytics(): Analytics {
        val httpTransport = GoogleNetHttpTransport.newTrustedTransport()
        val credential = GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(serviceAccountEmail)
                .setServiceAccountPrivateKeyFromP12File(
                        File(javaClass.getResource(keyFileLocation).path))
                .setServiceAccountScopes(AnalyticsScopes.all())
                .build();
        return Analytics.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName(applicationName).build();
    }
}
  • serviceAccountEmailはAPI Consoleで作成したアカウントのメールアドレス
  • keyFileLocationはAPI Consoleで作成したアカウントの認証鍵

データの取得

  • 昨日から今日までのセッション数を性別と年齢別に取得する
  • "ga:" + "xxxxx"のxxxxxはアナリティクスのprofileIDを指定する
  • 簡易的なコントローラーを用意してlog出力
@RestController
open class AnalyticsController @Autowired constructor(val googleAnalytics: Analytics) {

    val log: Logger = LoggerFactory.getLogger("ANALYTICS");

    @RequestMapping(value = "/analytics", method = arrayOf(RequestMethod.GET))
    fun index(): String {
        val gaData = googleAnalytics.data().ga()
                .get("ga:" + "xxxxx", "yesterday", "today", "ga:sessions")
                .setDimensions("ga:visitorGender,ga:visitorAgeBracket")
                .execute()

        for (row in gaData.rows) {
            log.info(Moshi.Builder().build()
                    .adapter(List::class.java)
                    .toJson(row))
        }

        return "ok";
    }
}
出力例
{"@timestamp":"2016-11-07T12:10:56.021+09:00","@version":1,"message":"[\"female\",\"18-24\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.022+09:00","@version":1,"message":"[\"female\",\"25-34\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.023+09:00","@version":1,"message":"[\"female\",\"35-44\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.024+09:00","@version":1,"message":"[\"female\",\"45-54\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.025+09:00","@version":1,"message":"[\"female\",\"55-64\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.025+09:00","@version":1,"message":"[\"male\",\"18-24\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.026+09:00","@version":1,"message":"[\"male\",\"25-34\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.027+09:00","@version":1,"message":"[\"male\",\"35-44\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}
{"@timestamp":"2016-11-07T12:10:56.028+09:00","@version":1,"message":"[\"male\",\"45-54\",\"xxx\"]","logger_name":"ANALYTICS","thread_name":"http-nio-8080-exec-7","level":"INFO","level_value":20000,"HOSTNAME":"xxxxx"}