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を使う

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

versionは4.7を使う。

Configurationのインスタンス

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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();
    }
}

データの取得

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
@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";
    }
}
出力例
1
2
3
4
5
6
7
8
9
{"@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"}