Firebase Analytics

Déclenchez une fonction lorsqu'un événement Firebase Analytics est reçu.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Firebase.Analytics.V1;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseAnalytics;

public class Function : ICloudEventFunction<AnalyticsLogData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, AnalyticsLogData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Event source: {source}", cloudEvent.Source);
        _logger.LogInformation("Event count: {count}", data.EventDim.Count);

        var firstEvent = data.EventDim.FirstOrDefault();
        if (firstEvent is object)
        {
            _logger.LogInformation("First event name: {name}", firstEvent.Name);
            DateTimeOffset timestamp = DateTimeOffset.FromUnixTimeMilliseconds(firstEvent.TimestampMicros / 1000);
            _logger.LogInformation("First event timestamp: {timestamp:u}", timestamp);
        }

        var userObject = data.UserDim;
        if (userObject is object)
        {
            _logger.LogInformation("Device model: {device}", userObject.DeviceInfo?.DeviceModel);
            _logger.LogInformation("Location: {city}, {country}", userObject.GeoInfo?.City, userObject.GeoInfo.Country);
        }
        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }
}

Go

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


// Package p contains a Google Analytics for Firebase Cloud Function.
package p

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/functions/metadata"
)

// AnalyticsEvent is the payload of an Analytics log event.
type AnalyticsEvent struct {
	EventDimensions []EventDimensions `json:"eventDim"`
	UserDimensions  interface{}       `json:"userDim"`
}

// EventDimensions holds Analytics event dimensions.
type EventDimensions struct {
	Name                    string      `json:"name"`
	Date                    string      `json:"date"`
	TimestampMicros         string      `json:"timestampMicros"`
	PreviousTimestampMicros string      `json:"previousTimestampMicros"`
	Params                  interface{} `json:"params"`
}

// HelloAnalytics handles Firebase Mobile Analytics log events.
func HelloAnalytics(ctx context.Context, e AnalyticsEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %w", err)
	}
	log.Printf("Function triggered by Google Analytics event: %v", meta.Resource)
	log.Printf("%+v", e)
	return nil
}

Node.js

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * Background Function triggered by a Google Analytics for Firebase log event.
 *
 * @param {!Object} event The Cloud Functions event.
 */
exports.helloAnalytics = event => {
  const {resource} = event;
  console.log(`Function triggered by the following event: ${resource}`);

  const [analyticsEvent] = event.data.eventDim;
  console.log(`Name: ${analyticsEvent.name}`);
  console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`);

  const userObj = event.data.userDim;
  console.log(`Device Model: ${userObj.deviceInfo.deviceModel}`);
  console.log(`Location: ${userObj.geoInfo.city}, ${userObj.geoInfo.country}`);
};

PHP

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


use Google\CloudFunctions\CloudEvent;

function firebaseAnalytics(CloudEvent $cloudevent): void
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $data = $cloudevent->getData();

    fwrite($log, 'Function triggered by the following event:' . $data['resource'] . PHP_EOL);

    $analyticsEvent = $data['eventDim'][0];
    $unixTime = $analyticsEvent['timestampMicros'] / 1000;

    fwrite($log, 'Name: ' . $analyticsEvent['name'] . PHP_EOL);
    fwrite($log, 'Timestamp: ' . gmdate("Y-m-d\TH:i:s\Z", $unixTime) . PHP_EOL);

    $userObj = $data['userDim'];
    fwrite($log, sprintf(
        'Location: %s, %s' . PHP_EOL,
        $userObj['geoInfo']['city'],
        $userObj['geoInfo']['country']
    ));

    fwrite($log, 'Device Model: %s' . $userObj['deviceInfo']['deviceModel'] . PHP_EOL);
}

Python

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

from datetime import datetime

def hello_analytics(data, context):
    """Triggered by a Google Analytics for Firebase log event.
    Args:
           data (dict): The event payload.
           context (google.cloud.functions.Context): Metadata for the event.
    """
    trigger_resource = context.resource
    print(f"Function triggered by the following event: {trigger_resource}")

    event = data["eventDim"][0]
    print(f'Name: {event["name"]}')

    event_timestamp = int(event["timestampMicros"][:-6])
    print(f"Timestamp: {datetime.utcfromtimestamp(event_timestamp)}")

    user_obj = data["userDim"]
    print(f'Device Model: {user_obj["deviceInfo"]["deviceModel"]}')

    geo_info = user_obj["geoInfo"]
    print(f'Location: {geo_info["city"]}, {geo_info["country"]}')

Ruby

Pour vous authentifier auprès de Cloud Functions, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

require "functions_framework"

# Triggered by a Google Analytics for Firebase log event.
FunctionsFramework.cloud_event "hello_analytics" do |event|
  # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  # The Analytics event payload can be obtained from the `data` field.
  payload = event.data

  logger.info "Function triggered by the following event: #{event.source}"

  event = payload["eventDim"].first
  logger.info "Name: #{event['name']}"

  event_timestamp = Time.at(event["timestampMicros"].to_i / 1_000_000).utc
  logger.info "Timestamp: #{event_timestamp.strftime '%Y-%m-%dT%H:%M:%SZ'}"

  user_obj = payload["userDim"]
  logger.info "Device Model: #{user_obj['deviceInfo']['deviceModel']}"

  geo_info = user_obj["geoInfo"]
  logger.info "Location: #{geo_info['city']}, #{geo_info['country']}"
end

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.