記錄事件

選取平台: iOS+ Android Web Flutter Unity C++


事件可讓您深入瞭解應用程式中的活動,例如使用者動作、系統事件或錯誤。

Google Analytics 會自動記錄部分事件,您不必新增任何程式碼,就能接收這些事件。如果應用程式需要收集其他資料,您最多可以在應用程式中記錄 500 種不同的 Analytics 事件類型。應用程式記錄的事件總量沒有限制。請注意,事件名稱區分大小寫。也就是說,如果事件只有名稱大小寫不同,記錄上仍會顯示為兩組不同的事件。

事前準備

請確認您已設定專案,並可按照「開始使用 C++ 版 Analytics」一文所述存取 Analytics。

記錄事件

初始化 firebase::analytics 模組後,您可以使用 LogEvent() 方法記錄事件。

為協助您快速上手,Analytics SDK 定義了多種建議事件,這些事件在不同類型的應用程式中都很常見,包括零售和電子商務、旅遊和遊戲應用程式。如要進一步瞭解這些事件和使用時機,請瀏覽 Firebase 說明中心的「事件和屬性」文章。

您可以在下列位置找到建議事件的導入詳細資料:

  • 建議事件:請參閱 Event 常數清單。
  • 預設參數:請參閱 Parameters 常數清單。

以下範例說明如何記錄建議的 SELECT_CONTENT 事件:

  const analytics::Parameter kSelectContentParameters[] = {
    analytics::Parameter(analytics::kParameterItemID , id),
    analytics::Parameter(analytics::kParameterItemName, "name"),
    analytics::Parameter(analytics::kUserPropertySignUpMethod, "Google"),
    analytics::Parameter("favorite_food", mFavoriteFood),
    analytics::Parameter("user_id", mUserId),
  };
  analytics::LogEvent(
    analytics::kEventSelectContent, kSelectContentParameters,
    sizeof(kSelectContentParameters) / sizeof(kSelectContentParameters[0]));

除了規定的參數外,您也可以在任何事件中加入下列參數:

  • 自訂參數:自訂參數不會直接顯示在Analytics報表中,但可做為目標對象定義中的篩選器,套用至所有報表。如果應用程式已連結至 BigQuery 專案,自訂參數也會包含在匯出至 BigQuery 的資料中。

  • VALUE 參數:VALUE 是通用參數,可用於累積與 Analytics 事件相關的重要指標。例如收益、距離、時間和點數。

如果應用程式有特定需求,但建議的 Analytics 事件類型不適用,您可以記錄自訂 Analytics 事件,如下例所示:

// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "firebase/analytics.h"
#include "firebase/analytics/event_names.h"
#include "firebase/analytics/parameter_names.h"
#include "firebase/analytics/user_property_names.h"
#include "firebase/app.h"

// Thin OS abstraction layer.
#include "main.h"  // NOLINT

// Execute all methods of the C++ Analytics API.
extern "C" int common_main(int argc, const char* argv[]) {
  namespace analytics = ::firebase::analytics;
  ::firebase::App* app;

  LogMessage("Initialize the Analytics library");
#if defined(__ANDROID__)
  app = ::firebase::App::Create(GetJniEnv(), GetActivity());
#else
  app = ::firebase::App::Create();
#endif  // defined(__ANDROID__)

  LogMessage("Created the firebase app %x",
             static_cast<int>(reinterpret_cast<intptr_t>(app)));
  analytics::Initialize(*app);
  LogMessage("Initialized the firebase analytics API");

  LogMessage("Enabling data collection.");
  analytics::SetAnalyticsCollectionEnabled(true);
  // App session times out after 30 minutes.
  // If the app is placed in the background and returns to the foreground after
  // the timeout is expired analytics will log a new session.
  analytics::SetSessionTimeoutDuration(1000 * 60 * 30);

  LogMessage("Get App Instance ID...");
  auto future_result = analytics::GetAnalyticsInstanceId();
  while (future_result.status() == firebase::kFutureStatusPending) {
    if (ProcessEvents(1000)) break;
  }
  if (future_result.status() == firebase::kFutureStatusComplete) {
    LogMessage("Analytics Instance ID %s", future_result.result()->c_str());
  } else {
    LogMessage("ERROR: Failed to fetch Analytics Instance ID %s (%d)",
               future_result.error_message(), future_result.error());
  }

  LogMessage("Set user properties.");
  // Set the user's sign up method.
  analytics::SetUserProperty(analytics::kUserPropertySignUpMethod, "Google");
  // Set the user ID.
  analytics::SetUserId("uber_user_510");

  LogMessage("Log current screen.");
  // Log the user's current screen.
  analytics::LogEvent(analytics::kEventScreenView, "Firebase Analytics C++ testapp", "testapp" );

  // Log an event with no parameters.
  LogMessage("Log login event.");
  analytics::LogEvent(analytics::kEventLogin);

  // Log an event with a floating point parameter.
  LogMessage("Log progress event.");
  analytics::LogEvent("progress", "percent", 0.4f);

  // Log an event with an integer parameter.
  LogMessage("Log post score event.");
  analytics::LogEvent(analytics::kEventPostScore, analytics::kParameterScore,
                      42);

  // Log an event with a string parameter.
  LogMessage("Log group join event.");
  analytics::LogEvent(analytics::kEventJoinGroup, analytics::kParameterGroupID,
                      "spoon_welders");

  // Log an event with multiple parameters.
  LogMessage("Log level up event.");
  {
    const analytics::Parameter kLevelUpParameters[] = {
        analytics::Parameter(analytics::kParameterLevel, 5),
        analytics::Parameter(analytics::kParameterCharacter, "mrspoon"),
        analytics::Parameter("hit_accuracy", 3.14f),
    };
    analytics::LogEvent(
        analytics::kEventLevelUp, kLevelUpParameters,
        sizeof(kLevelUpParameters) / sizeof(kLevelUpParameters[0]));
  }

  LogMessage("Complete");

  // Wait until the user wants to quit the app.
  while (!ProcessEvents(1000)) {
  }

  analytics::Terminate();
  delete app;

  LogMessage("Shutdown");

  return 0;
}

在 Android Studio 偵錯記錄檔中查看事件

您可以啟用詳細記錄功能,監控 SDK 記錄事件的情況,確認事件是否正確記錄。包括自動和手動記錄的事件。

您可以使用一系列 ADB 指令啟用詳細記錄功能:

adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

這個指令會在 Android Studio logcat 中顯示事件,協助您立即確認事件是否已傳送。

在資訊主頁中查看數據分析事件

在 Firebase 控制台中,您可以依序前往「 Analytics」 > 「Events」資訊主頁,查看事件的匯總統計資料。

請注意這個資訊主頁的下列事項:

  • 資訊主頁會顯示事件報表,這些報表是系統根據應用程式記錄的每種事件類型自動建立。

  • 資訊主頁一整天內會定時更新。如要立即測試,請按照本指南上一節所述,使用 Xcode 偵錯控制台或 Logcat 輸出內容。

進一步瞭解資訊主頁。