-
Notifications
You must be signed in to change notification settings - Fork 11
TrackingDetailsAndTricks
Google Analytics tracking in details, some workaround and some tricks.
set( field:String, value:String )
allow you to add a permanent parameter for all following hit requests.
For example add the application name:
tracker.set( Tracker.APP_NAME, "My Game" );
tracker.screenview( "High Scores" );
setOneTime( field:String, value:String )
allow you to add a "one shot" parameter for the next hit request.
For example change temporarily the data source
tracker.setOneTime( Tracker.DATA_SOURCE, "advertising" );
tracker.screenview( "Game Over" );
add( values:Dictionary )
works like the set()
method but allow you to add parameters in batch
from a Dictionnary
of field/value pairs.
For example define the application datas:
var gameinfo:Dictionnary = new Dictionnary();
gameinfo[ Tracker.APP_NAME ] = "My Game";
gameinfo[ Tracker.APP_ID ] = "com.something.mygame";
gameinfo[ Tracker.APP_VERSION ] = "1.0.0";
gameinfo[ Tracker.APP_INSTALLER_ID ] = "Amazon App Store";
tracker.add( gameinfo );
tracker.screenview( "Intro" );
You can use functions and/or classes helpers like:
ApplicationInfo
, SystemInfo
, TimingInfo
, etc.
generateFlashSystemInfo()
, generateAIRSystemInfo()
, generateCLISystemInfo()
, etc.
For example you would want to always add the System info:
var sysinfo:SystemInfo = generateFlashSystemInfo();
tracker.add( sysinfo.toDictionary() );
Or for example you would want to dynamically generate the application info from the AIR application descriptor:
var appinfo:ApplicationInfo = generateAIRAppInfo();
tracker.add( appinfo.toDictionary() );
The constants defined in Tracker
are the predefined data model
based on the Measurement Protocol reference.
When you use
tracker.set( Tracker.APP_NAME, "My Game" );
Tracker.APP_NAME
map to &an
based on what is defined
in the metadata
public function Metadata()
{
//...
addAlias( Tracker.APP_NAME, "an" );
}
based on the Measurement Protocol Reference
Required for all hit types.
Specifies the application name.
This field is required for all hit types sent to app properties.
For hits sent to web properties, this field is optional.
Parameter Value Type Default Value Max Length Supported Hit Types an text None 100 Bytes all Example value:
My App
Example usage:an=My%20App
That means you can not use any string
This will fail
tracker.set( "foo", "bar" );
because it does not validate against the metadata
the data model (HitModel
) ignores it and do not add it to the data set.
If you want to use a custom parameter you have to prepend it with &
This will work
tracker.set( "&foo", "bar" );
When the hit request is send to Google Analytics it will add &foo=bar
.
But be careful with that as the data model does not prevent to override already defined metadata parameters.
Instead of
tracker.set( Tracker.APP_NAME, "My Game" );
you could use
tracker.set( "&an", "My Game" );
and it would work
That way you could override some parameters and break the request you send to Google Analytics,
so be sure to check that your custom parameter is not already defined in the Metadata
class mentioned above.
Also, this Metadata
class only validate the naming of the parameters,
it does not validate
- their value type
- their max length
Such validation occurs in the Tracker
implementation
for example DefaultTracker.pageview()
public override function pageview( path:String, title:String = "" ):Boolean
{
// ...
if( title && (title.length > 0) )
{
if( title.length > 1500 )
{
throw new ArgumentError( "Title is bigger than 1500 bytes." );
}
}
}
based on the Measurement Protocol Reference
Optional.
The title of the page / document.
Parameter Value Type Default Value Max Length Supported Hit Types dt text None 1500 Bytes all Example value:
Settings
Example usage:dt=Settings
Our library may throttle events, as well as other hits, if a large number of send calls are made in a short period of time.
By default our trackers use a RateLimiter
-
Online SWF files (equivalent to analytics.js)
theWebTracker
starts with 20 hits
that are replenished at a rate of 2 hits per second. -
AIR applications (equivalent to Android SDK/iOS SDK)
theAppTracker
starts with 60 hits
that are replenished at a rate of 1 hit every 2 seconds. -
RedTamarin (command-line and server-side)
theCliTracker
starts with 100 hits
that are replenished at a rate of 10 hits per second.
By default our trackers use a sample rate of 100%, that means all hits are send, but then if your sites or apps reach millions of users you might consider sampling down your data to maybe 40% more or less.
By sampling the hits for your site or app, you will still get reliable report results while staying within the hit limits for your account.
see: How sampling works
By default, Google Analytics will group hits that are received within 30 minutes of one another into the same session. This period is configurable at the property level.
see: Learn how to configure this session timeout period
You can manually start a new session when sending a hit to Google Analytics.
The following example shows how to start a new session when sending a screen view:
tracker.setOneTime( Tracker.SESSION_CONTROL, SessionControl.START );
tracker.screenview( "Home Screen" );
Not supported yet.
As a workaround for now you could detect when a user is idle and/or present:
private function onCreationComplete():void
{
var na:NativeApplication = NativeApplication.nativeApplication;
na.idleThreshold = 2 * 60; // In seconds -- the default is 5 minutes.
na.addEventListener( Event.USER_IDLE, onUserIdle );
na.addEventListener( Event.USER_PRESENT, onUserPresent );
)
private function onUserIdle( event:Event ):void
{
tracker.setOneTime( Tracker.SESSION_CONTROL, SessionControl.END );
tracker.event( "activity", "idle" );
}
private function onUserPresent( event:Event ):void
{
tracker.setOneTime( Tracker.SESSION_CONTROL, SessionControl.START );
tracker.event( "activity", "present" );
}
Other workaround would be to update a timer for every hit request sent, and timeout the session when this timer reach 30 minutes.
Tracking pages is sending a "pageview" hit request:
tracker.pageview( "/hello/world", "Hello World" );
You can use UTF-8 in both the page path and title:
tracker.pageview( "/hello/€", "Hello €" );
Our trackers automatically add a domain name when sending a "pageview"
checkout the utilities: getHostname()
, getCLIHostname()
.
You can override the hostname this way:
tracker.set( Tracker.DOCUMENT_HOSTNAME, "www.as3lang.org" );
In some specific cases you would want to rewrite URLs containing identifying informations,
for example /user/USER_ID/account
would become /user/account
.
From inside an online SWF file or an AIR application when you track pageviews you are basically tracking virtual pages.
This is very similar to Single Page Application Tracking when an HTML page load content dynamically via AJAX.
Tracking screen is almost like pageview but the difference is that screens do not need a hostname but instead an application name.
This alone will not work:
tracker.screenview( "High Scores" );
You will need to either manually define the application name:
tracker.set( Tracker.APP_NAME, "My App" );
tracker.screenview( "High Scores" );
or automatically define the application info:
var appinfo:ApplicationInfo = generateAIRAppInfo();;
tracker.add( appinfo.toDictionary() );
tracker.screenview( "High Scores" );
Depending on how you're managing the navigation of your application you could automate the tracking of screens.
For example, you could take the convention that a screen is "visited"
when a DisplayObject
is added to the Stage:
public class MyScreen extends Sprite
{
public function MyScreen()
{
super();
name = "My Screen Name";
if( stage )
{
onAddedToStage();
}
else
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
}
//...
private function onAddedToStage( event:Event = null ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
tracker.screenview( this.name );
}
}
Use Events to collect data about interactions with your content.
See: About Events
Here a basic example:
tracker.event( "Videos", "play", "Big Buck Bunny" );
To make the difference between an event or a page or a screen the simple way to put it is
- a page is visited
- a screen is viewed
- an event is something is interacted with
and in general is user initiated
In some cases you might want to send an event as a non-interaction event.
For example to indicate that a video autoplay (eg. without the user actually clicking the "play" button).
tracker.setOneTime( Tracker.NON_INTERACTION, "1" );
tracker.event( "Videos", "play", "Mr. Robot: Official Trailer" );
Social interaction measurement allows you to measure a user's interactions with various social network sharing and recommendation widgets embedded in your content.
While event tracking measures general user-interactions very well, Social Analytics provides a consistent framework for recording social interactions. This in turn provides a consistent set of reports to compare social network interactions across multiple networks.
Basic example:
tracker.social( "Facebook", "Like", "Http://as3lang.org" );
See About Social plugins and interactions.
If you look into the addons, eg. libraries.uanalytics.tracker.addons
you will find a little example of helper for Twitter.
Here how you would use it:
var tracker:AppTracker = new AppTracker( "UA-12345-67" );
var twitter:Twitter = new Twitter( tracker );
//...
// on a Button
private function onClick( event:MouseEvent ):void
{
var sent:Boolean = twitter.retweet( this.url );
trace( "your retweet has been tracked" );
}
The helper "as is" do only the tracking, a complete solution would need to associate a library to access the Twitter API so a click on button "retweet" does send a retweet but also track this action in your analytics.
Studies have shown that reducing page load time improves the overall user experience of a site.
Google Analytics has a number of powerful reports that automatically measure and report on page load times. However, it is also possible to track custom timing information to measure performance specific to your site.
User timings allow developers to measure periods of time using the uanalytics ActionScript 3.0 library.
This is particularly useful for developers to measure the latency, or time spent, making Loader
/ URLLoader
, Socket
, etc. requests and loading web resources.
A basic example would be to indicate the time it took to load an image:
// in a Flash/AIR app it took 100ms to load a PNG image
tracker.timing( "timing", "imageloader", 100, "poster.png" );
Something more advanced would be to track time at different key points of an application
For example client-side you would make an API call
// client-side, it took 20ms to build the request
tracker.timing( "build", "REST", 20, "GET /api/version" );
// client-side, it took 300ms to send, wait, receive the response
tracker.timing( "client", "REST", 300, "GET /api/version" );
and server-side you would receive this call and return it
// server-side, it took 10ms to process the request
tracker.timing( "server", "REST", 100, "GET /api/version" );
That way even if in total you would need 300ms to send, wait and receive the call you could then split the total in more detailed results
<-- 20 --><-- ??? --><-- 100 -->
| client | wait | server |
total - ( client + server ) = wait time
300 - ( 20 + 100 ) = 180ms
When sending user timing data, you specify the amount of milliseconds spent in the timingValue parameter. It’s up to you to write code to capture this period of time.
The easiest way to do this is to create a timestamp at the beginning of a period of time and create another timestamp at the end of the period. Then you can take the difference between both timestamps to get time spent.
Here a a more detailled example:
private var timeStart:uint;
private var timeEnd:uint;
public function loadImage():void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
timeStart = getTimer();
loader.load( "BigBuckBunny.png" );
//...
}
private function onComplete( event:Event ):void
{
timeEnd = getTimer();
var diff:uint = timeEnd - timeStart;
tracker.timing( "loading", "image", diff, "BigBuckBunny.png" );
//...
}
Here a basic example:
tracker.exception( "Image not found", false );
Caught exceptions are errors in your app for which you've defined exception handling code, such as the occasional timeout of a network connection during a request for data.
Measure a caught exception by setting the exception field values on the tracker and sending the hit, as in this example:
try
{
//an error is thrown here
}
catch( e:Error )
{
tracker.exception( e.name + ":" + e.errorID, false );
}
Warning
Never send the exception message (
e.message
) to Google Analytics as it may contain personally identifiable information.
Uncaught exceptions represent instances where your app encountered unexpected conditions at runtime and are often fatal, causing the app to crash.
Uncaught exceptions can be sent to Google Analytics automatically
by setting a listener to the UncaughtErrorEvent.UNCAUGHT_ERROR
event.
public class MyScreen extends Sprite
{
public function MyScreen()
{
super();
loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, onGlobalErrors );
if( stage )
{
onAddedToStage();
}
else
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
}
//...
private function onGlobalErrors( event:UncaughtErrorEvent ):void
{
if (event.error is Error)
{
var error:Error = event.error as Error;
// do something with the error
tracker.exception( error.name + ":" + error.errorID );
}
else if (event.error is ErrorEvent)
{
var errorEvent:ErrorEvent = event.error as ErrorEvent;
// do something with the error
tracker.exception( "Error:" + errorEvent.errorID );
}
else
{
// a non-Error, non-ErrorEvent type was thrown and uncaught
tracker.exception( "unknown error occured" );
}
}
}
Read the Custom dimensions & metrics documentation.
Create and edit custom dimensions and metrics first in the Google Analytics backend.
There are limits
- 20 indices for custom dimensions (200 for Premium account)
- 20 indices for custom metrics (200 for Premium account)
- you can create them but not delete them, only disable them
- you should avoid reusing a custom dimension/metric for another one
A bit confusing right?
Let's see how a custom metric works
- you define it in the backend with the name "Memory"
in "Admin" then "Custom Definitions" - the index will be
1
- the type will be
Integer
other choices are:Currency (decimal)
,Time
- you can also define optional minimum and maximum values
- the scope will be
Hit
other choices are:Product
- be sure the variable is Active
Then you define it in your source code:
var priv_mem:Number = System.privateMemory; // bytes
var memory:uint = priv_mem / 1024 / 1024; // MB
tracker.set( Tracker.CUSTOM_METRIC(1), memory );
Which basically means "metric1" or "cm1" will be tracked as "Memory" and need to contain an integer value.
After all that you track it.
Then in a custom reports you will be able to find a "Memory" custom metric showing you the amount of memory (in MegaBytes) used by the application.
See Create and manage Custom Reports then include non-standard data in your reports.
Our follow a tutorial like How to Access Custom Dimensions in Google Analytics which explains it with coffee bean and coffee drinkers.
So that's the trick, you can select a custom dimension in the default reports but you will need to create a custom report to see custom metrics, and in both case you need to define those custom definitions on the backend before being able to collect them or see them in any reports.
Ecommerce tracking allows you to measure the number of transactions and revenue that your website generates.
On a typical ecommerce site, once a user clicks the "purchase" button in the browser, the user's purchase information is sent to the web server, which carries out the transaction. If successful, the server redirects the user to a "Thank You" or receipt page with transaction details and a receipt of the purchase. You can use the uanalytics library to send the ecommerce data from the "Thank You" page to Google Analytics.
There are two types of ecommerce data you can send using uanalytics: transaction and item data.
For example you would send a transaction like this:
tracker.transaction( "1234", "Acme Clothing", 11.99, 5, 1.29, "EUR" );
And for an item you would do that:
tracker.item( "1234", "Fluffy Pink Bunnies", 11.99, 1, "DD23444", "Party Toys" );
Note:
While most implementations will send both transaction and item data, you can send transactions without items, and items without transactions.
Our trackers can send only items without transactions or transactions without items
If you send an item hit without a transaction, a transaction hit with only the ID will be sent automatically.
This will not be done for you, you will have to handle this logic yourself.
Simply put, you have all the tools to do the ecommerce tracking but the uanalytics library does not provide an "ecommerce" logic (eg. a store/shop with items and a final transaction) for you.
Note:
Our trackers can track E-Commerce Transaction and Item but it seems
those will be deprecated in favour of Enhanced E-Commerce which uses
more complex parameters that we don't support yet.
In fact, analytics.js
need to load an additional ecommerce.js
,
see Ecommerce Tracking.
We may not support that at all as our focus is on the Measurement Protocol.