Integrating with Google Analytics

The Google Analytics Platform lets you measure user interactions with your business across various devices and environments. Google Analytics provides the resources to collect, store, process, and report on these user-interactions.

You can collect analytics on the client side and on the server side.

Client-side analytics collection

Use the Google Analytics APIs and SDKs to measure how users interact with your content and marketing initiatives. You can view user-interaction data in the Google Analytics user interface or use the Reporting APIs to fetch the data. For more details on client-side analytics collection, select the link below based on the type of your client:

  • Web Tracking (analytics.js) - Measure user interaction with websites or web applications.
  • Android - Measure user interaction with Android applications.
  • iOS - Measure user interaction with iOS applications.
  • Measurement Protocol - Measure user interaction in any environment with this low-level protocol.

Server-side analytics collection

Although App Engine provides a mechanism for logging events in your application, you can use Google Analytics to track specific server-side events in Google Analytics so that you can:

  • Analyze historical data - App Engine allows you to configure the maximum number of days, or size, of your log file. After that limit has been passed, you no longer have access to those log files. Tracking events in Google Analytics provides you a much longer lifespan into the visibility of past events.
  • Track key events - Log files can be verbose with various components of your application writing data to them. By using event tracking, you can pinpoint key events and track them, along with some metadata.
  • Work in the user interface - Take advantage of the rich user interface that Google Analytics provides to visualize, report, and export these server-side events.

To enable server-side analytics collection, you can use an HTTP client and make HTTP requests using the Google Analytics Measurement Protocol. For additional information, consult the Google Analytics developers guide for Event Tracking.

Sample Application

The sample application below shows how to track events in your App Engine application. The application makes an HTTP request and posts data about the event to Google Analytics.

Before you use the Google Analytics Measurement Protocol on Google App Engine:

* Before running the sample app locally, set the environment variables required by the app:



    export GA_TRACKING_ID=YOUR_TRACKING_ID


  • You can run the sample code locally using the command line. For example :

    python main.py
    

    • You can integrate the following code into your App Engine application to post event tracking data to Google Analytics:

      import logging
      import os
      
      from flask import Flask
      import requests
      
      
      app = Flask(__name__)
      
      
      # Environment variables are defined in app.yaml.
      GA_TRACKING_ID = os.environ['GA_TRACKING_ID']
      
      
      def track_event(category, action, label=None, value=0):
          data = {
              'v': '1',  # API Version.
              'tid': GA_TRACKING_ID,  # Tracking ID / Property ID.
              # Anonymous Client Identifier. Ideally, this should be a UUID that
              # is associated with particular user, device, or browser instance.
              'cid': '555',
              't': 'event',  # Event hit type.
              'ec': category,  # Event category.
              'ea': action,  # Event action.
              'el': label,  # Event label.
              'ev': value,  # Event value, must be an integer
          }
      
          response = requests.post(
              'http://www.google-analytics.com/collect', data=data)
      
          # If the request fails, this will raise a RequestException. Depending
          # on your application's needs, this may be a non-error and can be caught
          # by the caller.
          response.raise_for_status()
      
      
      @app.route('/')
      def track_example():
          track_event(
              category='Example',
              action='test action')
          return 'Event tracked.'
      
      
      @app.errorhandler(500)
      def server_error(e):
          logging.exception('An error occurred during a request.')
          return """
          An internal error occurred: <pre>{}</pre>
          See logs for full stacktrace.
          """.format(e), 500
      
      
      if __name__ == '__main__':
          # This is used when running locally. Gunicorn is used to run the
          # application on Google App Engine. See entrypoint in app.yaml.
          app.run(host='127.0.0.1', port=8080, debug=True)

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

App Engine flexible environment for Python docs