Introduction

Glean is a modern approach for a telemetry library and is part of the Glean project.

Glean logo

There are two implementations of Glean, with support for 5 different programming languages in total. Both implementations strive to contain the same features with similar, but idiomatic APIs.

Unless clearly stated otherwise, regard the text in this book as valid for both clients and all the supported programming languages and environments.

The Glean SDK

The Glean SDK is an implementation of Glean in Rust, with language bindings for Kotlin, Python, Rust and Swift.

For development documentation on the Glean SDK, refer to the Glean SDK development book.

To report issues or request changes on the Glean SDK, file a bug in Bugzilla in Data Platform & Tools :: Glean: SDK.

Glean.js

Glean.js is an implementation of Glean in JavaScript. Currently, it only has support for usage in web extensions.

For development documentation on Glean.js, refer to the Glean.js development documentation.

To report issues or request changes on Glean.js, file a bug in Bugzilla in Data Platform & Tools :: Glean.js.

Note Glean.js is still in development and does not provide all the features the Glean SDK does. Feature parity will be worked on after initial validation. Do not hesitate to file a bug if you want to use Glean.js and is missing some key Glean feature.

Sections

User Guides

This section of the book contains mostly step-by-step guides and essays detailing how to achieve specific tasks with Glean.

It contains guides on the first steps of integrating Glean into your project, choosing the right metric type for you, debugging products that use Glean and Glean's built-in error reporting mechanism.

If you want to start using Glean to report data, this is the section you should read.

API Reference

This section of the book contains reference pages for Glean’s user facing APIs.

If you are looking for information a specific Glean API, this is the section you should check out.

Language Binding Information

This section contains guides and essays regarding specific usage information and possibilities in each of Glean's language bindings.

Check out this section for information on the language binding you are using.

Appendix

Glossary

In this book we use a lot of Glean specific terminology. In the glossary, we go through many of the terms used throughout this book and describe exactly what we mean when we use them.

Changelog

This section contains detailed notes about changes in Glean, per release.

This Week in Glean

“This Week in Glean” is a series of blog posts that the Glean Team at Mozilla is using to try to communicate better about our work. They could be release notes, documentation, hopes, dreams, or whatever: so long as it is inspired by Glean.

Contribution Guidelines

This section contains detailed information on where and how to include new content to this book.

Contact

To contact the Glean team you can:

  • Find us in the #glean channel on chat.mozilla.org.
  • Send an email to glean-team@mozilla.com.
  • The Glean SDK team is: :janerik, :dexter, :travis, :mdroettboom, :gfritzsche, :chutten, :brizental.

License

Glean.js and the Glean SDK Source Code is subject to the terms of the Mozilla Public License v2.0. You can obtain a copy of the MPL at https://mozilla.org/MPL/2.0/.

Adding Glean to your project

This page describes the steps for adding Glean to a project. This does not include the steps for adding a new metrics or pings to an existing Glean integration. If that is what your are looking for, refer to the Adding new metrics or the Adding new pings guide.

Glean integration checklist

The Glean integration checklist can help to ensure your Glean SDK-using product is meeting all of the recommended guidelines.

Products (applications or libraries) using the Glean SDK to collect telemetry must:

  1. Integrate the Glean SDK into the build system. Since the Glean SDK does some code generation for your metrics at build time, this requires a few more steps than just adding a library.

  2. Go through data review process for all newly collected data.

  3. Ensure that telemetry coming from automated testing or continuous integration is either not sent to the telemetry server or tagged with the automation tag using the sourceTag feature.

  4. At least one week before releasing your product, file a data engineering bug to enable your product's application id and have your metrics be indexed by the Glean Dictionary.

Additionally, applications (but not libraries) must:

  1. Request a data review to add Glean to your application (since it can send data out of the box).

  2. Initialize Glean as early as possible at application startup.

  3. Provide a way for users to turn data collection off (e.g. providing settings to control Glean.setUploadEnabled()). The exact method used is application-specific.

Looking for an integration guide?

Step-by-step tutorials for each supported language/platform, can be found on the specific integration guides:

Adding Glean to your Kotlin project

This page provides a step-by-step guide on how to integrate the Glean library into a Kotlin project.

Nevertheless this is just one of the required steps for integrating Glean successfully into a project. Check you the full Glean integration checklist for a comprehensive list of all the steps involved in doing so.

Currently, these bindings only support the Android platform.

Setting up the dependency

The Glean SDK is published on maven.mozilla.org. To use it, you need to add the following to your project's top-level build file, in the allprojects block (see e.g. Glean SDK's own build.gradle):

repositories {
    maven {
       url "https://maven.mozilla.org/maven2"
    }
}

Each module that uses Glean SDK needs to specify it in its build file, in the dependencies block. Add this to your Gradle configuration:

implementation "org.mozilla.components:service-glean:{latest-version}"
Pick the correct version

The {latest-version} placeholder in the above link should be replaced with the version of Android Components used by the project.

The Glean SDK is released as part of android-components. Therefore, it follows android-components' versions. The android-components release page can be used to determine the latest version.

For example, if version 33.0.0 is used, then the include directive becomes:

implementation "org.mozilla.components:service-glean:33.0.0"
Size impact on the application APK

The Glean SDK APK ships binary libraries for all the supported platforms. Each library file measures about 600KB. If the final APK size of the consuming project is a concern, please enable ABI splits.

Dependency for local testing

Due to its use of a native library you will need additional setup to allow local testing.

First add a new configuration to your build.gradle, just before your dependencies:

configurations {
    jnaForTest
}

Then add the following lines to your dependencies block:

jnaForTest "net.java.dev.jna:jna:5.6.0@jar"
testImplementation files(configurations.jnaForTest.copyRecursive().files)
testImplementation "org.mozilla.telemetry:glean-forUnitTests:${project.ext.glean_version}"

Note: Always use org.mozilla.telemetry:glean-forUnitTests. This package is standalone and its version will be exported from the main Glean package automatically.

Setting up metrics and pings code generation

In order for the Glean SDK to generate an API for your metrics, two Gradle plugins must be included in your build:

The Glean Gradle plugin is distributed through Mozilla's Maven, so we need to tell your build where to look for it by adding the following to the top of your build.gradle:

buildscript {
    repositories {
        // Include the next clause if you are tracking snapshots of android components
        maven {
            url "https://snapshots.maven.mozilla.org/maven2"
        }
        maven {
            url "https://maven.mozilla.org/maven2"
        }

        dependencies {
            classpath "org.mozilla.components:tooling-glean-gradle:{android-components-version}"
        }
    }
}
Important

As above, the {android-components-version} placeholder in the above link should be replaced with the version number of android components used in your project.

The JetBrains Python plugin is distributed in the Gradle plugin repository, so it can be included with:

plugins {
    id "com.jetbrains.python.envs" version "0.0.26"
}

Right before the end of the same file, we need to apply the Glean Gradle plugin. Set any additional parameters to control the behavior of the Glean Gradle plugin before calling apply plugin.

// Optionally, set any parameters to send to the plugin.
ext.gleanGenerateMarkdownDocs = true
apply plugin: "org.mozilla.telemetry.glean-gradle-plugin"
Earlier versions

Note: Earlier versions of Glean used a Gradle script (sdk_generator.gradle) rather than a Gradle plugin. Its use is deprecated and projects should be updated to use the Gradle plugin as described above.

Offline builds

The Glean Gradle plugin has limited support for offline builds of applications that use the Glean SDK.

Adding Glean to your Swift project

This page provides a step-by-step guide on how to integrate the Glean library into a Swift project.

Nevertheless this is just one of the required steps for integrating Glean successfully into a project. Check you the full Glean integration checklist for a comprehensive list of all the steps involved in doing so.

Currently, these bindings only support the iOS platform.

Requirements

  • Python >= 3.6.

Setting up the dependency

The Glean SDK can be consumed through Carthage, a dependency manager for macOS and iOS. For consuming the latest version of the Glean SDK, add the following line to your Cartfile:

github "mozilla/glean" "{latest-version}"
Pick the correct version

The {latest-version} placeholder should be replaced with the version number of the latest Glean SDK release. You can find the version number on the release page.

Then check out and build the new dependency:

carthage update --platform iOS

Integrating with the build system

For integration with the build system you can follow the Carthage Quick Start steps.

  1. After building the dependency one drag the built .framework binaries from Carthage/Build/iOS into your application's Xcode project.

  2. On your application targets' Build Phases settings tab, click the + icon and choose New Run Script Phase. If you already use Carthage for other dependencies, extend the existing step. Create a Run Script in which you specify your shell (ex: /bin/sh), add the following contents to the script area below the shell:

    /usr/local/bin/carthage copy-frameworks
    
  3. Add the path to the Glean framework under "Input Files":

    $(SRCROOT)/Carthage/Build/iOS/Glean.framework
    
  4. Add the paths to the copied framework to the "Output Files":

    $(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/Glean.framework
    

Combined usage with application-services

If your application uses both the Glean SDK and application-services you can use a combined release to reduce the memory usage and startup time impact.

In your Cartfile require only application-services, e.g.:

github "mozilla/application-services" ~> "{latest-version}"
Pick the correct version

The {latest-version} placeholder should be replaced with the version number of the latest application-services release. You can find the version number on the release page.

Then check out and build the new dependency:

carthage update --platform iOS

Setting up metrics and pings code generation

The metrics.yaml file is parsed at build time and Swift code is generated. Add a new metrics.yaml file to your Xcode project.

Follow these steps to automatically run the parser at build time:

  1. Download the sdk_generator.sh script from the Glean repository:
    https://raw.githubusercontent.com/mozilla/glean/{latest-release}/glean-core/ios/sdk_generator.sh
    
Pick the correct version

As above, the {latest-version} placeholder should be replaced with the version number of Glean SDK release used in this project.

  1. Add the sdk_generator.sh file to your Xcode project.

  2. On your application targets' Build Phases settings tab, click the + icon and choose New Run Script Phase. Create a Run Script in which you specify your shell (ex: /bin/sh), add the following contents to the script area below the shell:

    bash $PWD/sdk_generator.sh
    
Using with application-services

If you are using the combined release of application-services and the Glean SDK you need to set the namespace to MozillaAppServices, e.g.:

bash $PWD/sdk_generator.sh --glean-namespace MozillaAppServices
  1. Add the path to your metrics.yaml and (optionally) pings.yaml under "Input files":

    $(SRCROOT)/{project-name}/metrics.yaml
    $(SRCROOT)/{project-name}/pings.yaml
    
  2. Add the path to the generated code file to the "Output Files":

    $(SRCROOT)/{project-name}/Generated/Metrics.swift
    
The generated API

The parser now generates a single file called Metrics.swift (since Glean v31.0.0).

  1. If you are using Git, add the following lines to your .gitignore file:

    .venv/
    {project-name}/Generated
    

    This will ignore files that are generated at build time by the sdk_generator.sh script. They don't need to be kept in version control, as they can be re-generated from your metrics.yaml and pings.yaml files.

Glean and embedded extensions

Metric collection is a no-op in application extensions and Glean will not run. Since extensions run in a separate sandbox and process from the application, Glean would run in an extension as if it were a completely separate application with different client ids and storage. This complicates things because Glean doesn’t know or care about other processes. Because of this, Glean is purposefully prevented from running in an application extension and if metrics need to be collected from extensions, it's up to the integrating application to pass the information to the base application to record in Glean.

Adding Glean to your Python project

This page provides a step-by-step guide on how to integrate the Glean library into a Python project.

Nevertheless this is just one of the required steps for integrating Glean successfully into a project. Check you the full Glean integration checklist for a comprehensive list of all the steps involved in doing so.

Setting up the dependency

We recommend using a virtual environment for your work to isolate the dependencies for your project. There are many popular abstractions on top of virtual environments in the Python ecosystem which can help manage your project dependencies.

The Glean SDK Python bindings currently have prebuilt wheels on PyPI for Windows (i686 and x86_64), Linux/glibc (x86_64) and macOS (x86_64). For other platforms, including BSD or Linux distributions that don't use glibc, such as Alpine Linux, the glean_sdk package will be built from source on your machine. This requires that Cargo and Rust are already installed. The easiest way to do this is through rustup.

Once you have your virtual environment set up and activated, you can install the Glean SDK into it using:

$ python -m pip install glean_sdk
Important

Installing Python wheels is still a rapidly evolving feature of the Python package ecosystem. If the above command fails, try upgrading pip:

python -m pip install --upgrade pip
Important

The Glean SDK Python bindings make extensive use of type annotations to catch type related errors at build time. We highly recommend adding mypy to your continuous integration workflow to catch errors related to type mismatches early.

Consuming YAML registry files

For Python, the metrics.yaml file must be available and loaded at runtime.

If your project is a script (i.e. just Python files in a directory), you can load the metrics.yaml using:

from glean import load_metrics

metrics = load_metrics("metrics.yaml")

# Use a metric on the returned object
metrics.your_category.your_metric.set("value")

If your project is a distributable Python package, you need to include the metrics.yaml file using one of the myriad ways to include data in a Python package and then use pkg_resources.resource_filename() to get the filename at runtime.

from glean import load_metrics
from pkg_resources import resource_filename

metrics = load_metrics(resource_filename(__name__, "metrics.yaml"))

# Use a metric on the returned object
metrics.your_category.your_metric.set("value")

Automation steps

Documentation

The documentation for your application or library's metrics and pings are written in metrics.yaml and pings.yaml.

For Mozilla projects, this SDK documentation is automatically published on the Glean Dictionary. For non-Mozilla products, it is recommended to generate markdown-based documentation of your metrics and pings into the repository. For most languages and platforms, this transformation can be done automatically as part of the build. However, for some language bindings the integration to automatically generate docs is an additional step.

The Glean SDK provides a commandline tool for automatically generating markdown documentation from your metrics.yaml and pings.yaml files. To perform that translation, run glean_parser's translate command:

python3 -m glean_parser translate -f markdown -o docs metrics.yaml pings.yaml

To get more help about the commandline options:

python3 -m glean_parser translate --help

We recommend integrating this step into your project's documentation build. The details of that integration is left to you, since it depends on the documentation tool being used and how your project is set up.

Metrics linting

Glean includes a "linter" for metrics.yaml and pings.yaml files called the glinter that catches a number of common mistakes in these files.

As part of your continuous integration, you should run the following on your metrics.yaml and pings.yaml files:

python3 -m glean_parser glinter metrics.yaml pings.yaml

Parallelism

All of the Glean SDK's target languages use a separate worker thread to do most of its work, including any I/O. This thread is fully managed by the Glean SDK as an implementation detail. Therefore, users should feel free to use the Glean SDK wherever it is most convenient, without worrying about the performance impact of updating metrics and sending pings.

Since the Glean SDK performs disk and networking I/O, it tries to do as much of its work as possible on separate threads and processes. Since there are complex trade-offs and corner cases to support Python parallelism, it is hard to design a one-size-fits-all approach.

Default behavior

When using the Python bindings, most of the Glean SDK's work is done on a separate thread, managed by the Glean SDK itself. The Glean SDK releases the Global Interpreter Lock (GIL) for most of its operations, therefore your application's threads should not be in contention with the Glean SDK's worker thread.

The Glean SDK installs an atexit handler so that its worker thread can cleanly finish when your application exits. This handler will wait up to 30 seconds for any pending work to complete.

By default, ping uploading is performed in a separate child process. This process will continue to upload any pending pings even after the main process shuts down. This is important for commandline tools where you want to return control to the shell as soon as possible and not be delayed by network connectivity.

Cases where subprocesses aren't possible

The default approach may not work with applications built using PyInstaller or similar tools which bundle an application together with a Python interpreter making it impossible to spawn new subprocesses of that interpreter. For these cases, there is an option to ensure that ping uploading occurs in the main process. To do this, set the allow_multiprocessing parameter on the glean.Configuration object to False.

Using the multiprocessing module

Additionally, the default approach does not work if your application uses the multiprocessing module for parallelism. The Glean SDK can not wait to finish its work in a multiprocessing subprocess, since atexit handlers are not supported in that context.
Therefore, if the Glean SDK detects that it is running in a multiprocessing subprocess, all of its work that would normally run on a worker thread will run on the main thread. In practice, this should not be a performance issue: since the work is already in a subprocess, it will not block the main process of your application.

Adding Glean to your JavaScript project

This page provides a step-by-step guide on how to integrate the Glean.js library into a JavaScript project.

Nevertheless this is just one of the required steps for integrating Glean successfully into a project. Check you the full Glean integration checklist for a comprehensive list of all the steps involved in doing so.

Currently, these bindings support collecting data from Browser Extensions (cross-browser), Node.js1 applications or scripts and Qt/QML applications2.

1

The Node.js SDK does not have persistent storage yet. This means, Glean does not persist state throughout application runs. For updates on the implementation of this feature in Node.js, follow Bug 1728807.

2

For information on adding Glean to a Qt/QML application, refer to the Qt specific documentation.

Requirements

  • Node.js >= 12.20.0
  • npm >= 7.0.0
  • Webpack >= 5.34.0
  • Python >= 3.6
    • The glean command requires Python to download glean_parser which is a Python library

Browser extension specific requirements

  • webextension-polyfill >= 0.8.0
    • Glean.js assumes a Promise-based browser API: Firefox provides such an API by default. Other browsers may require using a polyfill library such us webextension-polyfill when using Glean in browser extensions
  • Host permissions to the telemetry server
    • Only necessary if the defined server endpoint denies cross-origin requests
    • The default incoming.telemetry.mozilla.org server does require this type of permission. Follow Bug 1676676 for updates on this requirement
  • "storage" API permissions

Browser extension example configuration

The manifest.json file of the sample browser extension available on the mozilla/glean.js repository provides an example on how to define the above permissions as well as how and where to load the webextension-polyfill script.

Setting up the dependency

The Glean.js package is distributed as an npm package @mozilla/glean.

Install Glean.js in your JavaScript project, by running:

npm install @mozilla/glean

Then import Glean into your project:

// Glean.js for browser extensions
//
// esm
import Glean from "@mozilla/glean/webext";
// cjs
const { default: Glean } = require("@mozilla/glean/webext");

// Glean.js for Node.js
//
// esm
import Glean from "@mozilla/glean/node";
// cjs
const { default: Glean } = require("@mozilla/glean/node");

The currently available entry points are:

  • @mozilla/glean/webext
  • @mozilla/glean/node

Browser extension security considerations

In case of privilege-escalation attack into the context of the web extension using Glean, the malicious scripts would be able to call Glean APIs or use the browser.storage.local APIs directly. That would be a risk to Glean data, but not caused by Glean. Glean-using extensions should be careful not to relax the default Content-Security-Policy that generally prevents these attacks.

Common import errors

"Cannot find module '@mozilla/glean'"

Glean.js does not have a main package entry point. Instead it relies on a series of entry points depending on the platform you are targeting.

In order to import Glean use:

import Glean from '@mozilla/glean/{your-platform}'

"Module not found: Error: Can't resolve '@mozilla/glean/webext' in '...'"

Glean.js relies on Node.js' subpath exports feature to define multiple package entry points.

Please make sure that you are using a supported Node.js runtime and also make sure the tools you are using support this Node.js feature.

Setting up metrics and pings code generation

In JavaScript, the metrics and pings definitions must be parsed at build time. The @mozilla/glean package exposes glean_parser through the glean script.

To parse your YAML registry files using this script, define a new script in your package.json file:

{
  // ...
  "scripts": {
    // ...
    "build:glean": "glean translate path/to/metrics.yaml path/to/pings.yaml -f javascript -o path/to/generated",
    // Or, if you are building for a Typescript project
    "build:glean": "glean translate path/to/metrics.yaml path/to/pings.yaml -f typescript -o path/to/generated"
  }
}

Then run this script by calling:

npm run build:glean

Automation steps

Documentation

Prefer using the Glean Dictionary

While it is still possible to generate Markdown documentation, if working on a public Mozilla project rely on the Glean Dictionary for documentation. Your product will be automatically indexed by the Glean Dictionary after it gets enabled in the pipeline.

One of the commands provided by glean_parser allows users to generate Markdown documentation based on the contents of their YAML registry files. To perform that translation, use the translate command with a different output format, as shown below.

In your package.json, define the following script:

{
  // ...
  "scripts": {
    // ...
    "docs:glean": "glean translate path/to/metrics.yaml path/to/pings.yaml -f markdown -o path/to/docs",
  }
}

Then run this script by calling:

npm run docs:glean

YAML registry files linting

Glean includes a "linter" for the YAML registry files called the glinter that catches a number of common mistakes in these files. To run the linter use the glinter command.

In your package.json, define the following script:

{
  // ...
  "scripts": {
    // ...
    "lint:glean": "glean glinter path/to/metrics.yaml path/to/pings.yaml",
  }
}

Then run this script by calling:

npm run lint:glean

Adding Glean to your Qt/QML project

This page provides a step-by-step guide on how to integrate the Glean.js library into a Qt/QML project.

Nevertheless this is just one of the required steps for integrating Glean successfully into a project. Check you the full Glean integration checklist for a comprehensive list of all the steps involved in doing so.

Requirements

  • Python >= 3.6
  • Qt >= 5.15.2

Setting up the dependency

Glean.js' Qt/QML build is distributed as an asset with every Glean.js release. In order to download the latest version visit https://github.com/mozilla/glean.js/releases/latest.

Glean.js is a QML module, so extract the contents of the downloaded file wherever you keep your other modules. Make sure that whichever directory that module is placed in, is part of the QML Import Path.

After doing that, import Glean like so:

import org.mozilla.Glean <version>

Picking the correct version

The <version> number is the version of the release you downloaded minus its patch version. For example, if you downloaded Glean.js version 0.15.0 your import statement will be:

import org.mozilla.Glean 0.15

Consuming YAML registry files

Qt/QML projects need to setup metrics and pings code generation manually.

First install the glean_parser CLI tool.

pip install glean_parser

Make sure you have the correct glean_parser version!

Qt/QML support was added to glean_parser in version 3.5.0.

Then call glean_parser from the command line:

glean_parser translate path/to/metrics.yaml path/to/pings.yaml \
  -f javascript \
  -o path/to/generated/files \
  --option platform=qt \
  --option version=0.15

The translate command will takes a list of YAML registry file paths and an output path and parse the given YAML registry files into QML JavaScript files.

The generated folder will be a QML module. Make sure wherever the generated module is placed is also part of the QML Import Path.

Notice that when building for Qt/QML it is mandatory to give the translate command two extra options.

--option platform=qt

This option is what changes the output file from standard JavaScript to QML JavaScript.

--option version=<version>

The version passed to this option will be the version of the generated QML module.

Automation steps

Documentation

Prefer using the Glean Dictionary

While it is still possible to generate Markdown documentation, if working on a public Mozilla project rely on the Glean Dictionary for documentation. Your product will be automatically indexed by the Glean Dictionary after it gets enabled in the pipeline.

One of the commands provided by glean_parser allows users to generate Markdown documentation based on the contents of their YAML registry files. To perform that translation, use the translate command with a different output format, as shown below.

glean_parser translate path/to/metrics.yaml path/to/pings.yaml \
  -f markdown \
  -o path/to/docs

YAML registry files linting

glean_parser includes a "linter" for the YAML registry files called the glinter that catches a number of common mistakes in these files. To run the linter use the glinter command.

glean_parser glinter path/to/metrics.yaml path/to/pings.yaml

Debugging

By default, the Glean.js QML module uses a minified version of the Glean.js library. It may be useful to use the unminified version of the library in order to get proper line numbers and function names when debugging crashes.

The bundle provided contains the unminified version of the library. In order to use it, open the glean.js file inside the included module and change the line:

.import "glean.lib.js" as Glean

to

.import "glean.dev.js" as Glean

Troubleshooting

submitPing may cause crashes when debugging iOS devices

The submitPing function hits a known bug in the Qt JavaScript interpreter.

This bug is only reproduced in iOS devices, it does not happen in emulators. It also only happens when using the Qt debug library for iOS.

There is no way around this bug other than avoiding the Qt debug library for iOS altogether until it is fixed. Refer to the the Qt debugging documentation on how to do that.

Integrating Glean for product managers

This chapter provides guidance for planning the work involved in integrating Glean into your product, for internal Mozilla customers. For a technical coding perspective, see adding Glean to your project.

Glean is the standard telemetry platform required for all new Mozilla products. While there are some upfront costs to integrating Glean in your product, this pays off in easier long-term maintenance and a rich set of self-serve analysis tools. The Glean SDK team is happy to support your telemetry integration and make it successful. Find us in #glean or email glean-team@mozilla.com.

Building a telemetry plan

The Glean SDK provides support for answering basic product questions out-of-the-box, such as daily active users, product version and platform information.
However, it is also a good idea to have a sense of any additional product-specific questions you are trying to answer with telemetry, and, when possible, in collaboration with a data scientist.
This of course helps for your own planning, but is also invaluable for the Glean SDK team to support you, since we will understand the ultimate goals of your product's telemetry and ensure the design will meet those goals and we can identify any new features that may be required. It is best to frame this document in the form of questions and use cases rather than as specific data points and schemas.

Integrating the Glean SDK into your product

The technical steps for integrating the Glean SDK in your product are documented in its own chapter for supported platforms. We recommend having a member of the Glean SDK team review this integration to catch any potential pitfalls.

(Optional) Adapting Glean to your platform

The Glean SDK is a collection of cross platform libraries and tools that facilitate collection of Glean conforming telemetry from applications.
Consult the list of the currently supported platforms and languages. If your product's tech stack isn't currently supported, please reach out to the Glean team: significant work will be required to create a new integration.
In previous efforts, this has ranged from 1 to 3 months FTE of work, so it is important to plan for this work well in advance. While the first phase of this work generally requires the specialized expertise of the Glean SDK team, the second half can benefit from outside developers to move faster.

(Optional) Designing ping submission

The Glean SDK periodically sends telemetry to our servers in a bundle known as a "ping".
For mobile applications with common interaction models, such as web browsers, the Glean SDK provides basic pings out-of-the-box. For other kinds of products, it may be necessary to carefully design what triggers the submission of a ping. It is important to have a solid telemetry plan (see above) so we can make sure the ping submission will be able to answer the telemetry questions required of the product.

(Optional) New metric types

The Glean SDK has a number of different metric types that it can collect.
Metric types provide "guardrails" to make sure that telemetry is being collected correctly, and to present the data at analysis time more automatically. Occasionally, products need to collect data that doesn't fit neatly into one of the available metric types. Glean has a process to request and introduce more metric types and we will work with you to design something appropriate. This design and implementation work is at least 4 weeks, though we are working on the foundation to accelerate that. Having a telemetry plan (see above) will help to identify this work early.

Adding new metrics

Table of Contents

Process overview

When adding a new metric, the process is:

  • Consider the question you are trying to answer with this data, and choose the metric type and parameters to use.
  • Add a new entry to metrics.yaml.
  • Add code to your project to record into the metric by calling the Glean SDK.

Important: Any new data collection requires documentation and data-review. This is also required for any new metric automatically collected by the Glean SDK.

Choosing a metric type

The following is a set of questions to ask about the data being collected to help better determine which metric type to use.

Is it a single measurement?

If the value is true or false, use a boolean metric.

If the value is a string, use a string metric. For example, to record the name of the default search engine.

Beware: string metrics are exceedingly general, and you are probably best served by selecting the most specific metric for the job, since you'll get better error checking and richer analysis tools for free. For example, avoid storing a number in a string metric --- you probably want a counter metric instead.

If you need to store multiple string values in a metric, use a string list metric. For example, you may want to record the list of other Mozilla products installed on the device.

For all of the metric types in this section that measure single values, it is especially important to consider how the lifetime of the value relates to the ping it is being sent in. Since these metrics don't perform any aggregation on the client side, when a ping containing the metric is submitted, it will contain only the "last known" value for the metric, potentially resulting in data loss. There is further discussion of metric lifetimes below.

Are you measuring user behavior?

For tracking user behavior, it is usually meaningful to know the over of events that lead to the use of a feature. Therefore, for user behavior, an event metric is usually the best choice.

Be aware, however, that events can be particularly expensive to transmit, store and analyze, so should not be used for higher-frequency measurements.

Are you counting things?

If you want to know how many times something happened, use a counter metric. If you are counting a group of related things, or you don't know what all of the things to count are at build time, use a labeled counter metric.

If you need to know how many times something happened relative to the number of times something else happened, use a rate metric.

If you need to know when the things being counted happened relative to other things, consider using an event.

Are you measuring time?

If you need to record an absolute time, use a datetime metric. Datetimes are recorded in the user's local time, according to their device's real time clock, along with a timezone offset from UTC. Datetime metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question.

If you need to record how long something takes you have a few options.

If you need to measure the total time spent doing a particular task, look to the timespan metric. Timespan metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question. Note that this metric should only be used to measure time on a single thread. If multiple overlapping timespans are measured for the same metric, an invalid state error is recorded.

If you need to measure the relative occurrences of many timings, use a timing distribution. It builds a histogram of timing measurements, and is safe to record multiple concurrent timespans on different threads.

If you need to know the time between multiple distinct actions that aren't a simple "begin" and "end" pair, consider using an event.

For how long do you need to collect this data?

Think carefully about how long the metric will be needed, and set the expires parameter to disable the metric at the earliest possible time. This is an important component of Mozilla's lean data practices.

When the metric passes its expiration date (determined at build time), it will automatically stop collecting data.

When a metric's expiration is within in 14 days, emails will be sent from telemetry-alerts@mozilla.com to the notification_emails addresses associated with the metric. At that time, the metric should be removed, which involves removing it from the metrics.yaml file and removing uses of it in the source code. Removing a metric does not affect the availability of data already collected by the pipeline.

If the metric is still needed after its expiration date, it should go back for another round of data review to have its expiration date extended.

Important: Ensure that telemetry alerts are received and are reviewed in a timely manner. Expired metrics don't record any data, extending or removing a metric should be done in time. Consider adding both a group email address and an individual who is responsible for this metric to the notification_emails list.

When should the Glean SDK automatically clear the measurement?

The lifetime parameter of a metric defines when its value will be cleared. There are three lifetime options available:

ping (default)

The metric is cleared each time it is submitted in the ping. This is the most common case, and should be used for metrics that are highly dynamic, such as things computed in response to the user's interaction with the application.

application

The metric is related to an application run, and is cleared after the application restarts and any Glean-owned ping, due at startup, is submitted. This should be used for things that are constant during the run of an application, such as the operating system version. In practice, these metrics are generally set during application startup. A common mistake--- using the ping lifetime for these type of metrics---means that they will only be included in the first ping sent during a particular run of the application.

user

Reach out to the Glean team before using this.

The metric is part of the user's profile and will live as long as the profile lives. This is often not the best choice unless the metric records a value that really needs to be persisted for the full lifetime of the user profile, e.g. an identifier like the client_id, the day the product was first executed. It is rare to use this lifetime outside of some metrics that are built in to the Glean SDK.

While lifetimes are important to understand for all metric types, they are particularly important for the metric types that record single values and don't aggregate on the client (boolean, string, labeled_string, string_list, datetime and uuid), since these metrics will send the "last known" value and missing the earlier values could be a form of unintended data loss.

A lifetime example

Let's work through an example to see how these lifetimes play out in practice. Let's suppose we have a user preference, "turbo mode", which defaults to false, but the user can turn it to true at any time. We want to know when this flag is true so we can measure its affect on other metrics in the same ping. In the following diagram, we look at a time period that sends 4 pings across two separate runs of the application. We assume here, that like the Glean SDK's built-in metrics ping, the developer writing the metric isn't in control of when the ping is submitted.

In this diagram, the ping measurement windows are represented as rectangles, but the moment the ping is "submitted" is represented by its right edge. The user changes the "turbo mode" setting from false to true in the first run, and then toggles it again twice in the second run.

Metric lifetime timeline

  • A. Ping lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. It is included in the first ping after being recorded (Ping 2), which causes it to be cleared.

  • B. Ping lifetime, set on init and change: The default value is included in Ping 1, and the changed value is included in Ping 2, which causes it to be cleared. It therefore misses Ping 3, but when the application is started, it is recorded again and it is included in Ping 4. However, this causes it to be cleared again and it is not in Ping 5.

  • C. Application lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. After the value is changed, it is included in Pings 2 and 3, but then due to application restart it is cleared, so it is not included until the value is manually toggled again.

  • D. Application, set on init and change: The default value is included in Ping 1, and the changed value is included in Pings 2 and 3. Even though the application startup causes it to be cleared, it is set again, and all subsequent pings also have the value.

  • E. User, set on change: The default value is missing from Ping 1, but since user lifetime metrics aren't cleared unless the user profile is reset (e.g. on Android, when the product is uninstalled), it is included in all subsequent pings.

  • F. User, set on init and change: Since user lifetime metrics aren't cleared unless the user profile is reset, it is included in all subsequent pings. This would be true even if the "turbo mode" preference were never changed again.

Note that for all of the metric configurations, the toggle of the preference off and on during Ping 4 is completely missed. If you need to create a ping containing one, and only one, value for this metric, consider using a custom ping to create a ping whose lifetime matches the lifetime of the value.

What if none of these lifetimes are appropriate?

If the timing at which the metric is sent in the ping needs to closely match the timing of the metrics value, the best option is to use a custom ping to manually control when pings are sent.

This is especially useful when metrics need to be tightly related to one another, for example when you need to measure the distribution of frame paint times when a particular rendering backend is in use. If these metrics were in different pings, with different measurement windows, it is much harder to do that kind of reasoning with much certainty.

What should this new metric be called?

Metric names have a maximum length of 30 characters.

Reuse names from other applications

There's a lot of value using the same name for analogous metrics collected across different products. For example, BigQuery makes it simple to join columns with the same name across multiple tables. Therefore, we encourage you to investigate if a similar metric is already being collected by another product. If it is, there may be an opportunity for code reuse across these products, and if all the projects are using the Glean SDK, it's easy for libraries to send their own metrics. If sharing the code doesn't make sense, at a minimum we recommend using the same metric name for similar actions and concepts whenever possible.

Make names unique within an application

Metric identifiers (the combination of a metric's category and name) must be unique across all metrics that are sent by a single application. This includes not only the metrics defined in the app's metrics.yaml, but the metrics.yaml of any Glean SDK-using library that the application uses, including the Glean SDK itself. Therefore, care should be taken to name things specifically enough so as to avoid namespace collisions. In practice, this generally involves thinking carefully about the category of the metric, more than the name.

Note: Duplicate metric identifiers are not currently detected at build time. See bug 1578383 for progress on that. However, the probe_scraper process, which runs nightly, will detect duplicate metrics and e-mail the notification_emails associated with the given metrics.

Be as specific as possible

More broadly, you should choose the names of metrics to be as specific as possible. It is not necessary to put the type of the metric in the category or name, since this information is retained in other ways through the entire end-to-end system.

For example, if defining a set of events related to search, put them in a category called search, rather than just events or search_events. The events word here would be redundant.

What if none of these metric types is the right fit?

The current set of metrics the Glean SDK supports is based on known common use cases, but new use cases are discovered all the time.

Please reach out to us on #glean:mozilla.org. If you think you need a new metric type, we have a process for that.

How do I make sure my metric is working?

The Glean SDK has rich support for writing unit tests involving metrics. Writing a good unit test is a large topic, but in general, you should write unit tests for all new telemetry that does the following:

  • Performs the operation being measured.

  • Asserts that metrics contain the expected data, using the testGetValue API on the metric.

  • Where applicable, asserts that no errors are recorded, such as when values are out of range, using the testGetNumRecordedErrors API.

In addition to unit tests, it is good practice to validate the incoming data for the new metric on a pre-release channel to make sure things are working as expected.

Adding the metric to the metrics.yaml file

The metrics.yaml file defines the metrics your application or library will send. They are organized into categories. The overall organization is:

# Required to indicate this is a `metrics.yaml` file
$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0

toolbar:
  click:
    type: event
    description: |
      Event to record toolbar clicks.
    notification_emails:
      - CHANGE-ME@example.com
    bugs:
      - https://bugzilla.mozilla.org/123456789/
    data_reviews:
      - http://example.com/path/to/data-review
    expires: 2019-06-01  # <-- Update to a date in the future

  double_click:
    ...

Refer to the metrics YAML registry format for a full reference on the metrics.yaml file structure.

Using the metric from your code

The reference documentation for each metric type goes into detail about using each metric type from your code.

Note that all Glean metrics are write-only. Outside of unit tests, it is impossible to retrieve a value from the Glean SDK's database. While this may seem limiting, this is required to:

  • enforce the semantics of certain metric types (e.g. that Counters can only be incremented).
  • ensure the lifetime of the metric (when it is cleared or reset) is correctly handled.

Capitalization

One thing to note is that we try to adhere to the coding conventions of each language wherever possible, so the metric name and category in the metrics.yaml (which is in snake_case) may be changed to some other case convention, such as camelCase, when used from code.

Event extras and labels are never capitalized, no matter the target language.

Category and metric names in the metrics.yaml are in snake_case, but given the Kotlin coding standards defined by ktlint, these identifiers must be camelCase in Kotlin. For example, the metric defined in the metrics.yaml as:

views:
  login_opened:
    ...

is accessible in Kotlin as:

import org.mozilla.yourApplication.GleanMetrics.Views
GleanMetrics.Views.loginOpened...

Category and metric names in the metrics.yaml are in snake_case, but given the Swift coding standards defined by swiftlint, these identifiers must be camelCase in Swift. For example, the metric defined in the metrics.yaml as:

views:
  login_opened:
    ...

is accessible in Kotlin as:

GleanMetrics.Views.loginOpened...

Category and metric names in the metrics.yaml are in snake_case, which matches the PEP8 standard, so no translation is needed for Python.

Given the Rust coding standards defined by clippy, identifiers should all be snake_case. This includes category names which in the metrics.yaml are dotted.snake_case:

compound.category:
  metric_name:
    ...

In Rust this becomes:

use fog::metrics;

metrics::compound_category::metric_name...

JavaScript identifiers are customarily camelCase. This requires transforming a metric defined in the metrics.yaml as:

compound.category:
  metric_name:
    ...

to a form useful in JS as:

import * as compoundCategory from "./path/to/generated/files/compoundCategory.js";

compoundCategory.metricName...

Firefox Desktop has Coding Style Guidelines for both C++ and JS. This results in, for a metric defined in the metrics.yaml as:

compound.category:
  metric_name:
    ...

an identifier that looks like:

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::compound_category::metric_name...

JavaScript

Glean.compoundCategory.metricName...

Adding new metrics

Table of Contents

Process overview

When adding a new metric, the process is:

  • Consider the question you are trying to answer with this data, and choose the metric type and parameters to use.
  • Add a new entry to metrics.yaml.
  • Add code to your project to record into the metric by calling the Glean SDK.

Important: Any new data collection requires documentation and data-review. This is also required for any new metric automatically collected by the Glean SDK.

Choosing a metric type

The following is a set of questions to ask about the data being collected to help better determine which metric type to use.

Is it a single measurement?

If the value is true or false, use a boolean metric.

If the value is a string, use a string metric. For example, to record the name of the default search engine.

Beware: string metrics are exceedingly general, and you are probably best served by selecting the most specific metric for the job, since you'll get better error checking and richer analysis tools for free. For example, avoid storing a number in a string metric --- you probably want a counter metric instead.

If you need to store multiple string values in a metric, use a string list metric. For example, you may want to record the list of other Mozilla products installed on the device.

For all of the metric types in this section that measure single values, it is especially important to consider how the lifetime of the value relates to the ping it is being sent in. Since these metrics don't perform any aggregation on the client side, when a ping containing the metric is submitted, it will contain only the "last known" value for the metric, potentially resulting in data loss. There is further discussion of metric lifetimes below.

Are you measuring user behavior?

For tracking user behavior, it is usually meaningful to know the over of events that lead to the use of a feature. Therefore, for user behavior, an event metric is usually the best choice.

Be aware, however, that events can be particularly expensive to transmit, store and analyze, so should not be used for higher-frequency measurements.

Are you counting things?

If you want to know how many times something happened, use a counter metric. If you are counting a group of related things, or you don't know what all of the things to count are at build time, use a labeled counter metric.

If you need to know how many times something happened relative to the number of times something else happened, use a rate metric.

If you need to know when the things being counted happened relative to other things, consider using an event.

Are you measuring time?

If you need to record an absolute time, use a datetime metric. Datetimes are recorded in the user's local time, according to their device's real time clock, along with a timezone offset from UTC. Datetime metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question.

If you need to record how long something takes you have a few options.

If you need to measure the total time spent doing a particular task, look to the timespan metric. Timespan metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question. Note that this metric should only be used to measure time on a single thread. If multiple overlapping timespans are measured for the same metric, an invalid state error is recorded.

If you need to measure the relative occurrences of many timings, use a timing distribution. It builds a histogram of timing measurements, and is safe to record multiple concurrent timespans on different threads.

If you need to know the time between multiple distinct actions that aren't a simple "begin" and "end" pair, consider using an event.

For how long do you need to collect this data?

Think carefully about how long the metric will be needed, and set the expires parameter to disable the metric at the earliest possible time. This is an important component of Mozilla's lean data practices.

When the metric passes its expiration date (determined at build time), it will automatically stop collecting data.

When a metric's expiration is within in 14 days, emails will be sent from telemetry-alerts@mozilla.com to the notification_emails addresses associated with the metric. At that time, the metric should be removed, which involves removing it from the metrics.yaml file and removing uses of it in the source code. Removing a metric does not affect the availability of data already collected by the pipeline.

If the metric is still needed after its expiration date, it should go back for another round of data review to have its expiration date extended.

Important: Ensure that telemetry alerts are received and are reviewed in a timely manner. Expired metrics don't record any data, extending or removing a metric should be done in time. Consider adding both a group email address and an individual who is responsible for this metric to the notification_emails list.

When should the Glean SDK automatically clear the measurement?

The lifetime parameter of a metric defines when its value will be cleared. There are three lifetime options available:

ping (default)

The metric is cleared each time it is submitted in the ping. This is the most common case, and should be used for metrics that are highly dynamic, such as things computed in response to the user's interaction with the application.

application

The metric is related to an application run, and is cleared after the application restarts and any Glean-owned ping, due at startup, is submitted. This should be used for things that are constant during the run of an application, such as the operating system version. In practice, these metrics are generally set during application startup. A common mistake--- using the ping lifetime for these type of metrics---means that they will only be included in the first ping sent during a particular run of the application.

user

Reach out to the Glean team before using this.

The metric is part of the user's profile and will live as long as the profile lives. This is often not the best choice unless the metric records a value that really needs to be persisted for the full lifetime of the user profile, e.g. an identifier like the client_id, the day the product was first executed. It is rare to use this lifetime outside of some metrics that are built in to the Glean SDK.

While lifetimes are important to understand for all metric types, they are particularly important for the metric types that record single values and don't aggregate on the client (boolean, string, labeled_string, string_list, datetime and uuid), since these metrics will send the "last known" value and missing the earlier values could be a form of unintended data loss.

A lifetime example

Let's work through an example to see how these lifetimes play out in practice. Let's suppose we have a user preference, "turbo mode", which defaults to false, but the user can turn it to true at any time. We want to know when this flag is true so we can measure its affect on other metrics in the same ping. In the following diagram, we look at a time period that sends 4 pings across two separate runs of the application. We assume here, that like the Glean SDK's built-in metrics ping, the developer writing the metric isn't in control of when the ping is submitted.

In this diagram, the ping measurement windows are represented as rectangles, but the moment the ping is "submitted" is represented by its right edge. The user changes the "turbo mode" setting from false to true in the first run, and then toggles it again twice in the second run.

Metric lifetime timeline

  • A. Ping lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. It is included in the first ping after being recorded (Ping 2), which causes it to be cleared.

  • B. Ping lifetime, set on init and change: The default value is included in Ping 1, and the changed value is included in Ping 2, which causes it to be cleared. It therefore misses Ping 3, but when the application is started, it is recorded again and it is included in Ping 4. However, this causes it to be cleared again and it is not in Ping 5.

  • C. Application lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. After the value is changed, it is included in Pings 2 and 3, but then due to application restart it is cleared, so it is not included until the value is manually toggled again.

  • D. Application, set on init and change: The default value is included in Ping 1, and the changed value is included in Pings 2 and 3. Even though the application startup causes it to be cleared, it is set again, and all subsequent pings also have the value.

  • E. User, set on change: The default value is missing from Ping 1, but since user lifetime metrics aren't cleared unless the user profile is reset (e.g. on Android, when the product is uninstalled), it is included in all subsequent pings.

  • F. User, set on init and change: Since user lifetime metrics aren't cleared unless the user profile is reset, it is included in all subsequent pings. This would be true even if the "turbo mode" preference were never changed again.

Note that for all of the metric configurations, the toggle of the preference off and on during Ping 4 is completely missed. If you need to create a ping containing one, and only one, value for this metric, consider using a custom ping to create a ping whose lifetime matches the lifetime of the value.

What if none of these lifetimes are appropriate?

If the timing at which the metric is sent in the ping needs to closely match the timing of the metrics value, the best option is to use a custom ping to manually control when pings are sent.

This is especially useful when metrics need to be tightly related to one another, for example when you need to measure the distribution of frame paint times when a particular rendering backend is in use. If these metrics were in different pings, with different measurement windows, it is much harder to do that kind of reasoning with much certainty.

What should this new metric be called?

Metric names have a maximum length of 30 characters.

Reuse names from other applications

There's a lot of value using the same name for analogous metrics collected across different products. For example, BigQuery makes it simple to join columns with the same name across multiple tables. Therefore, we encourage you to investigate if a similar metric is already being collected by another product. If it is, there may be an opportunity for code reuse across these products, and if all the projects are using the Glean SDK, it's easy for libraries to send their own metrics. If sharing the code doesn't make sense, at a minimum we recommend using the same metric name for similar actions and concepts whenever possible.

Make names unique within an application

Metric identifiers (the combination of a metric's category and name) must be unique across all metrics that are sent by a single application. This includes not only the metrics defined in the app's metrics.yaml, but the metrics.yaml of any Glean SDK-using library that the application uses, including the Glean SDK itself. Therefore, care should be taken to name things specifically enough so as to avoid namespace collisions. In practice, this generally involves thinking carefully about the category of the metric, more than the name.

Note: Duplicate metric identifiers are not currently detected at build time. See bug 1578383 for progress on that. However, the probe_scraper process, which runs nightly, will detect duplicate metrics and e-mail the notification_emails associated with the given metrics.

Be as specific as possible

More broadly, you should choose the names of metrics to be as specific as possible. It is not necessary to put the type of the metric in the category or name, since this information is retained in other ways through the entire end-to-end system.

For example, if defining a set of events related to search, put them in a category called search, rather than just events or search_events. The events word here would be redundant.

What if none of these metric types is the right fit?

The current set of metrics the Glean SDK supports is based on known common use cases, but new use cases are discovered all the time.

Please reach out to us on #glean:mozilla.org. If you think you need a new metric type, we have a process for that.

How do I make sure my metric is working?

The Glean SDK has rich support for writing unit tests involving metrics. Writing a good unit test is a large topic, but in general, you should write unit tests for all new telemetry that does the following:

  • Performs the operation being measured.

  • Asserts that metrics contain the expected data, using the testGetValue API on the metric.

  • Where applicable, asserts that no errors are recorded, such as when values are out of range, using the testGetNumRecordedErrors API.

In addition to unit tests, it is good practice to validate the incoming data for the new metric on a pre-release channel to make sure things are working as expected.

Adding the metric to the metrics.yaml file

The metrics.yaml file defines the metrics your application or library will send. They are organized into categories. The overall organization is:

# Required to indicate this is a `metrics.yaml` file
$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0

toolbar:
  click:
    type: event
    description: |
      Event to record toolbar clicks.
    notification_emails:
      - CHANGE-ME@example.com
    bugs:
      - https://bugzilla.mozilla.org/123456789/
    data_reviews:
      - http://example.com/path/to/data-review
    expires: 2019-06-01  # <-- Update to a date in the future

  double_click:
    ...

Refer to the metrics YAML registry format for a full reference on the metrics.yaml file structure.

Using the metric from your code

The reference documentation for each metric type goes into detail about using each metric type from your code.

Note that all Glean metrics are write-only. Outside of unit tests, it is impossible to retrieve a value from the Glean SDK's database. While this may seem limiting, this is required to:

  • enforce the semantics of certain metric types (e.g. that Counters can only be incremented).
  • ensure the lifetime of the metric (when it is cleared or reset) is correctly handled.

Capitalization

One thing to note is that we try to adhere to the coding conventions of each language wherever possible, so the metric name and category in the metrics.yaml (which is in snake_case) may be changed to some other case convention, such as camelCase, when used from code.

Event extras and labels are never capitalized, no matter the target language.

Category and metric names in the metrics.yaml are in snake_case, but given the Kotlin coding standards defined by ktlint, these identifiers must be camelCase in Kotlin. For example, the metric defined in the metrics.yaml as:

views:
  login_opened:
    ...

is accessible in Kotlin as:

import org.mozilla.yourApplication.GleanMetrics.Views
GleanMetrics.Views.loginOpened...

Category and metric names in the metrics.yaml are in snake_case, but given the Swift coding standards defined by swiftlint, these identifiers must be camelCase in Swift. For example, the metric defined in the metrics.yaml as:

views:
  login_opened:
    ...

is accessible in Kotlin as:

GleanMetrics.Views.loginOpened...

Category and metric names in the metrics.yaml are in snake_case, which matches the PEP8 standard, so no translation is needed for Python.

Given the Rust coding standards defined by clippy, identifiers should all be snake_case. This includes category names which in the metrics.yaml are dotted.snake_case:

compound.category:
  metric_name:
    ...

In Rust this becomes:

use fog::metrics;

metrics::compound_category::metric_name...

JavaScript identifiers are customarily camelCase. This requires transforming a metric defined in the metrics.yaml as:

compound.category:
  metric_name:
    ...

to a form useful in JS as:

import * as compoundCategory from "./path/to/generated/files/compoundCategory.js";

compoundCategory.metricName...

Firefox Desktop has Coding Style Guidelines for both C++ and JS. This results in, for a metric defined in the metrics.yaml as:

compound.category:
  metric_name:
    ...

an identifier that looks like:

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::compound_category::metric_name...

JavaScript

Glean.compoundCategory.metricName...

Unit testing Glean metrics

In order to support unit testing inside of client applications using the Glean SDK, a set of testing API functions have been included. The intent is to make the Glean SDK easier to test 'out of the box' in any client application it may be used in. These functions expose a way to inspect and validate recorded metric values within the client application but are restricted to test code only through visibility annotations (@VisibleForTesting(otherwise = VisibleForTesting.NONE) for Kotlin, internal methods for Swift). (Outside of a testing context, Glean APIs are otherwise write-only so that it can enforce semantics and constraints about data).

To encourage using the testing API, it is also possible to generate testing coverage reports to show which metrics in your project are tested.

General test API method semantics

Using the Glean SDK's unit testing API requires adding Robolectric 4.0 or later as a testing dependency. In Gradle, this can be done by declaring a testImplementation dependency:

dependencies {
    testImplementation "org.robolectric:robolectric:4.3.1"
}

In order to prevent issues with async calls when unit testing the Glean SDK, it is important to put the Glean SDK into testing mode by applying the JUnit GleanTestRule to your test class. When the Glean SDK is in testing mode, it enables uploading and clears the recorded metrics at the beginning of each test run. The rule can be used as shown below:

@RunWith(AndroidJUnit4::class)
class ActivityCollectingDataTest {
    // Apply the GleanTestRule to set up a disposable Glean instance.
    // Please note that this clears the Glean data across tests.
    @get:Rule
    val gleanRule = GleanTestRule(ApplicationProvider.getApplicationContext())

    @Test
    fun checkCollectedData() {
      // The Glean SDK testing API can be called here.
    }
}

This will ensure that metrics are done recording when the other test functions are used.

To check if a value exists (i.e. it has been recorded), there is a testHasValue() function on each of the metric instances:

assertTrue(GleanMetrics.Search.defaultSearchEngineUrl.testHasValue())

To check the actual values, there is a testGetValue() function on each of the metric instances. It is important to check that the values are recorded as expected, since many of the metric types may truncate or error-correct the value. This function will return a datatype appropriate to the specific type of the metric it is being used with:

assertEquals("https://example.com/search?", GleanMetrics.Search.defaultSearchEngineUrl.testGetValue())

Note that each of these functions has its visibility limited to the scope of unit tests by making use of the @VisibleForTesting annotation, so the IDE should complain if you attempt to use them inside of client code.

NOTE: There's no automatic test rule for Glean tests implemented.

In order to prevent issues with async calls when unit testing the Glean SDK, it is important to put the Glean SDK into testing mode. When the Glean SDK is in testing mode, it enables uploading and clears the recorded metrics at the beginning of each test run.

Activate it by resetting Glean in your test's setup:

@testable import Glean
import XCTest

class GleanUsageTests: XCTestCase {
    override func setUp() {
        Glean.shared.resetGlean(clearStores: true)
    }

    // ...
}

This will ensure that metrics are done recording when the other test functions are used.

To check if a value exists (i.e. it has been recorded), there is a testHasValue() function on each of the metric instances:

XCTAssertTrue(GleanMetrics.Search.defaultSearchEngineUrl.testHasValue())

To check the actual values, there is a testGetValue() function on each of the metric instances. It is important to check that the values are recorded as expected, since many of the metric types may truncate or error-correct the value. This function will return a datatype appropriate to the specific type of the metric it is being used with:

XCTAssertEqual("https://example.com/search?", try GleanMetrics.Search.defaultSearchEngineUrl.testGetValue())

Note that each of these functions is marked as internal, you need to import Glean explicitly in test mode:

@testable import Glean

It is generally a good practice to "reset" the Glean SDK prior to every unit test that uses the Glean SDK, to prevent side effects of one unit test impacting others. The Glean SDK contains a helper function glean.testing.reset_glean() for this purpose. It has two required arguments: the application ID, and the application version. Each reset of the Glean SDK will create a new temporary directory for Glean to store its data in. This temporary directory is automatically cleaned up the next time the Glean SDK is reset or when the testing framework finishes.

The instructions below assume you are using pytest as the test runner. Other test-running libraries have similar features, but are different in the details.

Create a file conftest.py at the root of your test directory, and add the following to reset Glean at the start of every test in your suite:

import pytest
from glean import testing

@pytest.fixture(name="reset_glean", scope="function", autouse=True)
def fixture_reset_glean():
    testing.reset_glean(application_id="my-app-id", application_version="0.1.0")

To check if a value exists (i.e. it has been recorded), there is a test_has_value() function on each of the metric instances:

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# ...

assert metrics.search.search_engine_url.test_has_value()

To check the actual values, there is a test_get_value() function on each of the metric instances. It is important to check that the values are recorded as expected, since many of the metric types may truncate or error-correct the value. This function will return a datatype appropriate to the specific type of the metric it is being used with:

assert (
    "https://example.com/search?" ==
    metrics.search.default_search_engine_url.test_get_value()
)

TODO. To be implemented in bug 1648448.

Testing metrics for custom pings

In order to test metrics where the metric is included in more than one ping, the test functions take an optional pingName argument (ping_name in Python). This is the name of the ping that the metric is being sent in, such as "events" for the events ping, or "metrics" for the metrics ping. This could also be a custom ping name that the metric is being sent in. In most cases you should not have to supply the ping name to the test function and can just use the default which is the "default" ping that this metric is sent in. You should only need to provide a pingName if the metric is being sent in more than one ping in order to identify the correct metric store.

You can call the testHasValue() and testGetValue() functions with pingName like this:

GleanMetrics.Foo.uriCount.testHasValue("customPing")
GleanMetrics.Foo.uriCount.testGetValue("customPing")

Example of using the test API

Here is a longer example to better illustrate the intended use of the test API:

// Record a metric value with extra to validate against
GleanMetrics.BrowserEngagement.click.record(
    mapOf(
        BrowserEngagement.clickKeys.font to "Courier"
    )
)

// Record more events without extras attached
BrowserEngagement.click.record()
BrowserEngagement.click.record()

// Check if we collected any events into the 'click' metric
assertTrue(BrowserEngagement.click.testHasValue())

// Retrieve a snapshot of the recorded events
val events = BrowserEngagement.click.testGetValue()

// Check if we collected all 3 events in the snapshot
assertEquals(3, events.size)

// Check extra key/value for first event in the list
assertEquals("Courier", events.elementAt(0).extra["font"])

Here is a longer example to better illustrate the intended use of the test API:

// Record a metric value with extra to validate against
GleanMetrics.BrowserEngagement.click.record([.font: "Courier"])

// Record more events without extras attached
BrowserEngagement.click.record()
BrowserEngagement.click.record()

// Check if we collected any events into the 'click' metric
XCTAssertTrue(BrowserEngagement.click.testHasValue())

// Retrieve a snapshot of the recorded events
let events = try! BrowserEngagement.click.testGetValue()

// Check if we collected all 3 events in the snapshot
XCTAssertEqual(3, events.count)

// Check extra key/value for first event in the list
XCTAssertEqual("Courier", events[0].extra?["font"])

Here is a longer example to better illustrate the intended use of the test API:

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Record a metric value with extra to validate against
metrics.url.visit.add(1)

# Check if we collected any events into the 'click' metric
assert metrics.url.visit.test_has_value()

# Retrieve a snapshot of the recorded events
assert 1 == metrics.url.visit.test_get_value()

TODO. To be implemented in bug 1648448.

Generating testing coverage reports

Glean can generate coverage reports to track which metrics are tested in your unit test suite.

There are three steps to integrate it into your continuous integration workflow: recording coverage, post-processing the results, and uploading the results.

Recording coverage

Glean testing coverage is enabled by setting the GLEAN_TEST_COVERAGE environment variable to the name of a file to store results. It is good practice to set it to the absolute path to a file, since some testing harnesses (such as cargo test) may change the current working directory.

GLEAN_TEST_COVERAGE=$(realpath glean_coverage.txt) make test

Post-processing the results

A post-processing step is required to convert the raw output in the file specified by GLEAN_TEST_COVERAGE into usable output for coverage reporting tools. Currently, the only coverage reporting tool supported is codecov.io.

This post-processor is available in the coverage subcommand in the glean_parser tool.

For some build systems, glean_parser is already installed for you by the build system integration at the following locations:

  • On Android/Gradle, $GRADLE_HOME/glean/bootstrap-4.5.11/Miniconda3/bin/glean_parser
  • On iOS/Carthage, $PROJECT_ROOT/.venv/bin/glean_parser
  • For other systems, install glean_parser using pip install glean_parser

The glean_parser coverage command requires the following parameters:

  • -f: The output format to produce, for example codecovio to produce codecov.io's custom format.
  • -o: The path to the output file, for example codecov.json.
  • -c: The input raw coverage file. glean_coverage.txt in the example above.
  • A list of the metrics.yaml files in your repository.

For example, to produce output for codecov.io:

glean_parser coverage -f codecovio -o glean_coverage.json -c glean_coverage.txt app/metrics.yaml

In this example, the glean_coverage.json file is now ready for uploading to codecov.io.

Uploading coverage

If using codecov.io, the uploader doesn't send coverage results for YAML files by default. Pass the -X yaml option to the uploader to make sure they are included:

bash <(curl -s https://codecov.io/bash) -X yaml

Error reporting

The Glean SDK records the number of errors that occur when metrics are passed invalid data or are otherwise used incorrectly. This information is reported back in special labeled counter metrics in the glean.error category. Error metrics are included in the same pings as the metric that caused the error. Additionally, error metrics are always sent in the metrics ping ping.

The following categories of errors are recorded:

  • invalid_value: The metric value was invalid.
  • invalid_label: The label on a labeled metric was invalid.
  • invalid_state: The metric caught an invalid state while recording.
  • invalid_overflow: The metric value to be recorded overflows the metric-specific upper range.

For example, if you had a string metric and passed it a string that was too long:

MyMetrics.stringMetric.set("this_string_is_longer_than_the_limit_for_string_metrics")

The following error metric counter would be incremented:

Glean.error.invalidOverflow["my_metrics.string_metric"].add(1)

Resulting in the following keys in the ping:

{
  "metrics": {
    "labeled_counter": {
      "glean.error.invalid_overflow": {
        "my_metrics.string_metric": 1
      }
    }
  }
}

If you have a debug build of the Glean SDK, details about the errors being recorded are included in the logs. This detailed information is not included in Glean pings.

The Glean JavaScript SDK provides a slightly different set of metrics and pings

If you are looking for the metrics collected by Glean.js, refer to the documentation over on the @mozilla/glean.js repository.

Metrics

This document enumerates the metrics collected by this project using the Glean SDK. This project may depend on other projects which also collect metrics. This means you might have to go searching through the dependency tree to get a full picture of everything collected by this project.

Pings

all-pings

These metrics are sent in every ping.

All Glean pings contain built-in metrics in the ping_info and client_info sections.

In addition to those built-in metrics, the following metrics are added to the ping:

NameTypeDescriptionData reviewsExtrasExpirationData Sensitivity
glean.error.invalid_labellabeled_counterCounts the number of times a metric was set with an invalid label. The labels are the category.name identifier of the metric.Bug 1499761never1
glean.error.invalid_overflowlabeled_counterCounts the number of times a metric was set a value that overflowed. The labels are the category.name identifier of the metric.Bug 1591912never1
glean.error.invalid_statelabeled_counterCounts the number of times a timing metric was used incorrectly. The labels are the category.name identifier of the metric.Bug 1499761never1
glean.error.invalid_valuelabeled_counterCounts the number of times a metric was set to an invalid value. The labels are the category.name identifier of the metric.Bug 1499761never1

baseline

This is a built-in ping that is assembled out of the box by the Glean SDK.

See the Glean SDK documentation for the baseline ping.

This ping is sent if empty.

This ping includes the client id.

Data reviews for this ping:

Bugs related to this ping:

Reasons this ping may be sent:

  • active: The ping was submitted when the application became active again, which includes when the application starts. In earlier versions, this was called foreground.

    *Note*: this ping will not contain the `glean.baseline.duration` metric.
    
  • dirty_startup: The ping was submitted at startup, because the application process was killed before the Glean SDK had the chance to generate this ping, before becoming inactive, in the last session.

    *Note*: this ping will not contain the `glean.baseline.duration` metric.
    
  • inactive: The ping was submitted when becoming inactive. In earlier versions, this was called background.

All Glean pings contain built-in metrics in the ping_info and client_info sections.

In addition to those built-in metrics, the following metrics are added to the ping:

NameTypeDescriptionData reviewsExtrasExpirationData Sensitivity
glean.baseline.durationtimespanThe duration of the last foreground session.Bug 1512938never1, 2
glean.validation.first_run_hourdatetimeThe hour of the first run of the application.Bug 1680783never1
glean.validation.pings_submittedlabeled_counterA count of the pings submitted, by ping type. This metric appears in both the metrics and baseline pings. - On the metrics ping, the counts include the number of pings sent since the last metrics ping (including the last metrics ping) - On the baseline ping, the counts include the number of pings send since the last baseline ping (including the last baseline ping)Bug 1586764never1

deletion-request

This is a built-in ping that is assembled out of the box by the Glean SDK.

See the Glean SDK documentation for the deletion-request ping.

This ping is sent if empty.

This ping includes the client id.

Data reviews for this ping:

Bugs related to this ping:

Reasons this ping may be sent:

  • at_init: The ping was submitted at startup. Glean discovered that between the last time it was run and this time, upload of data has been disabled.

  • set_upload_enabled: The ping was submitted between Glean init and Glean shutdown. Glean was told after init but before shutdown that upload has changed from enabled to disabled.

All Glean pings contain built-in metrics in the ping_info and client_info sections.

This ping contains no metrics.

metrics

This is a built-in ping that is assembled out of the box by the Glean SDK.

See the Glean SDK documentation for the metrics ping.

This ping includes the client id.

Data reviews for this ping:

Bugs related to this ping:

Reasons this ping may be sent:

  • overdue: The last ping wasn't submitted on the current calendar day, but it's after 4am, so this ping submitted immediately

  • reschedule: A ping was just submitted. This ping was rescheduled for the next calendar day at 4am.

  • today: The last ping wasn't submitted on the current calendar day, but it is still before 4am, so schedule to send this ping on the current calendar day at 4am.

  • tomorrow: The last ping was already submitted on the current calendar day, so schedule this ping for the next calendar day at 4am.

  • upgrade: This ping was submitted at startup because the application was just upgraded.

All Glean pings contain built-in metrics in the ping_info and client_info sections.

In addition to those built-in metrics, the following metrics are added to the ping:

NameTypeDescriptionData reviewsExtrasExpirationData Sensitivity
glean.database.sizememory_distributionThe size of the database file at startup.Bug 1656589never1
glean.error.iocounterThe number of times we encountered an IO error when writing a pending ping to disk.Bug 1686233never1
glean.error.preinit_tasks_overflowcounterThe number of tasks queued in the pre-initialization buffer. Only sent if the buffer overflows.Bug 1609482never1
glean.time.invalid_timezone_offsetcounterCounts the number of times we encountered an invalid timezone offset when trying to get the current time. A timezone offset is invalid if it is outside [-24h, +24h]. If invalid a UTC offset is used (+0h).Bug 1611770, Bug 17174022021-12-311
glean.upload.deleted_pings_after_quota_hitcounterThe number of pings deleted after the quota for the size of the pending pings directory or number of files is hit. Since quota is only calculated for the pending pings directory, and deletion request ping live in a different directory, deletion request pings are never deleted.Bug 1601550never1
glean.upload.discarded_exceeding_pings_sizememory_distributionThe size of pings that exceeded the maximum ping size allowed for upload.Bug 1597761never1
glean.upload.pending_pingscounterThe total number of pending pings at startup. This does not include deletion-request pings.Bug 1665041never1
glean.upload.pending_pings_directory_sizememory_distributionThe size of the pending pings directory upon initialization of Glean. This does not include the size of the deletion request pings directory.Bug 1601550never1
glean.upload.ping_upload_failurelabeled_counterCounts the number of ping upload failures, by type of failure. This includes failures for all ping types, though the counts appear in the next successfully sent metrics ping.Bug 1589124
  • status_code_4xx
  • status_code_5xx
  • status_code_unknown
  • unrecoverable
  • recoverable
never1
glean.validation.first_run_hourdatetimeThe hour of the first run of the application.Bug 1680783never1
glean.validation.foreground_countcounterOn mobile, the number of times the application went to foreground.Bug 1683707never1
glean.validation.pings_submittedlabeled_counterA count of the pings submitted, by ping type. This metric appears in both the metrics and baseline pings. - On the metrics ping, the counts include the number of pings sent since the last metrics ping (including the last metrics ping) - On the baseline ping, the counts include the number of pings send since the last baseline ping (including the last baseline ping)Bug 1586764never1

Data categories are defined here.

Pings

A ping is a bundle of related metrics, gathered in a payload to be transmitted. The ping payload is encoded in JSON format and contains one or more of the common sections with shared information data.

If data collection is enabled, the chosen Glean SDK may provide a set of built-in pings that are assembled out of the box without any developer intervention.

Table of contents

Payload structure

Every ping payload has the following keys at the top-level:

  • The ping_info section contains core metadata that is included in every ping.

  • The client_info section contains information that identifies the client. It is included in most pings (including all built-in pings), but may be excluded from pings where we don't want to connect client information with the other metrics in the ping.

The following keys are only present if any metrics or events were recorded for the given ping:

  • The metrics section contains the submitted values for all metric types except for events. It has keys for each of the metric types, under which is data for each metric.

  • The events section contains the events recorded in the ping.

See the payload documentation for more details for each metric type in the metrics and events section.

The ping_info section

The following fields are included in the ping_info section, for every ping. Optional fields are marked accordingly.

seq

Type: Counter, Lifetime: User

A running counter of the number of times pings of this type have been sent.

start_time

Type: Datetime, Lifetime: User

The time of the start of collection of the data in the ping, in local time and with minute precision, including timezone information.

end_time

Type: Datetime, Lifetime: Ping

The time of the end of collection of the data in the ping, in local time and with minute precision, including timezone information. This is also the time this ping was generated and is likely well before ping transmission time.

reason (optional)

The reason the ping was submitted. The specific set of values and their meanings are defined for each metric type in the reasons field in the pings.yaml file.

experiments (optional)

A dictionary of active experiments.

This object contains experiment annotations keyed by the experiment id. Each annotation contains the experiment branch the client is enrolled in and may contain a string to string map with additional data in the extra key.

Both the id and branch are truncated to 30 characters. See Using the Experiments API on how to record experiments data.

{
  "<id>": {
    "branch": "branch-id",
    "extra": {
      "some-key": "a-value"
    }
  }
}

The client_info section

The following fields are included in the client_info section. Optional fields are marked accordingly.

app_build

Type: String, Lifetime: Ping

The build identifier generated by the CI system (e.g. "1234/A"). If the value was not provided through configuration, this metric gets set to Unknown.

app_channel (optional)

Type: String, Lifetime: Ping

The product-provided release channel (e.g. "beta").

app_display_version

Type: String, Lifetime: Ping

The user-visible version string (e.g. "1.0.3"). The meaning of the string (e.g. whether semver or a git hash) is application-specific. If the value was not provided through configuration, this metric gets set to Unknown.

architecture

Type: String, Lifetime: Ping

The architecture of the device (e.g. "arm", "x86").

client_id (optional)

Type: String, Lifetime: User

A UUID identifying a profile and allowing user-oriented correlation of data.

device_manufacturer (optional)

Type: String, Lifetime: Application

The manufacturer of the device the application is running on. Not set if the device manufacturer can't be determined (e.g. on Desktop).

device_model (optional)

Type: String, Lifetime: Application

The model of the device the application is running on. On Android, this is Build.MODEL, the user-visible marketing name, like "Pixel 2 XL". Not set if the device model can't be determined (e.g. on Desktop).

first_run_date

Type: Datetime, Lifetime: User

The date of the first run of the application, in local time and with day precision, including timezone information.

os

Type: String, Lifetime: Application

The name of the operating system (e.g. "Linux", "Android", "iOS").

os_version

Type: String, Lifetime: Application

The user-visible version of the operating system (e.g. "1.2.3"). If the version detection fails, this metric gets set to Unknown.

android_sdk_version (optional)

Type: String, Lifetime: Application

The Android specific SDK version of the software running on this hardware device (e.g. "23").

telemetry_sdk_build

Type: String, Lifetime: Application

The version of the Glean SDK.

locale (optional)

Type: String, Lifetime: Application

The locale of the application during initialization (e.g. "es-ES"). If the locale can't be determined on the system, the value is "und", to indicate "undetermined".

Ping submission

The pings that the Glean SDK generates are submitted to the Mozilla servers at specific paths, in order to provide additional metadata without the need to unpack the ping payload.

URL

A typical submission URL looks like

"<server-address>/submit/<application-id>/<doc-type>/<glean-schema-version>/<document-id>"

where:

  • <server-address>: the address of the server that receives the pings;
  • <application-id>: a unique application id, automatically detected by the Glean SDK; this is the value returned by Context.getPackageName();
  • <doc-type>: the name of the ping; this can be one of the pings available out of the box with the Glean SDK, or a custom ping;
  • <glean-schema-version>: the version of the Glean ping schema;
  • <document-id>: a unique identifier for this ping.

Limitations

To keep resource usage in check, the Glean SDK enforces some limitations on ping uploading and ping storage.

Rate limiting

Only up to 15 ping submissions every 60 seconds are allowed.

There are no exposed methods to change these rate limiting defaults, follow Bug 1647630 and Bug 1727069 for updates.

Request body size limiting

The body of a ping request may have up to 1MB (after compression). Pings that exceed this size are discarded and don't get uploaded. Size and number of discarded pings are recorded on the internal Glean metric glean.upload.discarded_exceeding_pings_size.

Storage quota

Pending pings are stored on disk. Storage is scanned every time Glean is initialized and upon scanning Glean checks its size. If it exceeds a size of 10MB or 250 pending pings, pings are deleted to get the storage back to an accepted size. Pings are deleted oldest first, until the storage size is below the quota.

The number of deleted pings due to exceeding storage quota is recorded on the metric glean.upload.deleted_pings_after_quota_hit and the size of the pending pings directory is recorded (regardless on whether quota has been reached) on the metric glean.upload.pending_pings_directory_size.

Deletion request pings are not subject to this limitation and never get deleted.

Submitted headers

A pre-defined set of headers is additionally sent along with the submitted ping.

Content-Type

Describes the data sent to the server. Value is always application/json; charset=utf-8.

Date

Submission date/time in GMT/UTC+0 offset, e.g. Mon, 23 Jan 2019 10:10:10 GMT+00:00.

User-Agent

The Glean SDKs do not set this header1, so it will contain whatever value was set by the underlying uploading mechanism. For example, when sending pings from browsers it will contain the characteristic browser UA string.

This header is parsed by the Glean pipeline and can be queried at analysis time through the metadata.user_agent.* fields in the ping tables.

X-Telemetry-Agent

The Glean SDK version and platform this ping is sent from. Useful for debugging purposes when pings are sent to the error stream. as it describes the application and the Glean SDK used for sending the ping.

It's looks like Glean/40.0.0 (Kotlin on Android), where 40.0.0 is the Glean SDK version number and Kotlin on Android is the name of the language used by the SDK that sent the request plus the name of the platform it is running on.

This header is currently only sent by the Glean JavaScript SDK. See note.

X-Client-Type

Custom header to support handling of Glean pings in the legacy pipeline. Values is always Glean.

X-Client-Version

The Glean SDK version e.g. 0.40.0, sent as a custom header to support handling of Glean pings in the legacy pipeline.

X-Debug-Id (optional)

Debug header attached to Glean pings by using the debug APIs, e.g. test-tag.

When this header is present, the ping is redirected to the Glean Debug View.

X-Source-Tags (optional)

A list of tags to associate with the ping, useful for clustering pings at analysis time, for example to tell data generated from CI from other data e.g. automation, perf.

This header is attached to Glean pings by using the debug APIs.

1

This is only true for the Glean JavaScript SDK at the moment. For the other SDKs this header is overwritten with the value that is described on the X-Telemetry-Agent header section. However, this feature will be implemented soon on all SDKs. Follow Bug 1711928 for updates.

Custom pings

Applications can define metrics that are sent in custom pings. Unlike the built-in pings, custom pings are sent explicitly by the application.

This is useful when the scheduling of the built-in pings (metrics, baseline and events) are not appropriate for your data. Since the timing of the submission of custom pings is handled by the application, the measurement window is under the application's control.

This is especially useful when metrics need to be tightly related to one another, for example when you need to measure the distribution of frame paint times when a particular rendering backend is in use. If these metrics were in different pings, with different measurement windows, it is much harder to do that kind of reasoning with much certainty.

Defining a custom ping

Custom pings must be defined in a pings.yaml file, placed in the same directory alongside your app's metrics.yaml file.

For example, to define a custom ping called search specifically for search information:

$schema: moz://mozilla.org/schemas/glean/pings/2-0-0

search:
  description: >
    A ping to record search data.
  include_client_id: false
  notification_emails:
    - CHANGE-ME@example.com
  bugs:
    - http://bugzilla.mozilla.org/123456789/
  data_reviews:
    - http://example.com/path/to/data-review

Refer to the pings YAML registry format for a full reference on the pings.yaml file structure.

Sending metrics in a custom ping

To send a metric on a custom ping, you add the custom ping's name to the send_in_pings parameter in the metrics.yaml file.

Ping metadata must be loaded before sending!

After defining a custom ping, before it can be used for sending data, its metadata must be loaded into your application or library.

For example, to define a new metric to record the default search engine, which is sent in a custom ping called search, put search in the send_in_pings parameter. Note that it is an error to specify a ping in send_in_pings that does not also have an entry in pings.yaml.

search.default:
  name:
    type: string
    description: >
      The name of the default search engine.
    send_in_pings:
      - search

If this metric should also be sent in the default ping for the given metric type, you can add the special value default to send_in_pings:

    send_in_pings:
      - search
      - default

The glean.restarted event

For custom pings that contain event metrics, the glean.restarted event is injected by Glean on every application restart that may happen during the pings measurement window.

Only applies to the Glean JavaScript SDK

The behavior described in this section only applies to custom pings sent by the Glean JavaScript SDK. Follow the implementation of this feature on the other SDKs through Bug 1716725.

Event timestamps throughout application restarts

Event timestamps are always calculated relative to the first event in a ping. The first event will always have timestamp 0 and subsequent events will have timestamps corresponding to the elapsed amount of milliseconds since that first event.

That is also the case for events recorded throughout restarts.

Example

In the below example payload, there were two events recorded on the first application run. The first event is timestamp 0 and the second event happens one second after the first one, so it has timestamp 1000.

The application is restarted one hour after the first event and a glean.restarted event is recorded, timestamp 3600000. Finally, an event is recorded during the second application run two seconds after restart, timestamp 3800000.

{
  ...
  "events": [
    {
      "timestamp": 0,
      "category": "examples",
      "name": "event_example",
    },
    {
      "timestamp": 1000,
      "category": "examples",
      "name": "event_example"
    },
    {
      "timestamp": 3600000,
      "category": "glean",
      "name": "restarted"
    },
    {
      "timestamp": 3800000,
      "category": "examples",
      "name": "event_example"
    },
  ]
}

Caveat: Handling decreasing time offsets

For events recorded in a single application run, Glean relies on a monotonically increasing timer to calculate event timestamps, while for calculating the time elapsed between application runs Glean has to rely on the computer clock, which is not necessarily monotonically increasing.

In the case that timestamps in between application runs are not monotonically increasing, Glean will take the value of the previous timestamp and add one millisecond, thus guaranteeing that timestamps are always increasing.

Checking for decreasing time offsets between restarts

When this edge case is hit, Glean records an InvalidValue error for the glean.restarted metric. This metric may be consulted at analysis time. It is sent in the same ping where the error happened.

In the below example payload, the first and second application runs go exactly like in the example above.

The only difference is that when the restart happens, the offset between the absolute time of the first event and the absolute time of the restart is not enough to keep the timestamps increasing. That may happen for many reasons, such as a change in timezones or simply a manual change in the clock by the user.

In this case, Glean will ignore the incorrect timestamp and add one millisecond to the last timestamp of the previous run, in order to keep the monotonically increasing nature of the timestamps.

{
  ...
  "events": [
    {
      "timestamp": 0,
      "category": "examples",
      "name": "event_example",
    },
    {
      "timestamp": 1000,
      "category": "examples",
      "name": "event_example"
    },
    {
      "timestamp": 1001,
      "category": "glean",
      "name": "restarted"
    },
    {
      "timestamp": 3001,
      "category": "examples",
      "name": "event_example"
    },
  ]
}

Testing custom pings

Applications defining custom pings can use use the ping testing API to test these pings in unit tests.

General testing strategy

The schedule of custom pings depends on the specific application implementation, since it is up to the SDK user to define the ping semantics. This makes the testing strategy a bit more complex, but usually boiling down to:

  1. Triggering the code path that accumulates/records the data.
  2. Defining a callback validation function using the ping testing API.
  3. Finally triggering the code path that submits the custom ping or submitting the ping using the submit API.

Pings sent by Glean

If data collection is enabled, the Glean SDK provides a set of built-in pings that are assembled out of the box without any developer intervention. The following is a list of these built-in pings:

  • baseline ping: A small ping sent every time the application goes to foreground and background. Going to foreground also includes when the application starts.
  • deletion-request ping: Sent when the user disables telemetry in order to request a deletion of their data.
  • events ping: The default ping for events. Sent every time the application goes to background or a certain number of events is reached.
  • metrics ping: The default ping for metrics. Sent approximately daily.

Applications can also define and send their own custom pings when the schedules of these pings is not suitable.

There is also a high-level overview of how the metrics and baseline pings relate and the timings they record.

Available pings per platform

Language Bindingbaselinedeletion-requesteventsmetrics
Kotlin
Swift
Python
Rust
JavaScript
Firefox Desktop

Defining foreground and background state

These docs refer to application 'foreground' and 'background' state in several places.

Foreground

For Android, this specifically means the activity becomes visible to the user, it has entered the Started state, and the system invokes the onStart() callback.

Background

This specifically means when the activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback.

This may occur, if the user uses Overview button to change to another app, the user presses the Back button and navigates to a previous application or the home screen, or if the user presses the Home button to return to the home screen. This can also occur if the user navigates away from the application through some notification or other means.

The system may also call onStop() when the activity has finished running, and is about to be terminated.

Foreground

For iOS, the Glean SDK attaches to the willEnterForegroundNotification. This notification is posted by the OS shortly before an app leaves the background state on its way to becoming the active app.

Background

For iOS, this specifically means when the app is no longer visible to the user, or when the UIApplicationDelegate receives the applicationDidEnterBackground event.

This may occur if the user opens the task switcher to change to another app, or if the user presses the Home button to show the home screen. This can also occur if the user navigates away from the app through a notification or other means.

Note: Glean does not currently support Scene based lifecycle events that were introduced in iOS 13.

The baseline ping

Description

This ping is intended to provide metrics that are managed by the Glean SDK itself, and not explicitly set by the application or included in the application's metrics.yaml file.

Platform availability

Language BindingKotlinSwiftPythonRustJavaScriptFirefox Desktop
baseline ping

Scheduling

The baseline ping is automatically submitted with a reason: active when the application becomes active (on mobile it means getting to foreground). These baseline pings do not contain duration.

The baseline ping is automatically submitted with a reason: inactive when the application becomes inactive (on mobile it means getting to background). If no baseline ping is triggered when becoming inactive (e.g. the process is abruptly killed) a baseline ping with reason dirty_startup will be submitted on the next application startup. This only happens from the second application start onward.

See also the ping schedules and timing overview.

Contents

The baseline ping also includes the common ping sections found in all pings.

It also includes a number of metrics defined in the Glean SDK itself.

Querying ping contents

A quick note about querying ping contents (i.e. for sql.telemetry.mozilla.org): Each metric in the baseline ping is organized by its metric type, and uses a namespace of glean.baseline. For instance, in order to select duration you would use metrics.timespan['glean.baseline.duration']. If you were trying to select a String based metric such as os, then you would use metrics.string['glean.baseline.os']

Example baseline ping

{
  "ping_info": {
    "experiments": {
      "third_party_library": {
        "branch": "enabled"
      }
    },
    "seq": 0,
    "start_time": "2019-03-29T09:50-04:00",
    "end_time": "2019-03-29T09:53-04:00",
    "reason": "foreground"
  },
  "client_info": {
    "telemetry_sdk_build": "0.49.0",
    "first_run_date": "2019-03-29-04:00",
    "os": "Android",
    "android_sdk_version": "27",
    "os_version": "8.1.0",
    "device_manufacturer": "Google",
    "device_model": "Android SDK built for x86",
    "architecture": "x86",
    "app_build": "1",
    "app_display_version": "1.0",
    "client_id": "35dab852-74db-43f4-8aa0-88884211e545"
  },
  "metrics": {
    "timespan": {
      "glean.baseline.duration": {
        "value": 52,
        "time_unit": "second"
      }
    }
  }
}

The deletion-request ping

Description

This ping is submitted when a user opts out of sending technical and interaction data.

This ping contains the client id.

This ping is intended to communicate to the Data Pipeline that the user wishes to have their reported Telemetry data deleted. As such it attempts to send itself at the moment the user opts out of data collection, and continues to try and send itself.

Adding secondary ids

It is possible to send secondary ids in the deletion request ping. For instance, if the application is migrating from legacy telemetry to Glean, the legacy client ids can be added to the deletion request ping by creating a metrics.yaml entry for the id to be added with a send_in_pings value of deletion_request.

An example metrics.yaml entry might look like this:

legacy_client_id:
   type: uuid
   description:
     A UUID uniquely identifying the legacy client.
   send_in_pings:
     - deletion_request
   ...

Platform availability

Language BindingKotlinSwiftPythonRustJavaScriptFirefox Desktop
deletion-request ping

Scheduling

The deletion-request ping is automatically submitted when upload is disabled in Glean. If upload fails, it is retried after Glean is initialized.

Contents

The deletion-request does not contain additional metrics aside from secondary ids that have been added.

Example deletion-request ping

{
  "ping_info": {
    "seq": 0,
    "start_time": "2019-12-06T09:50-04:00",
    "end_time": "2019-12-06T09:53-04:00"
  },
  "client_info": {
    "telemetry_sdk_build": "22.0.0",
    "first_run_date": "2019-03-29-04:00",
    "os": "Android",
    "android_sdk_version": "28",
    "os_version": "9",
    "device_manufacturer": "Google",
    "device_model": "Android SDK built for x86",
    "architecture": "x86",
    "app_build": "1",
    "app_display_version": "1.0",
    "client_id": "35dab852-74db-43f4-8aa0-88884211e545"
  },
  "metrics": {
    "uuid": {
      "legacy_client_id": "5faffa6d-6147-4d22-a93e-c1dbd6e06171"
    }
  }
}

The events ping

Description

The events ping's purpose is to transport all of the event metric information. If the application crashes, an events ping is generated next time the application starts with events that were not sent before the crash.

Platform availability

Language BindingKotlinSwiftPythonRustJavaScriptFirefox Desktop
events ping

Scheduling

The events ping is collected under the following circumstances:

  1. Normally, it is collected when the application becomes inactive (on mobile, this means going to background), if there are any recorded events to send.

  2. When the queue of events exceeds Glean.configuration.maxEvents (default 500).

  3. If there are any unsent events found on disk when starting the application. (This results in this ping never containing the glean.restarted event.)

All of these cases are handled automatically, with no intervention or configuration required by the application.

Python and JavaScript caveats

Since the Glean Python and JavaScript SDKs don't have a concept of "going to background", case (1) above does not apply.

Contents

At the top-level, this ping contains the following keys:

  • ping_info: The information common to all pings.

  • events: An array of all of the events that have occurred since the last time the events ping was sent.

Each entry in the events array is an object with the following properties:

  • "timestamp": The milliseconds relative to the first event in the ping.

  • "category": The category of the event, as defined by its location in the metrics.yaml file.

  • "name": The name of the event, as defined in the metrics.yaml file.

  • "extra" (optional): A mapping of strings to strings providing additional data about the event. The keys are restricted to 40 characters and values in this map will never exceed 100 characters.

Example event JSON

{
  "ping_info": {
    "experiments": {
      "third_party_library": {
        "branch": "enabled"
      }
    },
    "seq": 0,
    "start_time": "2019-03-29T09:50-04:00",
    "end_time": "2019-03-29T10:02-04:00"
  },
  "client_info": {
    "telemetry_sdk_build": "0.49.0",
    "first_run_date": "2019-03-29-04:00",
    "os": "Android",
    "android_sdk_version": "27",
    "os_version": "8.1.0",
    "device_manufacturer": "Google",
    "device_model": "Android SDK built for x86",
    "architecture": "x86",
    "app_build": "1",
    "app_display_version": "1.0",
    "client_id": "35dab852-74db-43f4-8aa0-88884211e545"
  },
  "events": [
    {
      "timestamp": 0,
      "category": "examples",
      "name": "event_example",
      "extra": {
        "metadata1": "extra",
        "metadata2": "more_extra"
      }
    },
    {
      "timestamp": 1000,
      "category": "examples",
      "name": "event_example"
    }
  ]
}

The metrics ping

Description

The metrics ping is intended for all of the metrics that are explicitly set by the application or are included in the application's metrics.yaml file (except events). The reported data is tied to the ping's measurement window, which is the time between the collection of two metrics pings. Ideally, this window is expected to be about 24 hours, given that the collection is scheduled daily at 04:00. However, the metrics ping is only submitted while the application is actually running, so in practice, it may not meet the 04:00 target very frequently. Data in the ping_info section of the ping can be used to infer the length of this window and the reason that triggered the ping to be submitted. If the application crashes, unsent recorded metrics are sent along with the next metrics ping.

Additionally, it is undesirable to mix metric recording from different versions of the application. Therefore, if a version upgrade is detected, the metrics ping is collected immediately before further metrics from the new version are recorded.

Platform availability

Language BindingKotlinSwiftPythonRustJavaScriptFirefox Desktop
metrics ping

Scheduling

The desired behavior is to collect the ping at the first available opportunity after 04:00 local time on a new calendar day, but given constraints of the platform, it can only be submitted while the application is running. This breaks down into three scenarios:

  1. the application was just installed;
  2. the application was just upgraded (the version of the app is different from the last time the app was run);
  3. the application was just started (after a crash or a long inactivity period);
  4. the application was running at 04:00.

In the first case, since the application was just installed, if the due time for the current calendar day has passed, a metrics ping is immediately generated and scheduled for sending (reason code overdue). Otherwise, if the due time for the current calendar day has not passed, a ping collection is scheduled for that time (reason code today).

In the second case, if a version change is detected at startup, the metrics ping is immediately submitted so that metrics from one version are not aggregated with metrics from another version (reason code upgrade).

In the third case, if the metrics ping was not already collected on the current calendar day, and it is before 04:00, a collection is scheduled for 04:00 on the current calendar day (reason code today). If it is after 04:00, a new collection is scheduled immediately (reason code overdue). Lastly, if a ping was already collected on the current calendar day, the next one is scheduled for collecting at 04:00 on the next calendar day (reason code tomorrow).

In the fourth and last case, the application is running during a scheduled ping collection time. The next ping is scheduled for 04:00 the next calendar day (reason code reschedule).

More scheduling examples are included below.

See also the ping schedules and timing overview.

Contents

The metrics ping contains all of the metrics defined in metrics.yaml (except events) that don't specify a ping or where default is specified in their send in pings property.

Additionally, error metrics in the glean.error category are included in the metrics ping.

The metrics ping shall also include the common ping_info and 'client_info' sections. It also includes a number of metrics defined in the Glean SDK itself.

Querying ping contents

Information about query ping contents is available in Accessing Glean data in the Firefox data docs.

Scheduling Examples

Crossing due time with the application closed

  1. The application is opened on Feb 7 on 15:00, closed on 15:05.

    • Glean records one metric A (say startup time in ms) during this measurement window MW1.
  2. The application is opened again on Feb 8 on 17:00.

  • Glean notes that we passed local 04:00 since MW1.

  • Glean closes MW1, with:

    • start_time=Feb7/15:00;
    • end_time=Feb8/17:00.
  • Glean records metric A again, into MW2, which has a start_time of Feb8/17:00.

Crossing due time and changing timezones

  1. The application is opened on Feb 7 on 15:00 in timezone UTC, closed on 15:05.

    • Glean records one metric A (say startup time in ms) during this measurement window MW1.
  2. The application is opened again on Feb 8 on 17:00 in timezone UTC+1.

    • Glean notes that we passed local 04:00 UTC+1 since MW1.

    • Glean closes MW1, with:

      • start_time=Feb7/15:00/UTC;
      • end_time=Feb8/17:00/UTC+1.
    • Glean records metric A again, into MW2.

The application doesn’t run in a week

  1. The application is opened on Feb 7 on 15:00 in timezone UTC, closed on 15:05.

    • Glean records one metric A (say startup time in ms) during this measurement window MW1.
  2. The application is opened again on Feb 16 on 17:00 in timezone UTC.

    • Glean notes that we passed local 04:00 UTC since MW1.

    • Glean closes MW1, with:

      • start_time=Feb7/15:00/UTC;
      • end_time=Feb16/17:00/UTC.
    • Glean records metric A again, into MW2.

The application doesn’t run for a week, and when it’s finally re-opened the timezone has changed

  1. The application is opened on Feb 7 on 15:00 in timezone UTC, closed on 15:05.

    • Glean records one metric A (say startup time in ms) during this measurement window MW1.
  2. The application is opened again on Feb 16 on 17:00 in timezone UTC+1.

    • Glean notes that we passed local 04:00 UTC+1 since MW1.

    • Glean closes MW1, with:

      • start_time=Feb7/15:00/UTC
      • end_time=Feb16/17:00/UTC+1.
    • Glean records metric A again, into MW2.

The user changes timezone in an extreme enough fashion that they cross 04:00 twice on the same date

  1. The application is opened on Feb 7 at 15:00 in timezone UTC+11, closed at 15:05.

    • Glean records one metric A (say startup time in ms) during this measurement window MW1.
  2. The application is opened again on Feb 8 at 04:30 in timezone UTC+11.

    • Glean notes that we passed local 04:00 UTC+11.

    • Glean closes MW1, with:

      • start_time=Feb7/15:00/UTC+11;
      • end_time=Feb8/04:30/UTC+11.
    • Glean records metric A again, into MW2.

  3. The user changes to timezone UTC-10 and opens the application at Feb 7 at 22:00 in timezone UTC-10

    • Glean records metric A again, into MW2 (not MW1, which was already sent).
  4. The user opens the application at Feb 8 05:00 in timezone UTC-10

    • Glean notes that we have not yet passed local 04:00 on Feb 9
    • Measurement window MW2 remains the current measurement window
  5. The user opens the application at Feb 9 07:00 in timezone UTC-10

    • Glean notes that we have passed local 04:00 on Feb 9

    • Glean closes MW2 with:

      • start_time=Feb8/04:30/UTC+11;
      • end_time=Feb9/19:00/UTC-10.
    • Glean records metric A again, into MW3.

Ping schedules and timings overview

Full reference details about the metrics and baseline ping schedules are detailed elsewhere.

The following diagram shows a typical timeline of a mobile application, when pings are sent and what timing-related information is included.

ping timeline diagram

There are two distinct runs of the application, where the OS shutdown the application at the end of Run 1, and the user started it up again at the beginning of Run 2.

There are three distinct foreground sessions, where the application was visible on the screen and the user was able to interact with it.

The rectangles for the baseline and metrics pings represent the measurement windows of those pings, which always start exactly at the end of the preceding ping. The ping_info.start_time and ping_info.end_time metrics included in these pings correspond to these beginning and the end of their measurement windows.

The baseline.duration metric (included only in baseline pings) corresponds to amount of time the application spent on the foreground, which, since measurement window always extend to the next ping, is not always the same thing as the baseline ping's measurement window.

The submission_timestamp is the time the ping was received at the telemetry endpoint, added by the ingestion pipeline. It is not exactly the same as ping_info.end_time, since there may be various networking and system latencies both on the client and in the ingestion pipeline (represented by the dotted horizontal line, not to scale). Also of note is that start_time/end_time are measured using the client's real-time clock in its local timezone, which is not a fully reliable source of time.

The "Baseline 4" ping illustrates an important corner case. When "Session 2" ended, the OS also shut down the entire process, and the Glean SDK did not have an opportunity to send a baseline ping immediately. In this case, it is sent at the next available opportunity when the application starts up again in "Run 2". This baseline ping is annotated with the reason code dirty_startup.

The "Metrics 2" ping likewise illustrates another important corner case. "Metrics 1" was able to be sent at the target time of 04:00 (local device time) because the application was currently running. However, the next time 04:00 came around, the application was not active, so the Glean SDK was unable to send a metrics ping. It is sent at the next available opportunity, when the application starts up again in "Run 2". This metrics ping is annotated with the reason code overdue.

Debugging products using the Glean SDK

Glean provides a few debugging features to assist with debugging a product using Glean.

Features

Log Pings

Print the ping payload upon sending a ping.

Debug View Tag

Tags all outgoing pings as debug pings to make them available for real-time validation, on the Glean Debug View.

Glean Debug View

The Glean Debug View enables you to easily see in real-time what data your application is sending.

This data is what actually arrives in our data pipeline, shown in a web interface that is automatically updated when new data arrives. Any data sent from a Glean-instrumented application usually shows up within 10 seconds, updating the pages automatically. Pings are retained for 3 weeks.

Troubleshooting

If nothing is showing up on the dashboard after you set a debugViewTag and you see Glean must be enabled before sending pings. in the logs, Glean is disabled. Check with the application author on how to re-enable it.

Source Tags

Tags outgoing pings with a maximum of 5 comma-separated tags.

Send Ping

Sends a ping on demand.

Debugging methods

Each language binding or platform supported may expose one or more of the following methods to interact with and enable these debugging functionalities.

  1. Enable debugging features through APIs exposed through the Glean singleton;
  2. Enable debugging features through environment variables set at runtime;
  3. Enable debugging features through platform specific tooling.

For methods 1. and 2., refer to the API reference section "Debugging" for detailed information on how to use them.

For method 3. please refer to the platform specific pages on how to debug products using Glean.

Platform Specific Information

  1. Debugging Android applications using the Glean SDK
  2. Debugging iOS applications using the Glean SDK
  3. Debugging Python applications using the Glean SDK
  4. Debugging JavaScript applications using Glean.js

Available debugging methods per platform

Glean APIEnvironment VariablesPlatform Specific Tooling
Kotlin1
Swift2
Python
Rust
JavaScript
Firefox Desktop3
1

In Kotlin, the Glean SDK exposes the GleanDebugActivity for interacting with debug features. Although it is technically possible to also use environment variables in Android, the Glean team is not aware of a proper way to set environment variables in Android devices or emulators.

2

In Swift, the Glean SDK exposes a custom URL format for interacting with debug features.

3

In Firefox Desktop, developers may use the interface exposed through about:glean to log, tag or send pings.

Debugging Android applications using the Glean SDK

The Glean SDK exports the GleanDebugActivity that can be used to toggle debugging features on or off. Users can invoke this special activity, at run-time, using the following adb command:

adb shell am start -n [applicationId]/mozilla.telemetry.glean.debug.GleanDebugActivity [extra keys]

In the above:

  • [applicationId] is the product's application id as defined in the manifest file and/or build script. For the Glean sample application, this is org.mozilla.samples.gleancore for a release build and org.mozilla.samples.gleancore.debug for a debug build.

  • [extra keys] is a list of extra keys to be passed to the debug activity. See the documentation for the command line switches used to pass the extra keys. These are the currently supported keys:

keytypedescription
logPingsboolean (--ez)If set to true, pings are dumped to logcat; defaults to false
debugViewTagstring (--es)Tags all outgoing pings as debug pings to make them available for real-time validation, on the Glean Debug View. The value must match the pattern [a-zA-Z0-9-]{1,20}. Important: in older versions of the Glean SDK, this was named tagPings
sourceTagsstring array (--esa)Tags outgoing pings with a maximum of 5 comma-separated tags. The tags must match the pattern [a-zA-Z0-9-]{1,20}. The automation tag is meant for tagging pings generated on automation: such pings will be specially handled on the pipeline (i.e. discarded from non-live views). Tags starting with glean are reserved for future use. Subsequent calls of this overwrite any previously stored tag
sendPingstring (--es)Sends the ping with the given name immediately
startNextstring (--es)The name of an exported Android Activity, as defined in the product manifest file, to start right after the GleanDebugActivity completes. All the options provided are propagated to this next activity as well. When omitted, the default launcher activity for the product is started instead.

All the options provided to start the activity are passed over to the main activity for the application to process. This is useful if SDK users wants to debug telemetry while providing additional options to the product to enable specific behaviors.

Note: Due to limitations on Android logcat message size, pings larger than 4KB are broken into multiple log messages when using logPings.

For example, to direct a release build of the Glean sample application to (1) dump pings to logcat, (2) tag the ping with the test-metrics-ping tag, and (3) send the "metrics" ping immediately, the following command can be used:

adb shell am start -n org.mozilla.samples.gleancore/mozilla.telemetry.glean.debug.GleanDebugActivity \
  --ez logPings true \
  --es sendPing metrics \
  --es debugViewTag test-metrics-ping

The logPings command doesn't trigger ping submission and you won't see any output until a ping has been sent. You can use the sendPing command to force a ping to be sent, but it could be more desirable to trigger the pings submission on their normal schedule. For instance, the baseline and events pings can be triggered by moving the app out of the foreground and the metrics ping can be triggered normally if it is overdue for the current calendar day.

Note: The device or emulator must be connected to the internet for this to work. Otherwise the job that sends the pings won't be triggered.

If no metrics have been collected, no pings will be sent unless send_if_empty is set on your ping. See the ping documentation for more information on ping scheduling to learn when pings are sent.

Options that are set using the adb flags are not immediately reset and will persist until the application is closed or manually reset.

Glean SDK Log messages

When running a Glean SDK-powered app in the Android emulator or on a device connected to your computer via cable, there are several ways to read the log output.

Android Studio

Android Studio can show the logs of a connected emulator or device. To display the log messages for an app:

  1. Run an app on your device.
  2. Click View > Tool Windows > Logcat (or click Logcat in the tool window bar).

The Logcat window will show all log messages and allows to filter those by the application ID. Select the application ID of the product you're debugging. You can also filter by Glean only.

More information can be found in the View Logs with Logcat help article.

Command line

On the command line you can show all of the log output using:

adb logcat

This is the unfiltered output of all log messages. You can match for glean using grep:

adb logcat | grep -i glean

A simple way to filter for only the application that is being debugged is by using pidcat, a wrapper around adb, which adds colors and proper filtering by application ID and log level. Run it like this to filter for an application:

pidcat [applicationId]

In the above [applicationId] is the product's application id as defined in the manifest file and/or build script. For the Glean sample application, this is org.mozilla.samples.gleancore for a release build and org.mozilla.samples.gleancore.debug for a debug build.

Debugging iOS applications using the Glean SDK

Enabling debugging features in iOS through environment variables

Debugging features in iOS can be enabled using environment variables. For more information on the available features accessible through this method and how to enable them, see Debugging API reference.

These environment variables must be set on the device that is running the application.

Enabling debugging features in iOS through a custom URL scheme

For debugging and validation purposes on iOS, the Glean SDK makes use of a custom URL scheme which is implemented within the application that is consuming the Glean SDK. The Glean SDK provides some convenience functions to facilitate this, but it's up to the consuming application to enable this functionality. Applications that enable this Glean SDK feature will be able to launch the application from a URL with the Glean debug commands embedded in the URL itself.

Available commands and query format

All 4 Glean debugging features are available through the custom URL scheme tool.

  • logPings: This is either true or false and will cause pings that are submitted to also be echoed to the device's log.
  • debugViewTag: This command will tag outgoing pings with the provided value, in order to identify them in the Glean Debug View.
  • sourceTags: This command tags outgoing pings with a maximum of 5 comma-separated tags.
  • sendPing: This command expects a string name of a ping to force immediate collection and submission of.

The structure of the custom URL uses the following format:

<protocol>://glean?<command 1>=<paramter 1>&<command 2>=<parameter 2> ...

Where:

  • <protocol> is the "URL Scheme" that has been added for your app (see Instrumenting the application below), such as glean-sample-app.
  • This is followed by :// and then glean which is required for the Glean SDK to recognize the command is meant for it to process.
  • Following standard URL query format, the next character after glean is the ? indicating the beginning of the query.
  • This is followed by one or more queries in the form of <command>=<parameter>, where the command is one of the commands listed above, followed by an = and then the value or parameter to be used with the command.

There are a few things to consider when creating the custom URL:

  • Invalid commands will log an error and cause the entire URL to be ignored.
  • Not all commands are required to be encoded in the URL, you can mix and match the commands that you need.
  • Multiple instances of commands are not allowed in the same URL and, if present, will cause the entire URL to be ignored.
  • The logPings command doesn't trigger ping submission and you won't see any output until a ping has been submitted. You can use the sendPing command to force a ping to be sent, but it could be more desirable to trigger the pings submission on their normal schedule. For instance, the baseline and events pings can be triggered by moving the app out of the foreground and the metrics ping can be triggered normally if it is overdue for the current calendar day. See the ping documentation for more information on ping scheduling to learn when pings are sent.
  • Enabling debugging features through custom URLs overrides any debugging features set through environment variables.

Instrumenting the application for Glean SDK debug functionality

In order to enable the debugging features in a Glean SDK consuming iOS application, it is necessary to add some information to the application's Info.plist, and add a line and possibly an override for a function in the AppDelegate.swift.

Register custom URL scheme in Info.plist

Note: If your application already has a custom URL scheme implemented, there is no need to implement a second scheme, you can simply use that and skip to the next section about adding the convenience method. If the app doesn't have a custom URL scheme implemented, then you will need to perform the following instructions to register your app to receive custom URLs.

Find and open the application's Info.plist and right click any blank area and select Add Row to create a new key.

You will be prompted to select a key from a drop-down menu, scroll down to and select URL types. This creates an array item, which can be expanded by clicking the triangle disclosure icon.

Select Item 0, click on it and click the disclosure icon to expand it and show the URL identifier line. Double-click the value field and fill in your identifier, typically the same as the bundle ID.

Right-click on Item 0 and select Add Row from the context menu. In the dropdown menu, select URL Schemes to add the item.

Click on the disclosure icon of URL Schemes to expand the item, double-click the value field of Item 0 and key in the value for your application's custom scheme. For instance, the Glean sample app uses glean-sample-app, which allows for custom URLs to be crafted using that as a protocol, for example: glean-sample-app://glean?logPings=true

Add the Glean.handleCustomUrl() convenience function and necessary overrides

In order to handle the incoming Glean SDK debug commands, it is necessary to implement the override in the application's AppDelegate.swift file. Within that function, you can make use of the convenience function provided in Glean handleCustomUrl(url: URL).

An example of a simple implementation of this would look like this:

func application(_: UIApplication,
                 open url: URL,
                 options _: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    // ...

    // This does nothing if the url isn't meant for Glean.
    Glean.shared.handleCustomUrl(url: url)

    // ...

    return true
}

If you need additional help setting up a custom URL scheme in your application, please refer to Apple's documentation.

Invoking the Glean-iOS debug commands

Now that the app has the Glean SDK debug functionality enabled, there are a few ways in which we can invoke the debug commands.

Using a web browser

Perhaps the simplest way to invoke the Glean SDK debug functionality is to open a web browser and type/paste the custom URL into the address bar. This is especially useful on an actual device because there isn't a good way to launch from the command line and process the URL for an actual device.

Using the glean-sample-app as an example: to activate ping logging, tag the pings to go to the Glean Debug View, and force the events ping to be sent, enter the following URL in a web browser on the iOS device:

glean-sample-app://glean?logPings=true&debugViewTag=My-ping-tag&sendPing=events

This should cause iOS to prompt you with a dialog asking if you want to open the URL in the Glean Sample App, and if you select "Okay" then it will launch (or resume if it's already running) the application with the indicated commands and parameters and immediately force the collection and submission of the events ping.

Note: This method does not work if the browser you are using to input the command is the same application you are attempting to pass the Glean debug commands to. So, you couldn't use Firefox for iOS to trigger commands within Firefox for iOS.

It is also possible to encode the URL into a 2D barcode or QR code and launch the app via the camera app. After scanning the encoded URL, the dialog prompting to launch the app should appear as if the URL were entered into the browser address bar.

Using the command line

This method is useful for testing via the Simulator, which typically requires a Mac with Xcode installed, including the Xcode command line tools. In order to perform the same command as above with using the browser to input the URL, you can use the following command in the command line terminal of the Mac:

xcrun simctl openurl booted "glean-sample-app://glean?logPings=true&debugViewTag=My-ping-tag&sendPing=events"

This will launch the simulator and again prompt the user with a dialog box asking if you want to open the URL in the Glean Sample App (or whichever app you are instrumenting and testing).

Glean log messages

The Glean SDK integrates with the unified logging system available on iOS. There are various ways to retrieve log information, see the official documentation.

If debugging in the simulator, the logging messages can be seen in the console window within Xcode.

When running a Glean-powered app in the iOS Simulator or on a device connected to your computer via cable you can use Console.app to view the system log. You can filter the logs with category:glean to only see logs from the Glean SDK.

You can also use the command line utility log to stream the log output. Run the following in a shell:

log stream --predicate 'category contains "glean"'

See Diagnosing Issues Using Crash Reports and Device Logs for more information about debugging deployed iOS apps.

Debugging Python applications using the Glean SDK

Debugging features in Python can be enabled using environment variables. For more information on the available features and how to enable them, see the Debugging API reference.

Sending pings

Unlike other platforms, Python doesn't expose convenience methods to send pings on demand.

In case that is necessary, calling the submit function for a given ping, such as pings.custom_ping.submit(), will send it.

Logging pings

If the GLEAN_LOG_PINGS environment variable is set to true, pings are logged to the console on DEBUG level whenever they are submitted.

Make sure that when you configure logging in your application, you set the level for the Python logging library to DEBUG or higher. Otherwise pings won't be logged even if GLEAN_LOG_PINGS is set to true.

You can set the logging level for the Python logging to DEBUG as follows:

import logging

logging.basicConfig(level=logging.DEBUG)

All log messages from the Glean SDK are on the glean logger, so if you need to control it independently, you can set a level for just the Glean SDK (but note that the global Python logging level also needs to be set as above):

logging.getLogger("glean").setLevel(logging.DEBUG)

See the Python logging documentation for more information.

Debugging JavaScript applications using Glean.js

Debugging features in JavaScript can be enabled through APIs exposed on the Glean object. For more information on the available features and how to enable them, see the Debugging API reference.

Sending pings

Unlike other platforms, JavaScript doesn't expose convenience methods to send pings on demand.

In case that is necessary, calling the submit function for a given ping, such as pings.customPing.submit(), will send it.

Note that this method is only effective for custom pings. Glean internal pings are not exposed to users.

Logging pings

By calling Glean.logPings(true) all subsequent pings sent will be logged to the console.

To access the logs for web extensions on

Firefox

  1. Go to about:debugging#/runtime/this-firefox;
  2. Find the extension you want to see the logs for;
  3. Click on Inspect.

Chromium-based browsers

  1. Go to chrome://extensions;
  2. Find the extension you want to see the logs for;
  3. Click on background page.

YAML Registry Format

User defined Glean pings and metrics are declared in YAML files, which must be parsed by glean_parser to generate public APIs for said metrics and pings.

These files also serve the purpose of documenting metrics and pings. They are consumed by the probe-scraper tool, which generates a REST API to access metrics and pings information consumed by most other tools in the Glean ecosystem, such as GLAM and the Glean Dictionary.

Moreover, for products that do not wish to use the Glean Dictionary as their metrics and pings documentation source, glean_parser provides an option to generate Markdown documentation for metrics and pings based on these files. For more information of that, refer to the help output of the translate command, by running in your terminal:

$ glean_parser translate --help

metrics.yaml file

For a full reference on the metrics.yaml format, refer to the Metrics YAML Registry Format page.

pings.yaml file

For a full reference on the pings.yaml format, refer to the Pings YAML Registry Format page.

Metrics YAML Registry Format

Metrics sent by an application or library are defined in YAML files which follow the metrics.yaml JSON schema.

This files must be parsed by glean_parser at build time in order to generate code in the target language (e.g. Kotlin, Swift, ...). The generated code is what becomes the public API to access the project's metrics.

For more information on how to introduce the glean_parser build step for a specific language / environment, refer to the "Adding Glean to your project" section of this book.

Note on the naming of these files

Although we refer to metrics definitions YAML files as metrics.yaml throughout Glean documentation this files may be named whatever makes the most sense for each project and may even be broken down into multiple files, if necessary.

File structure

---
# Schema
$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0

# Category
toolbar:
  # Name
  click:
    # Metric Parameters
    type: event
    description: |
      Event to record toolbar clicks.
    notification_emails:
      - CHANGE-ME@example.com
    bugs:
      - https://bugzilla.mozilla.org/123456789/
    data_reviews:
      - http://example.com/path/to/data-review
    expires: 2019-06-01

  double_click:
    ...

Schema

Declaring the schema at the top of a metrics definitions file is required, as it is what indicates that the current file is a metrics definitions file.

Category

Categories are the top-level keys on metrics definition files. One single definition file may contain multiple categories grouping multiple metrics. They serve the purpose of grouping related metrics in a project.

Categories can contain alphanumeric lower case characters as well as the . and _ characters which can be used to provide extra structure, for example category.subcategory is a valid category. Category lengths may not exceed 40 characters.

Categories may not start with the string glean. That prefix is reserved for Glean internal metrics.

See the "Capitalization" note to understand how the category is formatted in generated code.

Name

Metric names are the second-level keys on metrics definition files.

Names may contain alphanumeric lower case characters as well as the _ character. Metric name lengths may not exceed 30 characters.

"Capitalization" rules also apply to metric names on generated code.

Metric parameters

Specific metric types may have special required parameters in their definition, these parameters are documented in each "Metric Type" reference page.

Following are the parameters common to all metric types.

Required parameters

type

Specifies the type of a metric, like "counter" or "event". This defines which operations are valid for the metric, how it is stored and how data analysis tooling displays it. See the list of supported metric types.

Types should not be changed after release

Once a metric is released in a product, its type should not be changed. If any data was collected locally with the older type, and hasn't yet been sent in a ping, recording data with the new type may cause any old persisted data to be lost for that metric. See this comment for an extended explanation of the different scenarios.

This does not apply to users on the Glean JavaScript SDK. The issues on changing a metrics type described above, do not apply for that SDK.

description

A textual description of the metric for humans. It should describe what the metric does, what it means for analysts, and its edge cases or any other helpful information.

The description field may contain markdown syntax.

Imposed limits on line length

The Glean linter uses a line length limit of 80 characters. If your description is longer, e.g. because it includes longer links, you can disable yamllint using the following annotations (and make sure to enable yamllint again as well):

# yamllint disable
description: |
  Your extra long description, that's longer than 80 characters by far.
# yamllint enable

notification_emails

A list of email addresses to notify for important events with the metric or when people with context or ownership for the metric need to be contacted.

For example when a metric's expiration is within in 14 days, emails will be sent from telemetry-alerts@mozilla.com to the notification_emails addresses associated with the metric.

Consider adding both a group email address and an individual who is responsible for this metric.

bugs

A list of bugs (e.g. Bugzilla or GitHub) that are relevant to this metric. For example, bugs that track its original implementation or later changes to it.

Each entry should be the full URL to the bug in an issue tracker. The use of numbers alone is deprecated and will be an error in the future.

data_reviews

A list of URIs to any data collection review responses relevant to the metric.

expires

When the metric is set to expire.

After a metric expires, an application will no longer collect or send data related to it. May be one of the following values:

  • <build date>: An ISO date yyyy-mm-dd in UTC on which the metric expires. For example, 2019-03-13. This date is checked at build time. Except in special cases, this form should be used so that the metric automatically "sunsets" after a period of time. Emails will be sent to the notification_emails addresses when the metric is about to expire. Generally, when a metric is no longer needed, it should simply be removed. This does not affect the availability of data already collected by the pipeline.
  • never: This metric never expires.
  • expired: This metric is manually expired.

Optional parameters

lifetime

default: ping

Defines the lifetime of the metric. Different lifetimes affect when the metrics value is reset.

ping (default)

The metric is cleared each time it is submitted in the ping. This is the most common case, and should be used for metrics that are highly dynamic, such as things computed in response to the user's interaction with the application.

application

The metric is related to an application run, and is cleared after the application restarts and any Glean-owned ping, due at startup, is submitted. This should be used for things that are constant during the run of an application, such as the operating system version. In practice, these metrics are generally set during application startup. A common mistake--- using the ping lifetime for these type of metrics---means that they will only be included in the first ping sent during a particular run of the application.

user

Reach out to the Glean team before using this.

The metric is part of the user's profile and will live as long as the profile lives. This is often not the best choice unless the metric records a value that really needs to be persisted for the full lifetime of the user profile, e.g. an identifier like the client_id, the day the product was first executed. It is rare to use this lifetime outside of some metrics that are built in to the Glean SDK.

send_in_pings

default: events|metrics

Defines which pings the metric should be sent on. If not specified, the metric is sent on the "default ping", which is the events ping for events and the metrics ping for everything else.

Most metrics don't need to specify this unless they are sent on custom pings.

disabled

default: false

Data collection for this metric is disabled.

This is useful when you want to temporarily disable the collection for a specific metric without removing references to it in your source code.

Generally, when a metric is no longer needed, it should simply be removed. This does not affect the availability of data already collected by the pipeline.

version

default: 0

The version of the metric. A monotonically increasing integer value. This should be bumped if the metric changes in a backward-incompatible way.

data_sensitivity

default: []

A list of data sensitivity categories that the metric falls under. There are four data collection categories related to data sensitivity defined in Mozilla's data collection review process:

Category 1: Technical Data (technical)

Information about the machine or Firefox itself. Examples include OS, available memory, crashes and errors, outcome of automated processes like updates, safe browsing, activation, versions, and build id. This also includes compatibility information about features and APIs used by websites, add-ons, and other 3rd-party software that interact with Firefox during usage.

Category 2: Interaction Data (interaction)

Information about the user’s direct engagement with Firefox. Examples include how many tabs, add-ons, or windows a user has open; uses of specific Firefox features; session length, scrolls and clicks; and the status of discrete user preferences.

Category 3: Web activity data (web_activity)

Information about user web browsing that could be considered sensitive. Examples include users’ specific web browsing history; general information about their web browsing history (such as TLDs or categories of webpages visited over time); and potentially certain types of interaction data about specific webpages visited.

Category 4: Highly sensitive data (highly_sensitive)

Information that directly identifies a person, or if combined with other data could identify a person. Examples include e-mail, usernames, identifiers such as google ad id, apple id, Firefox account, city or country (unless small ones are explicitly filtered out), or certain cookies. It may be embedded within specific website content, such as memory contents, dumps, captures of screen data, or DOM data.

Pings YAML Registry Format

Custom pings sent by an application or library are defined in YAML files which follow the pings.yaml JSON schema.

This files must be parsed by glean_parser at build time in order to generate code in the target language (e.g. Kotlin, Swift, ...). The generated code is what becomes the public API to access the project's custom pings.

For more information on how to introduce the glean_parser build step for a specific language / environment, refer to the "Adding Glean to your project" section of this book.

Note on the naming of these files

Although we refer to pings definitions YAML files as pings.yaml throughout Glean documentation this files may be named whatever makes the most sense for each project and may even be broken down into multiple files, if necessary.

File structure

---
# Schema
$schema: moz://mozilla.org/schemas/glean/pings/2-0-0

# Name
search:
  # Ping parameters
  description: >
    A ping to record search data.
  include_client_id: false
  notification_emails:
    - CHANGE-ME@example.com
  bugs:
    - http://bugzilla.mozilla.org/123456789/
  data_reviews:
    - http://example.com/path/to/data-review

Schema

Declaring the schema at the top of a pings definitions file is required, as it is what indicates that the current file is a pings definitions file.

Name

Ping names are the top-level keys on pings definitions files. One single definition file may contain multiple ping declarations.

Ping names are limited to lowercase letters from the ISO basic Latin alphabet and hyphens and a maximum of 30 characters.

Pings may not contain the words custom or ping in their names. These are considered redundant words and will trigger a REDUNDANT_PING lint failure on glean_parser.

"Capitalization" rules apply to ping names on generated code.

Reserved ping names

The names baseline, metrics, events, deletion-request and all-pings are reserved and may not be used as the name of a custom ping.

Ping parameters

Required parameters

description

A textual description of the purpose of the ping. It may contain markdown syntax.

include_client_id

A boolean indicating whether to include the client_id in the client_info section of the ping.

notification_emails

A list of email addresses to notify for important events with the ping or when people with context or ownership for the ping need to be contacted.

Consider adding both a group email address and an individual who is responsible for this ping.

bugs

A list of bugs (e.g. Bugzilla or GitHub) that are relevant to this ping. For example, bugs that track its original implementation or later changes to it.

Each entry should be the full URL to the bug in an issue tracker. The use of numbers alone is deprecated and will be an error in the future.

data_reviews

A list of URIs to any data collection review responses relevant to the metric.

Optional parameters

send_if_empty

default: false

A boolean indicating if the ping is sent if it contains no metric data.

reasons

default: {}

The reasons that this ping may be sent. The keys are the reason codes, and the values are a textual description of each reason. The ping payload will (optionally) contain one of these reasons in the ping_info.reason field.

The General API

The Glean SDK has a minimal API available on its top-level Glean object called the General API. This API allows, among other things, to enable and disable upload, register custom pings and set experiment data.

Only initialize in the main application!

The Glean SDK should only be initialized from the main application, not individual libraries. If you are adding Glean SDK support to a library, you can safely skip this section.

The API

The Glean SDK provides a general API that supports the following operations. See below for language-specific details.

OperationDescriptionNotes
initializeConfigure and initialize the Glean SDK.Initializing the Glean SDK
setUploadEnabledEnable or disable Glean collection and upload.Toggling upload status
registerPingsRegister custom pings generated from pings.yaml.Custom pings
setExperimentActiveIndicate that an experiment is running.Using the Experiments API
setExperimentInactiveIndicate that an experiment is no longer running..Using the Experiments API

Initializing

The following steps are required for applications using the Glean SDK, but not libraries.

Note

The initialize function must be called, even if telemetry upload is disabled. Glean needs to perform maintenance tasks even when telemetry is disabled, and because Glean does this as part of its initialization, it is required to always call the initialize function. Otherwise, Glean won't be able to clean up collected data, disable queuing of pre-init tasks, or perform other required operations.

This does not apply to special builds where telemetry is disabled at build time. In that case, it is acceptable to not call initialize at all.

Initialize Glean with the correct value for uploadEnabled!

Glean.initialize must always be called with real values. Always pass the user preference, e.g. Glean.initialize(upload=userSettings.telemetry_enabled) or the equivalent for your application. Never call Glean.initialize(upload=true) if true is a placeholder value that later gets reset by Glean.setUploadEnabled(false). Depending on the provided placeholder value, this might trigger the generation of new client ids or the submission of bogus deletion-request pings.

Multiple processes support

The Glean SDK does not support use across multiple processes, and must only be initialized on the application's main process. Initializing in other processes is a no-op. Additionally, Glean must be initialized on the main (UI) thread of the applications main process. Failure to do so will throw an IllegalThreadStateException.

An excellent place to initialize Glean is within the onCreate method of the class that extends Android's Application class.

import org.mozilla.yourApplication.GleanMetrics.GleanBuildInfo
import org.mozilla.yourApplication.GleanMetrics.Pings

class SampleApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        // If you have custom pings in your application, you must register them
        // using the following command. This command should be omitted for
        // applications not using custom pings.
        Glean.registerPings(Pings)

        // Initialize the Glean library.
        Glean.initialize(
            applicationContext,
            // Here, `settings()` is a method to get user preferences, specific to
            // your application and not part of the Glean SDK API.
            uploadEnabled = settings().isTelemetryEnabled,
            buildInfo = GleanBuildInfo.buildInfo
        )
    }
}

The Glean SDK should be initialized as soon as possible, and importantly, before any other libraries in the application start using Glean. Library code should never call Glean.initialize, since it should be called exactly once per application.

Uploads when using Android Components

When the Glean SDK is consumed through Android Components, it is required to configure an HTTP client to be used for upload. For example:

// Requires `org.mozilla.components:concept-fetch`
import mozilla.components.concept.fetch.Client
// Requires `org.mozilla.components:lib-fetch-httpurlconnection`.
// This can be replaced by other implementations, e.g. `lib-fetch-okhttp`
// or an implementation from `browser-engine-gecko`.
import mozilla.components.lib.fetch.httpurlconnection.HttpURLConnectionClient

import mozilla.components.service.glean.config.Configuration
import mozilla.components.service.glean.net.ConceptFetchHttpUploader

val httpClient = ConceptFetchHttpUploader(lazy { HttpURLConnectionClient() as Client })
val config = Configuration(httpClient = httpClient)
Glean.initialize(
   context,
   uploadEnabled = true,
   configuration = config,
   buildInfo = GleanBuildInfo.buildInfo
)
Multiple processes support

The Glean SDK does not support use across multiple processes, and must only be initialized on the application's main process.

An excellent place to initialize Glean is within the application(_:) method of the class that extends the UIApplicationDelegate class.

import Glean
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // If you have custom pings in your application, you must register them
        // using the following command. This command should be omitted for
        // applications not using custom pings.
        Glean.shared.registerPings(GleanMetrics.Pings)

        // Initialize the Glean library.
        Glean.shared.initialize(
            // Here, `Settings` is a method to get user preferences specific to
            // your application, and not part of the Glean SDK API.
            uploadEnabled = Settings.isTelemetryEnabled
        )
    }
}

The Glean SDK should be initialized as soon as possible, and importantly, before any other libraries in the application start using Glean. Library code should never call Glean.shared.initialize, since it should be called exactly once per application.

The main control for the Glean SDK is on the glean.Glean singleton.

The Glean SDK should be initialized as soon as possible, and importantly, before any other libraries in the application start using Glean. Library code should never call Glean.initialize, since it should be called exactly once per application.

from glean import Glean

Glean.initialize(
    application_id="my-app-id",
    application_version="0.1.0",
    upload_enabled=True,
)

Additional configuration is available on the glean.Configuration object, which can be passed into Glean.initialize().

Unlike Android and Swift, the Python bindings do not automatically send any pings. See the custom pings documentation about adding custom pings and sending them.

Multiple processes support

The Glean SDK does not support use across multiple processes, and must only be initialized on the application's main process.

The Glean SDK should be initialized as soon as possible, and importantly, before any other libraries in the application start using Glean. Library code should never call Glean.initialize, since it should be called exactly once per application.

use glean::{ClientInfoMetrics, Configuration};
let cfg = Configuration {
    data_path,
    application_id: "my-app-id".into(),
    upload_enabled: true,
    max_events: None,
    delay_ping_lifetime_io: false,
    channel: None,
    server_endpoint: Some("https://incoming.telemetry.mozilla.org".into()),
    uploader: None,
    use_core_mps: true,
};

let client_info = ClientInfoMetrics {
    app_build: env!("CARGO_PKG_VERSION").to_string(),
    app_display_version: env!("CARGO_PKG_VERSION").to_string(),
};

glean::initialize(cfg, client_info);

Unlike in other implementations, the Rust language bindings do not provide a default uploader. See PingUploader for details.

The main control for Glean is on the Glean singleton.

The Glean.js library should be initialized as soon as possible when the product using it is started.

// Glean.js for webextensions: the following code
// runs in the background script.
import Glean from "@mozilla/glean/webext";

Glean.initialize(
    "my-app-id",
    true, // uploadEnabled
    {
      appDisplayVersion: "0.1.0"
    }
);

What happens after Glean is initialized?

Once initialized, if upload is enabled, the Glean SDK will automatically start collecting baseline metrics. If upload is disabled, any persisted metrics, events and pings (other than first_run_date and first_run_hour) are cleared, and subsequent calls to record metrics will be no-ops.

Release channels

If the application has the concept of release channels and knows which channel it is on at run-time, then it can provide the Glean SDK with this information by setting it as part of the Configuration object parameter of the initialize method.

Behavior when uninitialized

Metric recording that happens before the Glean SDK is initialized is queued and applied at initialization. To avoid unbounded memory growth the queue is bounded (currently to a maximum of 100 tasks), and further recordings are dropped. The number of recordings dropped, if any, is recorded in the glean.error.preinit_tasks_overflow metric.

Custom ping submission will not fail before initialization. Collection and upload of the custom ping is delayed until the Glean SDK is initialized. Built-in pings are only available after initialization.

Toggling upload status

Glean.setUploadEnabled() should be called in response to the user enabling or disabling telemetry.

Do not call setUploadEnabled before initializing

If called before Glean.initialize() the call to Glean.setUploadEnabled() will be ignored. Set the initial state using uploadEnabled on Glean.initialize().

Glean.shared.setUploadEnabled() should be called in response to the user enabling or disabling telemetry.

Do not call setUploadEnabled before initializing

If called before Glean.shared.initialize() the call to Glean.shared.setUploadEnabled() will be ignored. Set the initial state using uploadEnabled on Glean.shared.initialize().

Glean.set_upload_enabled() should be called in response to the user enabling or disabling telemetry.

Do not call set_upload_enabled before initializing

If called before Glean.initialize() the call to Glean.set_upload_enabled() will be ignored. Set the initial state using upload_enabled on Glean.initialize().

Glean.setUploadEnabled() should be called in response to the user enabling or disabling telemetry.

Do not call setUploadEnabled before initializing

If called before Glean.initialize() the call to Glean.setUploadEnabled() will be ignored. Set the initial state using uploadEnabled on Glean.initialize().

The application should provide some form of user interface to call this method.

When going from enabled to disabled, all pending events, metrics and pings are cleared, except for first_run_date and first_run_hour. When re-enabling, core Glean metrics will be recomputed at that time.

Using the experiments API

The Glean SDK supports tagging all its pings with experiments annotations. The annotations are useful to report that experiments were active at the time the measurement were collected. The annotations are reported in the optional experiments entry in the ping_info section of all the Glean SDK pings.

Experiment annotations are not persisted

The experiment annotations set through this API are not persisted by the Glean SDK. The application or consuming library is responsible for setting the relevant experiment annotations at each run.

It's not required to define experiment IDs and branches

Experiment IDs and branches don't need to be pre-defined in the Glean SDK registry files. Please also note that the extra map is a non-nested arbitrary String to String map. It also has limits on the size of the keys and values defined below.

Recording API

setExperimentActive

Annotates Glean pings with experiment data.

// Annotate Glean pings with experiments data.
Glean.setExperimentActive(
  experimentId = "blue-button-effective",
  branch = "branch-with-blue-button",
  extra: mapOf(
    "buttonLabel" to "test"
  )
)
// Annotate Glean pings with experiments data.
Glean.shared.setExperimentActive(
  experimentId: "blue-button-effective",
  branch: "branch-with-blue-button",
  extra: ["buttonLabel": "test"]
)
from glean import Glean

Glean.set_experiment_active(
  experiment_id="blue-button-effective",
  branch="branch-with-blue-button",
  extra={
    "buttonLabel": "test"
  }
)
let mut extra = HashMap::new();
extra.insert("buttonLabel".to_string(), "test".to_string());
glean::set_experiment_active(
    "blue-button-effective".to_string(),
    "branch-with-blue-button".to_string(),
    Some(extra),
);

C++

At present there is no dedicated C++ Experiments API for Firefox Desktop

If you require one, please file a bug.

JavaScript

let FOG = Cc["@mozilla.org/toolkit/glean;1"].createInstance(Ci.nsIFOG);
FOG.setExperimentActive(
  "blue-button-effective",
  "branch-with-blue-button",
  {"buttonLabel": "test"}
);

Limits

  • experimentId, branch, and the keys and values of the extra field are fixed at a maximum length of 100 bytes. Longer strings are truncated. (Specifically, length is measured in the number of bytes when the string is encoded in UTF-8.)
  • extra map is limited to 20 entries. If passed a map which contains more elements than this, it is truncated to 20 elements. WARNING Which items are truncated is nondeterministic due to the unordered nature of maps. What's left may not necessarily be the first elements added.

Recorded errors

  • invalid_value: If the values of experimentId or branch are truncated for length, if the keys or values in the extra map are truncated for length, or if the extra map is truncated for the number of elements.

setExperimentInactive

Removes the experiment annotation. Should be called when the experiment ends.

Glean.setExperimentInactive("blue-button-effective")
Glean.shared.setExperimentInactive(experimentId: "blue-button-effective")
from glean import Glean

Glean.set_experiment_inactive("blue-button-effective")
glean::set_experiment_inactive("blue-button-effective".to_string());

C++

At present there is no dedicated C++ Experiments API for Firefox Desktop

If you require one, please file a bug.

JavaScript

let FOG = Cc["@mozilla.org/toolkit/glean;1"].createInstance(Ci.nsIFOG);
FOG.setExperimentInactive("blue-button-effective");

Testing API

testIsExperimentActive

Reveals if the experiment is annotated in Glean pings.

assertTrue(Glean.testIsExperimentActive("blue-button-effective"))
XCTAssertTrue(Glean.shared.testIsExperimentActive(experimentId: "blue-button-effective"))
from glean import Glean

assert Glean.test_is_experiment_active("blue-button-effective")
assert!(glean::test_is_experiment_active("blue-button-effective".to_string());

testGetExperimentData

Returns the recorded experiment data including branch and extras.

assertEquals(
  "branch-with-blue-button", Glean.testGetExperimentData("blue-button-effective")?.branch
)
XCTAssertEqual(
  "branch-with-blue-button",
  Glean.testGetExperimentData(experimentId: "blue-button-effective")?.branch
)
from glean import Glean

assert (
    "branch-with-blue-button" ==
    Glean.test_get_experiment_data("blue-button-effective").branch
)
assert_eq!(
    "branch-with-blue-button",
    glean::test_get_experiment_data("blue-button-effective".to_string()).branch,
);

C++

At present there is no dedicated C++ Experiments API for Firefox Desktop

If you require one, please file a bug.

JavaScript

let FOG = Cc["@mozilla.org/toolkit/glean;1"].createInstance(Ci.nsIFOG);
Assert.equals(
  "branch-with-blue-button",
  FOG.testGetExperimentData("blue-button-effective").branch
);

Reference

Registering custom pings

After defining custom pings The Glean SDK build generates code from pings.yaml in a Pings object, which must be instantiated so Glean can send pings by name.

API

registerPings

Loads custom ping metadata into your application or library

In Kotlin, this object must be registered with the Glean SDK from your startup code before calling Glean.initialize (such as in your application's onCreate method or a function called from that method).

import org.mozilla.yourApplication.GleanMetrics.Pings

override fun onCreate() {
    Glean.registerPings(Pings)

    Glean.initialize(applicationContext, uploadEnabled = true)
}

In Swift, this object must be registered with the Glean SDK from your startup code before calling Glean.shared.initialize (such as in your application's UIApplicationDelegate application(_:didFinishLaunchingWithOptions:) method or a function called from that method).

import Glean

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Glean.shared.registerPings(GleanMetrics.Pings)

        Glean.shared.initialize(uploadEnabled = true)
    }
}

For Python, the pings.yaml file must be available and loaded at runtime.

While the Python language bindings do provide a Glean.register_ping_type function, if your project is a script (i.e. just Python files in a directory), you can load the pings.yaml before calling Glean.initialize using:

from glean import load_pings

pings = load_pings("pings.yaml")

Glean.initialize(
    application_id="my-app-id",
    application_version="0.1.0",
    upload_enabled=True,
)

If your project is a distributable Python package, you need to include the pings.yaml file using one of the myriad ways to include data in a Python package and then use pkg_resources.resource_filename() to get the filename at runtime.

from glean import load_pings
from pkg_resources import resource_filename

pings = load_pings(resource_filename(__name__, "pings.yaml"))

In Rust custom pings need to be registered individually. This should be done before calling glean::initialize.

use your_glean_metrics::pings;

glean::register_ping_type(&pings::custom_ping);
glean::register_ping_type(&pings::search);
glean::initialize(cfg, client_info);

Shut down

Provides a way for users to gracefully shut down Glean, by blocking until it is finished performing pending tasks such as recording metrics and uploading pings.

How the Glean SDKs execute tasks

Most calls to Glean APIs are dispatched1. This strategy is adopted because most tasks performed by the Glean SDKs involve file system read or write operations, HTTP requests and other time consuming actions.

Each Glean SDK has an internal structure called "Dispatcher" which makes sure API calls get executed in the order they were called, while not requiring the caller to block on the completion of each of these tasks.

1

Here, this term indicates the tasks are run asynchronously in JavaScript or in a different thread for all other SDKs.

API

shutdown

fn main() {
    let cfg = Configuration {
        // ...
    };
    let client_info = /* ... */;
    glean::initialize(cfg, client_info);

    // Ensure the dispatcher thread winds down
    glean::shutdown();
}
import Glean from "@mozilla/glean/webext";

async function onUninstall() {
  // Flips Glean upload status to `false`,
  // which triggers sending of a `deletion-request` ping.
  Glean.setUploadEnabled(false);

  // Block on shut down to guarantee all pending pings
  // (including the `deletion-request` sent above)
  // are sent before the extension is uninstalled.
  await Glean.shutdown();

  // Uninstall browser extension without asking for user approval before doing so.
  await browser.management.uninstallSelf({ showConfirmDialog: false });
}

The shutdown API is available for all JavaScript targets, even though the above example is explicitly using the webext target.

Reference

Debugging

Different platforms have different ways to enable each debug functionality. They may be enabled

Platform Specific Information

Check out the platform specific guides on how to use Glean's debug functionalities.

  1. Debugging Android applications using the Glean SDK
  2. Debugging iOS applications using the Glean SDK
  3. Debugging Python applications using the Glean SDK
  4. Debugging JavaScript applications using Glean.js

Features

The Glean SDK provides four debugging features.

Log Pings

This is either true or false and will cause all subsequent pings that are submitted, to also be echoed to the device's log.

Debug View Tag

This will tag all subsequent outgoing pings with the provided value, in order to identify them in the Glean Debug View.

Source Tags

This will tag all subsequent outgoing pings with a maximum of 5 comma-separated tags.

Send Pings

This feature is only available through the Android and iOS debug tools.

This expects the name of a ping and forces its immediate submission.

Log pings

This flag causes all subsequent pings that are submitted to also be echoed to the product's log.

Once enabled, the only way to disable this feature is to restart or manually reset the application.

On how to access logs

The Glean SDK logs warnings and errors through platform-specific logging frameworks. See the platform-specific instructions for information on how to view the logs on the platform you are on.

Limits

API

setLogPings

Enables or disables ping logging.

This API can safely be called before Glean.initialize. The tag will be applied upon initialization in this case.

import Glean

Glean.shared.setLogPings(true)
use glean;

glean.set_log_pings(true);
import Glean from "@mozilla/glean/<platform>";

Glean.setLogPings(true);

Environment variable

GLEAN_LOG_PINGS

It is also possible to enable ping logging through the GLEAN_LOG_PINGS environment variable.

This variable must be set at runtime, not at compile time. It will be checked upon Glean initialization.

Xcode IDE scheme editor popup screenshot

To set environment variables to the process running your app in an iOS device or emulator you need to edit the scheme for your app. In the Xcode IDE, use the shortcut Cmd + < to open the scheme editor popup. The environment variables editor is under the Arguments tab on this popup.

$ GLEAN_LOG_PINGS=true python my_application.py
$ GLEAN_LOG_PINGS=true cargo run
$ GLEAN_LOG_PINGS=true ./mach run

Debug View Tag

Tag all subsequent outgoing pings with a given value, in order to redirect them to the Glean Debug View.

"To tag" a ping with the Debug View Tag means that the ping request will contain the X-Debug-Id header with the given tag.

Once enabled, the only way to disable this feature is to restart or manually reset the application.

Limits

API

setDebugViewTag

Sets the Debug View Tag to a given value.

This API can safely be called before Glean.initialize. The tag will be applied upon initialization in this case.

import Glean

Glean.shared.setDebugViewTag("my-tag")
use glean;

glean.set_debug_view_tag("my-tag");
import Glean from "@mozilla/glean/<platform>";

Glean.setDebugViewTag("my-tag");

Environment variable

GLEAN_DEBUG_VIEW_TAG

It is also possible to set the debug view tag through the GLEAN_DEBUG_VIEW_TAG environment variable.

This variable must be set at runtime, not at compile time. It will be checked upon Glean initialization.

Xcode IDE scheme editor popup screenshot

To set environment variables to the process running your app in an iOS device or emulator you need to edit the scheme for your app. In the Xcode IDE, use the shortcut Cmd + < to open the scheme editor popup. The environment variables editor is under the Arguments tab on this popup.

$ GLEAN_DEBUG_VIEW_TAG="my-tag" python my_application.py
$ GLEAN_DEBUG_VIEW_TAG="my-tag" cargo run
$ GLEAN_DEBUG_VIEW_TAG="my-tag" ./mach run

Source Tags

Tag all subsequent outgoing pings with a maximum of 5 comma-separated tags.

"To tag" a ping with Source Tags means that the ping request will contain the X-Source-Tags header with a comma separated list of the given tags.

Once enabled, the only way to disable this feature is to restart or manually reset the application.

Limits

API

setSourceTags

Sets the Source Tags to a given value.

This API can safely be called before Glean.initialize. The tag will be applied upon initialization in this case.

import Glean

Glean.shared.setSourceTags(["my-tag", "your-tag", "our-tag"])
use glean;

glean.set_source_tags(["my-tag", "your-tag", "our-tag"]);
import Glean from "@mozilla/glean/<platform>";

Glean.setSourceTags(["my-tag", "your-tag", "our-tag"]);

Environment variable

GLEAN_SOURCE_TAGS

It is also possible to set the debug view tag through the GLEAN_SOURCE_TAGS environment variable.

This variable must be set at runtime, not at compile time. It will be checked upon Glean initialization.

Xcode IDE scheme editor popup screenshot

To set environment variables to the process running your app in an iOS device or emulator you need to edit the scheme for your app. In the Xcode IDE, use the shortcut Cmd + < to open the scheme editor popup. The environment variables editor is under the Arguments tab on this popup.

$ GLEAN_SOURCE_TAGS=my-tag,your-tag,our-tag python my_application.py
$ GLEAN_SOURCE_TAGS=my-tag,your-tag,our-tag cargo run
$ GLEAN_SOURCE_TAGS=my-tag,your-tag,our-tag ./mach run

Metrics

Not sure which metric type to use? These docs contain a series of questions that can help. Reference information about each metric type is linked below.

The parameters available that apply to any metric type are in the metric parameters page.

There are different metrics to choose from, depending on what you want to achieve:

Labeled metrics

There are two types of metrics listed above - labeled and unlabeled metrics. If a metric is labeled, it means that for a single metric entry you define in metrics.yaml, you can record into multiple metrics under the same name, each of the same type and identified by a different string label.

This is useful when you need to break down metrics by a label known at build time or run time. For example:

Labeled metrics come in two forms:

Note: Be careful with using arbitrary strings as labels and make sure they can't accidentally contain identifying data (like directory paths or user input).

Label format

To ensure maximum support in database columns, labels must be made up of dot-separated identifiers with lowercase ASCII alphanumerics, containing underscores and dashes.

Specifically, they must conform to this regular expression:

^[a-z_][a-z0-9_-]{0,29}(\\.[a-z_][a-z0-9_-]{0,29})*$

Adding or changing metric types

Glean has a well-defined process for requesting changes to existing metric types or suggesting the implementation of new metric types:

  1. Glean consumers need to file a bug in the Data platforms & tools::Glean Metric Types component, filling in the provided form;
  2. The triage owner of the Bugzilla component prioritizes this within 6 business days and kicks off the decision making process.
  3. Once the decision process is completed, the bug is closed with a comment outlining the decision that was made.

Boolean

Boolean metrics are used for reporting simple flags.

Recording API

set

Sets a boolean metric to a specific value.

import org.mozilla.yourApplication.GleanMetrics.Flags

Flags.a11yEnabled.set(System.isAccesibilityEnabled())
import org.mozilla.yourApplication.GleanMetrics.Flags;

Flags.INSTANCE.a11yEnabled.set(System.isAccessibilityEnabled());
Flags.a11yEnabled.set(self.isAccessibilityEnabled)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.flags.a11y_enabled.set(is_accessibility_enabled())
use glean_metrics;

flags::a11y_enabled.set(system.is_accessibility_enabled());
import * as flags from "./path/to/generated/files/flags.js";

flags.a11yEnabled.set(this.isAccessibilityEnabled());

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::flags::a11y_enabled.Set(false);

JavaScript

Glean.flags.a11yEnabled.set(false);

Recorded errors

N/A

Testing API

testGetValue

Gets the recorded value for a given boolean metric.

import org.mozilla.yourApplication.GleanMetrics.Flags

assertTrue(Flags.a11yEnabled.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Flags;

assertTrue(Flags.INSTANCE.a11yEnabled.testGetValue());
@testable import Glean

XCTAssertTrue(try Flags.a11yEnabled.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert True is metrics.flags.a11y_enabled.test_get_value()
use glean_metrics;

assert!(flags::a11y_enabled.test_get_value(None).unwrap());
import * as flags from "./path/to/generated/files/flags.js";

assert(await flags.a11yEnabled.testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_EQ(false, mozilla::glean::flags::a11y_enabled.TestGetValue().value());

JavaScript

Assert.equal(false, Glean.flags.a11yEnabled.testGetValue());

testHasValue

Whether or not any value was recorded for a given boolean metric.

import org.mozilla.yourApplication.GleanMetrics.Flags

assertTrue(Flags.a11yEnabled.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Flags;

assertTrue(Flags.INSTANCE.a11yEnabled.testHasValue());
@testable import Glean

XCTAssertTrue(try Flags.a11yEnabled.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert True is metrics.flags.a11y_enabled.test_has_value()

Metric parameters

Example boolean metric definition:

flags:
  a11y_enabled:
    type: boolean
    description: >
      Records whether a11y is enabled on the device.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

N/A

Data questions

Reference

Labeled Booleans

Labeled booleans are used to record different related boolean flags.

Recording API

set

Sets one of the labels in a labeled boolean metric to a specific value.

import org.mozilla.yourApplication.GleanMetrics.Accessibility

Accessibility.features["screen_reader"].set(isScreenReaderEnabled())
Accessibility.features["high_contrast"].set(isHighContrastEnabled())
import org.mozilla.yourApplication.GleanMetrics.Accessibility;

Acessibility.INSTANCE.features["screen_reader"].set(isScreenReaderEnabled());
Acessibility.INSTANCE.features["high_contrast"].set(isHighContrastEnabled());
Accessibility.features["screen_reader"].set(isScreenReaderEnabled())
Accessibility.features["high_contrast"].set(isHighContrastEnabled())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.accessibility.features["screen_reader"].set(is_screen_reader_enabled())
metrics.accessibility.features["high_contrast"].set(is_high_contrast_enabled())

#![allow(unused)]
fn main() {
use glean_metrics;

accessibility::features.get("screen_reader").set(is_screen_reader_enabled());
accessibility::features.get("high_contrast").set(is_high_contrast_enabled());
}
import * as acessibility from "./path/to/generated/files/acessibility.js";

acessibility.features["screen_reader"].set(this.isScreenReaderEnabled());
acessibility.features["high_contrast"].set(this.isHighContrastEnabled());

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::accessibility::features.Get("screen_reader"_ns).Set(true);
mozilla::glean::accessibility::features.Get("high_contrast"_ns).Set(false);

JavaScript

Glean.accessibility.features.screen_reader.set(true);
Glean.accessibility.features["high_contrast"].set(false);

Recorded Errors

Testing API

testGetValue

Gets the recorded value for a given label in a labeled boolean metric.

import org.mozilla.yourApplication.GleanMetrics.Accessibility

// Do the booleans have the expected values?
assertEquals(True, Accessibility.features["screen_reader"].testGetValue())
assertEquals(False, Accessibility.features["high_contrast"].testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Accessibility;

// Do the booleans have the expected values?
assertEquals(True, Acessibility.INSTANCE.features["screen_reader"].testGetValue());
assertEquals(False, Acessibility.INSTANCE.features["high_contrast"].testGetValue());
@testable import Glean

// Do the booleans have the expected values?
XCTAssertEqual(true, try Accessibility.features["screen_reader"].testGetValue())
XCTAssertEqual(false, try Accessibility.features["high_contrast"].testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Do the booleans have the expected values?
assert metrics.accessibility.features["screen_reader"].test_get_value()
assert not metrics.accessibility.features["high_contrast"].test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;

// Do the booleans have the expected values?
assert!(accessibility::features.get("screen_reader").test_get_value(None).unwrap());
assert!(!accessibility::features.get("high_contrast").test_get_value(None).unwrap());
}
import * as accessibility from "./path/to/generated/files/acessibility.js";

assert(await accessibility.features["screen_reader"].testGetValue());
assert(!(await accessibility.features["high_contrast"].testGetValue()));

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_EQ(
    true,
    mozilla::glean::accessibility::features.Get("screen_reader"_ns).TestGetValue().unwrap().ref());
ASSERT_EQ(
    false,
    mozilla::glean::accessibility::features.Get("high_contrast"_ns).TestGetValue().unwrap().ref());

JavaScript

Assert.equal(true, Glean.accessibility.features["screen_reader"].testGetValue());
Assert.equal(false, Glean.accessibility.features.high_contrast.testGetValue());

testHasValue

Whether or not any value was recorded for a given label in a labeled boolean metric.

import org.mozilla.yourApplication.GleanMetrics.Accessibility

// Was anything recorded?
assertTrue(Accessibility.features["screen_reader"].testHasValue())
assertTrue(Accessibility.features["high_contrast"].testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Accessibility;

// Was anything recorded?
assertEquals(True, Acessibility.INSTANCE.features["screen_reader"].testHasValue());
assertEquals(True, Acessibility.INSTANCE.features["high_contrast"].testHasValue());
@testable import Glean

// Was anything recorded?
XCTAssert(Accessibility.features["screen_reader"].testHasValue())
XCTAssert(Accessibility.features["high_contrast"].testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was anything recorded?
assert metrics.accessibility.features["screen_reader"].test_has_value()
assert metrics.accessibility.features["high_contrast"].test_has_value()

testGetNumRecordedErrors

Gets the number of errors recorded for a given labeled boolean metric in total.

import org.mozilla.yourApplication.GleanMetrics.Accessibility

// Did we record any invalid labels?
assertEquals(0, Accessibility.features.testGetNumRecordedErrors(ErrorType.InvalidLabel))
import org.mozilla.yourApplication.GleanMetrics.Accessibility;

// Did we record any invalid labels?
assertEquals(0, Acessibility.INSTANCE.features.testGetNumRecordedErrors());
@testable import Glean

// Were there any invalid labels?
XCTAssertEqual(0, Accessibility.features.testGetNumRecordedErrors(.invalidLabel))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Did we record any invalid labels?
assert 0 == metrics.accessibility.features.test_get_num_recorded_errors(
    ErrorType.INVALID_LABEL
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

// Did we record any invalid labels?
assert_eq!(
  1,
  accessibility::features.test_get_num_recorded_errors(
    ErrorType::InvalidLabel
  )
);
}
import * as accessibility from "./path/to/generated/files/acessibility.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert(
  1,
  await accessibility.features.testGetNumRecordedErrors(ErrorType.InvalidLabel)
);

Metric parameters

Example labeled boolean metric definition:

accessibility:
  features:
    type: labeled_boolean
    description: >
      a11y features enabled on the device.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    labels:
      - screen_reader
      - high_contrast
      ...

Extra metric parameters

labels

Labeled metrics may have an optional labels parameter, containing a list of known labels. The labels in this list must match the following requirements:

Important

If the labels are specified in the metrics.yaml, using any label not listed in that file will be replaced with the special value __other__.

If the labels are not specified in the metrics.yaml, only 16 different dynamic labels may be used, after which the special value __other__ will be used.

Removing or changing labels, including their order in the registry file, is permitted. Avoid reusing labels that were removed in the past. It is best practice to add documentation about removed labels to the description field so that analysts will know of their existence and meaning in historical data. Special care must be taken when changing GeckoView metrics sent through the Glean SDK, as the index of the labels is used to report Gecko data through the Glean SDK.

Data questions

Reference

Counter

Used to count how often something happens, say how often a certain button was pressed. A counter always starts from 0. Each time you record to a counter, its value is incremented. Unless incremented by a positive value, a counter will not be reported in pings, that means: the value 0 is never sent in a ping.

If you find that you need to control the actual value sent in the ping, you may be measuring something, not just counting something, and a Quantity metric may be a better choice.

Let the Glean metric do the counting

When using a counter metric, it is important to let the Glean metric do the counting. Using your own variable for counting and setting the counter yourself could be problematic because it will be difficult to reset the value at the exact moment that the value is sent in a ping. Instead, just use counter.add to increment the value and let Glean handle resetting the counter.

Recording API

add

Increases the counter by a certain amount. If no amount is passed it defaults to 1.

import org.mozilla.yourApplication.GleanMetrics.Controls

Controls.refreshPressed.add() // Adds 1 to the counter.
Controls.refreshPressed.add(5) // Adds 5 to the counter.
import org.mozilla.yourApplication.GleanMetrics.Controls;

Controls.INSTANCE.refreshPressed.add(); // Adds 1 to the counter.
Controls.INSTANCE.refreshPressed.add(5); // Adds 5 to the counter.
Controls.refreshPressed.add() // Adds 1 to the counter.
Controls.refreshPressed.add(5) // Adds 5 to the counter.
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.controls.refresh_pressed.add()  # Adds 1 to the counter.
metrics.controls.refresh_pressed.add(5) # Adds 5 to the counter.
use glean_metrics;

controls::refresh_pressed.add(1); // Adds 1 to the counter.
controls::refresh_pressed.add(5); // Adds 5 to the counter.
import * as controls from "./path/to/generated/files/controls.js";

controls.refreshPressed.add(); // Adds 1 to the counter.
controls.refreshPressed.add(5); // Adds 5 to the counter.

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::controls::refresh_pressed.Add(1);
mozilla::glean::controls::refresh_pressed.Add(5);

JavaScript

Glean.controls.refreshPressed.add(1);
Glean.controls.refreshPressed.add(5);

Recorded errors

Limits

Testing API

testGetValue

Gets the recorded value for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Controls

assertEquals(6, Controls.refreshPressed.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Controls;

assertEquals(6, Controls.INSTANCE.refreshPressed.testGetValue());
@testable import Glean

XCTAssertEqual(6, try Controls.refreshPressed.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert 6 == metrics.controls.refresh_pressed.test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;

assert_eq!(6, controls::refresh_pressed.test_get_value(None).unwrap());
}
import * as controls from "./path/to/generated/files/controls.js";

assert.strictEqual(6, await controls.refreshPressed.testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_TRUE(mozilla::glean::controls::refresh_pressed.TestGetValue().isOk());
ASSERT_EQ(6, mozilla::glean::controls::refresh_pressed.TestGetValue().unwrap().value());

JavaScript

// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.equal(6, Glean.controls.refreshPressed.testGetValue());

testHasValue

Whether or not any value was recorded for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Controls

assertTrue(Controls.refreshPressed.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Controls;

assertTrue(Controls.INSTANCE.refreshPressed.testHasValue());
@testable import Glean

XCTAssert(Controls.refreshPressed.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.controls.refresh_pressed.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Controls

assertEquals(
    1, Controls.refreshPressed.testGetNumRecordedErrors(ErrorType.InvalidValue)
)
import org.mozilla.yourApplication.GleanMetrics.Controls;

assertEquals(
    1, Controls.INSTANCE.refreshPressed.testGetNumRecordedErrors(ErrorType.InvalidValue)
);
XCTAssertEqual(1, Controls.refreshPressed.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

from glean.testing import ErrorType

assert 1 == metrics.controls.refresh_pressed.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

assert_eq!(
  1,
  controls::refresh_pressed.test_get_num_recorded_errors(
    ErrorType::InvalidValue
  )
);
}
import * as controls from "./path/to/generated/files/controls.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  1,
  await controls.refreshPressed.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric parameters

Example counter metric definition:

controls:
  refresh_pressed:
    type: counter
    description: >
      Counts how often the refresh button is pressed.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

N/A

Data questions

Reference

Labeled Counters

Labeled counters are used to record different related counts that should sum up to a total. Each counter always starts from 0. Each time you record to a labeled counter, its value is incremented. Unless incremented by a positive value, a counter will not be reported in pings, that means: the value 0 is never sent in a ping.

Recording API

add

Increases one of the labels in a labeled counter metric by a certain amount. If no amount is passed it defaults to 1.

import org.mozilla.yourApplication.GleanMetrics.Stability

Stability.crashCount["uncaught_exception"].add() // Adds 1 to the "uncaught_exception" counter.
Stability.crashCount["native_code_crash"].add(3) // Adds 3 to the "native_code_crash" counter.
import org.mozilla.yourApplication.GleanMetrics.Stability;

Stability.INSTANCE.crashCount["uncaught_exception"].add(); // Adds 1 to the "uncaught_exception" counter.
Stability.INSTANCE.crashCount["native_code_crash"].add(3); // Adds 3 to the "native_code_crash" counter.
Stability.crashCount["uncaught_exception"].add() // Adds 1 to the "uncaught_exception" counter.
Stability.crashCount["native_code_crash"].add(3) // Adds 3 to the "native_code_crash" counter.
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Adds 1 to the "uncaught_exception" counter.
metrics.stability.crash_count["uncaught_exception"].add()
# Adds 3 to the "native_code_crash" counter.
metrics.stability.crash_count["native_code_crash"].add(3)

#![allow(unused)]
fn main() {
use glean_metrics;

stability::crash_count.get("uncaught_exception").add(1); // Adds 1 to the "uncaught_exception" counter.
stability::crash_count.get("native_code_crash").add(3); // Adds 3 to the "native_code_crash" counter.
}
import * as stability from "./path/to/generated/files/stability.js";

// Adds 1 to the "uncaught_exception" counter.
stability.crashCount["uncaught_exception"].add();
// Adds 3 to the "native_code_crash" counter.
stability.crashCount["native_code_crash"].add(3);

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::stability::crash_count.Get("uncaught_exception"_ns).Add(1);
mozilla::glean::stability::crash_count.Get("native_code_crash"_ns).Add(3);

JavaScript

Glean.stability.crashCount.uncaught_exception.add(1);
Glean.stability.crashCount["native_code_crash"].add(3);

Errors recorded

Limits

Testing API

testGetValue

Gets the recorded value for a given label in a labeled counter metric.

import org.mozilla.yourApplication.GleanMetrics.Stability

// Do the counters have the expected values?
assertEquals(1, Stability.crashCount["uncaught_exception"].testGetValue())
assertEquals(3, Stability.crashCount["native_code_crash"].testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Stability;

// Do the counters have the expected values?
assertEquals(1, Stability.INSTANCE.crashCount["uncaught_exception"].testGetValue());
assertEquals(3, Stability.INSTANCE.crashCount["native_code_crash"].testGetValue());
@testable import Glean

// Do the counters have the expected values?
XCTAssertEqual(1, try Stability.crashCount["uncaught_exception"].testGetValue())
XCTAssertEqual(3, try Stability.crashCount["native_code_crash"].testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Do the counters have the expected values?
assert 1 == metrics.stability.crash_count["uncaught_exception"].test_get_value()
assert 3 == metrics.stability.crash_count["native_code_crash"].test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;

// Do the counters have the expected values?
assert_eq!(1, stability::crash_count.get("uncaught_exception").test_get_value().unwrap());
assert_eq!(3, stability::crash_count.get("native_code_crash").test_get_value().unwrap());
}
import * as stability from "./path/to/generated/files/stability.js";

// Do the counters have the expected values?
assert.strictEqual(1, await stability.crashCount["uncaught_exception"].testGetValue());
assert.strictEqual(3, await stability.crashCount["native_code_crash"].testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_EQ(
    1,
    mozilla::glean::stability::crash_count.Get("uncaught_exception"_ns).TestGetValue().unwrap().ref());
ASSERT_EQ(
    3,
    mozilla::glean::stability::crash_count.Get("native_code_crash"_ns).TestGetValue().unwrap().ref());

JavaScript

Assert.equal(1, Glean.stability.crashCount["uncaught_exception"].testGetValue());
Assert.equal(3, Glean.stability.crashCount.native_code_crash.testGetValue());

testHasValue

Whether or not any value was recorded for a given label in a labeled counter metric.

import org.mozilla.yourApplication.GleanMetrics.Stability

// Was anything recorded?
assertTrue(Stability.crashCount["uncaught_exception"].testHasValue())
assertTrue(Stability.crashCount["native_code_crash"].testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Stability;

// Was anything recorded?
assertTrue(Stability.INSTANCE.crashCount["uncaught_exception"].testHasValue());
assertTrue(Stability.INSTANCE.crashCount["native_code_crash"].testHasValue());
@testable import Glean

// Was anything recorded?
XCTAssert(Stability.crashCount["uncaught_exception"].testHasValue())
XCTAssert(Stability.crashCount["native_code_crash"].testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was anything recorded?
assert metrics.stability.crash_count["uncaught_exception"].test_has_value()
assert metrics.stability.crash_count["native_code_crash"].test_has_value()

testGetNumRecordedErrors

Gets the number of errors recorded for a given labeled counter metric in total.

import org.mozilla.yourApplication.GleanMetrics.Stabilit

// Were there any invalid labels?
assertEquals(0, Stability.crashCount.testGetNumRecordedErrors(ErrorType.InvalidLabel))
import org.mozilla.yourApplication.GleanMetrics.Stability;

// Were there any invalid labels?
assertEquals(0, Stability.INSTANCE.crashCount.testGetNumRecordedErrors(ErrorType.InvalidLabel));
@testable import Glean

// Were there any invalid labels?
XCTAssertEqual(0, Stability.crashCount.testGetNumRecordedErrors(.invalidLabel))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Were there any invalid labels?
assert 0 == metrics.stability.crash_count.test_get_num_recorded_errors(
    ErrorType.INVALID_LABEL
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

// Were there any invalid labels?
assert_eq!(
  0,
  stability::crash_count.test_get_num_recorded_errors(
    ErrorType::InvalidLabel
  )
);
}
import * as stability from "./path/to/generated/files/stability.js";
import { ErrorType } from "@mozilla/glean/<platform>";

// Were there any invalid labels?
assert(
  0,
  await stability.crashCount.testGetNumRecordedErrors(ErrorType.InvalidLabel)
);

Metric parameters

Example labeled counter metric definition:

accessibility:
  features:
    type: labeled_counter
    description: >
      Counts the number of crashes that occur in the application.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    labels:
      - uncaught_exception
      - native_code_crash
      ...

Extra metric parameters

labels

Labeled metrics may have an optional labels parameter, containing a list of known labels. The labels in this list must match the following requirements:

Important

If the labels are specified in the metrics.yaml, using any label not listed in that file will be replaced with the special value __other__.

If the labels are not specified in the metrics.yaml, only 16 different dynamic labels may be used, after which the special value __other__ will be used.

Removing or changing labels, including their order in the registry file, is permitted. Avoid reusing labels that were removed in the past. It is best practice to add documentation about removed labels to the description field so that analysts will know of their existence and meaning in historical data. Special care must be taken when changing GeckoView metrics sent through the Glean SDK, as the index of the labels is used to report Gecko data through the Glean SDK.

Data questions

Reference

Strings

String metrics allow recording a Unicode string value with arbitrary content.

This metric type does not support recording JSON blobs - please get in contact with the Glean SDK team if you're missing a type.

Important

Be careful using arbitrary strings and make sure they can't accidentally contain identifying data (like directory paths or user input).

Recording API

set

Set a string metric to a specific value.

import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Record a value into the metric.
SearchDefault.name.set("duck duck go")
// If it changed later, you can record the new value:
SearchDefault.name.set("wikipedia")
import org.mozilla.yourApplication.GleanMetrics.SearchDefault;

// Record a value into the metric.
SearchDefault.INSTANCE.name.set("duck duck go");
// If it changed later, you can record the new value:
SearchDefault.INSTANCE.name.set("wikipedia");
// Record a value into the metric.
SearchDefault.name.set("duck duck go")
// If it changed later, you can record the new value:
SearchDefault.name.set("wikipedia")
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Record a value into the metric.
metrics.search_default.name.set("duck duck go")
# If it changed later, you can record the new value:
metrics.search_default.name.set("wikipedia")

#![allow(unused)]
fn main() {
use glean_metrics;

// Record a value into the metric.
search_default::name.set("duck duck go");
// If it changed later, you can record the new value:
search_default::name.set("wikipedia");
}
import * as searchDefault from "./path/to/generated/files/searchDefault.js";

// Record a value into the metric.
searchDefault.name.set("duck duck go");
// If it changed later, you can record the new value:
searchDefault.name.set("wikipedia");

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::search_default::name.Set("wikipedia"_ns);

JavaScript

Glean.searchDefault.name.set("wikipedia");

Limits

Recorded errors

Testing API

testGetValue

Get the recorded value for a given string metric.

The recorded value may have been truncated. See "Limits" section above.

import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Does the string metric have the expected value?
assertEquals("wikipedia", SearchDefault.name.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Does the string metric have the expected value?
assertEquals("wikipedia", SearchDefault.INSTANCE.name.testGetValue());
@testable import Glean

// Does the string metric have the expected value?
XCTAssertEqual("wikipedia", try SearchDefault.name.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Does the string metric have the expected value?
assert "wikipedia" == metrics.search_default.name.test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;

// Does the string metric have the expected value?
assert_eq!(6, search_default::name.test_get_value(None).unwrap());
}
import * as searchDefault from "./path/to/generated/files/searchDefault.js";

assert.strictEqual("wikipedia", await searchDefault.name.testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

// Is it clear of errors?
ASSERT_TRUE(mozilla::glean::search_default::name.TestGetValue().isOk());
// Does it have the expected value?
ASSERT_STREQ(
  "wikipedia",
  mozilla::glean::search_default::name.TestGetValue().unwrap().value().get()
);

JavaScript

// Does it have the expected value?
// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.equal("wikipedia", Glean.searchDefault.name.testGetValue());

testHasValue

Whether or not any value was recorded for a given string metric.

import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Was anything recorded?
assertTrue(SearchDefault.name.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Was anything recorded?
assertTrue(SearchDefault.INSTANCE.name.testHasValue());
@testable import Glean

// Was anything recorded?
XCTAssert(SearchDefault.name.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was anything recorded?
assert metrics.search_default.name.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given string metric.

import org.mozilla.yourApplication.GleanMetrics.SearchDefault

// Was the string truncated, and an error reported?
assertEquals(1, SearchDefault.name.testGetNumRecordedErrors(ErrorType.InvalidOverflow))
import org.mozilla.yourApplication.GleanMetrics.SearchDefault;

// Was the string truncated, and an error reported?
assertEquals(
    1,
    SearchDefault.INSTANCE.name.testGetNumRecordedErrors(
        ErrorType.InvalidOverflow
    )
);
@testable import Glean

// Was the string truncated, and an error reported?
XCTAssertEqual(1, SearchDefault.name.testGetNumRecordedErrors(.invalidOverflow))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was the string truncated, and an error reported?
assert 1 == metrics.search_default.name.test_get_num_recorded_errors(
    ErrorType.INVALID_OVERFLOW
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

// Was the string truncated, and an error reported?
assert_eq!(
  1,
  search_default::name.test_get_num_recorded_errors(
    ErrorType::InvalidOverflow
  )
);
}
import * as searchDefault from "./path/to/generated/files/searchDefault.js";
import { ErrorType } from "@mozilla/glean/<platform>";

// Was the string truncated, and an error reported?
assert.strictEqual(
  1,
  await searchDefault.name.testGetNumRecordedErrors(ErrorType.InvalidOverflow)
);

Metric parameters

Example string metric definition:

controls:
  refresh_pressed:
    type: string
    description: >
      The name of the default search engine.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

N/A

Data questions

Reference

Labeled Strings

Labeled strings record multiple Unicode string values, each under a different label.

Recording API

set

Sets one of the labels in a labeled string metric to a specific value.

import org.mozilla.yourApplication.GleanMetrics.Login

Login.errorsByStage["server_auth"].set("Invalid password")
import org.mozilla.yourApplication.GleanMetrics.Login;

Login.INSTANCE.errorsByStage["server_auth"].set("Invalid password");
Login.errorsByStage["server_auth"].set("Invalid password")
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.login.errors_by_stage["server_auth"].set("Invalid password")

#![allow(unused)]
fn main() {
use glean_metrics;

login::errors_by_stage.get("server_auth").set("Invalid password");
}
import * as login from "./path/to/generated/files/login.js";

login.errorsByStage["server_auth"].set("Invalid password");

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::login::errors_by_stage.Get("server_auth"_ns).Set("Invalid password"_ns);

JavaScript

Glean.login.errorsByStage["server_auth"].set("Invalid password");

Limits

Recorded Errors

Testing API

testGetValue

Gets the recorded value for a given label in a labeled string metric.

import org.mozilla.yourApplication.GleanMetrics.Login

// Does the metric have the expected value?
assertTrue(Login.errorsByStage["server_auth"].testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Login;

// Does the metric have the expected value?
assertTrue(Login.INSTANCE.errorsByStage["server_auth"].testGetValue());
@testable import Glean

// Does the metric have the expected value?
XCTAssert(Login.errorsByStage["server_auth"].testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Does the metric have the expected value?
assert "Invalid password" == metrics.login.errors_by_stage["server_auth"].testGetValue())

#![allow(unused)]
fn main() {
use glean_metrics;

// Does the metric have the expected value?
assert!(login::errors_by_stage.get("server_auth").test_get_value());
}
import * as login from "./path/to/generated/files/login.js";

// Does the metric have the expected value?
assert.strictEqual("Invalid password", await metrics.login.errorsByStage["server_auth"].testGetValue())

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_STREQ("Invalid password",
             mozilla::glean::login::errors_by_stage.Get("server_auth"_ns)
                .TestGetValue()
                .unwrap()
                .ref()
                .get());

JavaScript

Assert.equal("Invalid password", Glean.login.errorsByStage["server_auth"].testGetValue());

testHasValue

Whether or not any value was recorded for a given label in a labeled string metric.

import org.mozilla.yourApplication.GleanMetrics.Login

// Was anything recorded?
assertTrue(Login.errorsByStage["server_auth"].testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Login;

// Was anything recorded?
assertTrue(Login.INSTANCE.errorsByStage["server_auth"].testHasValue());
@testable import Glean

// Was anything recorded?
XCTAssert(Login.errorsByStage["server_auth"].testHasValue())
# Was anything recorded?
assert metrics.login.errors_by_stage["server_auth"].test_has_value()

testGetNumRecordedErrors

Gets the number of errors recorded for a given labeled string metric in total.

import org.mozilla.yourApplication.GleanMetrics.Login

// Were there any invalid labels?
assertEquals(0, Login.errorsByStage.testGetNumRecordedErrors(ErrorType.InvalidLabel))
import org.mozilla.yourApplication.GleanMetrics.Login;

// Were there any invalid labels?
assertEquals(0, Login.INSTANCE.errorsByStage.testGetNumRecordedErrors(ErrorType.InvalidLabel));
@testable import Glean

// Were there any invalid labels?
XCTAssertEqual(0, Login.errorsByStage.testGetNumRecordedErrors(.invalidLabel))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Were there any invalid labels?
assert 0 == metrics.login.errors_by_stage.test_get_num_recorded_errors(
    ErrorType.INVALID_LABEL
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

// Were there any invalid labels?
assert_eq!(
  0,
  login::errors_by_stage.test_get_num_recorded_errors(
    ErrorType::InvalidLabel
  )
);
}
import * as login from "./path/to/generated/files/login.js";
import { ErrorType } from "@mozilla/glean/<platform>";

// Were there any invalid labels?
assert(
  0,
  await login.errorsByStage.testGetNumRecordedErrors(ErrorType.InvalidLabel)
);

Metric parameters

Example labeled boolean metric definition:

login:
  errors_by_stage:
    type: labeled_string
    description: Records the error type, if any, that occur in different stages of the login process.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    labels:
      - server_auth
      - enter_email
      ...

Extra metric parameters

labels

Labeled metrics may have an optional labels parameter, containing a list of known labels. The labels in this list must match the following requirements:

Important

If the labels are specified in the metrics.yaml, using any label not listed in that file will be replaced with the special value __other__.

If the labels are not specified in the metrics.yaml, only 16 different dynamic labels may be used, after which the special value __other__ will be used.

Removing or changing labels, including their order in the registry file, is permitted. Avoid reusing labels that were removed in the past. It is best practice to add documentation about removed labels to the description field so that analysts will know of their existence and meaning in historical data. Special care must be taken when changing GeckoView metrics sent through the Glean SDK, as the index of the labels is used to report Gecko data through the Glean SDK.

Data questions

Reference

String List

Strings lists are used for recording a list of Unicode string values, such as the names of the enabled search engines.

Important

Be careful using arbitrary strings and make sure they can't accidentally contain identifying data (like directory paths or user input).

Recording API

add

Add a new string to the list.

import org.mozilla.yourApplication.GleanMetrics.Search

Search.engines.add("wikipedia")
Search.engines.add("duck duck go")
import org.mozilla.yourApplication.GleanMetrics.Search

Search.INSTANCE.engines().add("wikipedia")
Search.INSTANCE.engines().add("duck duck go")
Search.engines.add("wikipedia")
Search.engines.add("duck duck go")
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.search.engines.add("wikipedia")
metrics.search.engines.add("duck duck go")
use glean_metrics::search;

search::engines.add("wikipedia".to_string());
search::engines.add("duck duck go".to_string());
Glean.search.engines.add("wikipedia");
Glean.search.engines.add("duck duck go");

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::search::engines.Add("wikipedia"_ns);
mozilla::glean::search::engines.Add("duck duck go"_ns);

JavaScript

Glean.search.engines.add("wikipedia");
Glean.search.engines.add("duck duck go");

Recorded errors

Limits

set

Set the metric to a specific list of strings.

import org.mozilla.yourApplication.GleanMetrics.Search

Search.engines.set(listOf("wikipedia", "duck duck go"))
import org.mozilla.yourApplication.GleanMetrics.Search

Search.INSTANCE.engines().set(listOf("wikipedia", "duck duck go"))
Search.engines.set(["wikipedia", "duck duck go"])
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.search.engines.set(["wikipedia", "duck duck go"])
use glean_metrics::search;

search::engines.set(vec!["wikipedia".to_string(), "duck duck go".to_string()])
Glean.search.engines.set(["wikipedia", "duck duck go"]);

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::search::engines.Set({"wikipedia"_ns, "duck duck go"_ns});

JavaScript

Glean.search.engines.set(["wikipedia", "duck duck go"]);

Recorded errors

Limits

Testing API

testGetValue

Gets the recorded value for a given string list metric.

import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals(listOf("Google", "DuckDuckGo"), Search.engines.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals(
    Arrays.asList("Google", "DuckDuckGo"),
    Search.INSTANCE.engines().testGetValue()
)
@testable import Glean

XCTAssertEqual(["Google", "DuckDuckGo"], try Search.engines.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert ["Google", "DuckDuckGo"] == metrics.search.engines.test_get_value()
use glean_metrics::search;

assert_eq!(
    vec!["Google".to_string(), "DuckDuckGo".to_string()],
    search::engines.test_get_value(None).unwrap()
);
// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
const engines = Glean.search.engines.testGetValue();
Assert.ok(engines.includes("wikipedia"));
Assert.ok(engines.includes("duck duck go"));

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_EQUAL(mozilla::glean::search::engines.TestGetValue().isOk());
nsTArray<nsCString> list = mozilla::glean::search::engines.TestGetValue().unwrap();
ASSERT_TRUE(list.Contains("wikipedia"_ns));
ASSERT_TRUE(list.Constains("duck duck go"_ns));

JavaScript

// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
const engines = Glean.search.engines.testGetValue();
Assert.ok(engines.includes("wikipedia"));
Assert.ok(engines.includes("duck duck go"));

testHasValue

Whether or not any value was recorded for a given string list metric.

import org.mozilla.yourApplication.GleanMetrics.Search

assertTrue(Search.engines.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Search

assertTrue(Search.INSTANCE.engines().testHasValue())
@testable import Glean

XCTAssert(Search.engines.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.search.engines.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given string list metric.

import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals(1, Search.engines.testGetNumRecordedErrors(ErrorType.InvalidValue))
import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals(
    1, Search.INSTANCE.engines().testGetNumRecordedErrors(ErrorType.InvalidValue)
)
@testable import Glean

// Were any of the values too long, and thus an error was recorded?
XCTAssertEqual(1, Search.engines.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert 1 == metrics.search.engines.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)
use glean::ErrorType;
use glean_metrics::search;

assert_eq!(
    0,
    search::engines.test_get_num_recorded_errors(ErrorType::InvalidValue)
);

Metric parameters

Example string list metric definition:

search:
  engines:
    type: string_list
    description: >
      Records the name of the enabled search engines.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

N/A

Data questions

Reference

Timespan

Timespans are used to make a measurement of how much time is spent in a particular task.

To measure the distribution of multiple timespans, see Timing Distributions. To record absolute times, see Datetimes.

It is not recommended to use timespans in multiple threads, since calling start or stop out of order will be recorded as an invalid_state error.

Recording API

start

Starts tracking time. Uses an internal monotonic timer.

import org.mozilla.yourApplication.GleanMetrics.Auth

fun onShowLogin() {
    Auth.loginTime.start()
    // ...
}
import org.mozilla.yourApplication.GleanMetrics.Auth;

void onShowLogin() {
    Auth.INSTANCE.loginTime.start();
    // ...
}
func onShowLogin() {
    Auth.loginTime.start()
    // ...
}
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

def on_show_login():
    metrics.auth.login_time.start()
    # ...

#![allow(unused)]
fn main() {
use fog::metrics;

fn show_login() {
    metrics::auth::login_time.start();
    // ...
}
}
import * as auth from "./path/to/generated/files/auth.js";

function onShowLogin() {
    auth.loginTime.start();
    // ...
}

C++

#include "mozilla/glean/GleanMetrics.h"
void OnShowLogin() {
  mozilla::glean::auth::login_time.Start();
  // ...
}

JavaScript

function onShowLogin() {
  Glean.auth.loginTime.start();
  // ...
}

Recorded errors

Limits

stop

Stops tracking time. The metric value is set to the elapsed time.

import org.mozilla.yourApplication.GleanMetrics.Auth

fun onLogin() {
    Auth.loginTime.stop()
    // ...
}
import org.mozilla.yourApplication.GleanMetrics.Auth;

void onLogin() {
    Auth.INSTANCE.loginTime.stop();
    // ...
}
func onLogin() {
    Auth.loginTime.stop()
    // ...
}
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

def on_login():
    metrics.auth.login_time.stop()
    # ...

#![allow(unused)]
fn main() {
use fog::metrics;

fn login() {
    metrics::auth::login_time.stop();
    // ...
}
}
import * as auth from "./path/to/generated/files/auth.js";

function onLogin() {
    auth.login_time.stop();
    // ...
}

C++

#include "mozilla/glean/GleanMetrics.h"
void OnLogin() {
  mozilla::glean::auth::login_time.Stop();
  // ...
}

JavaScript

function onLogin() {
  Glean.auth.loginTime.stop();
  // ...
}

Recorded errors

cancel

Cancels a previous start. No error is recorded if there was no previous start.

import org.mozilla.yourApplication.GleanMetrics.Auth

fun onLoginCancel() {
    Auth.loginTime.cancel()
    // ...
}
import org.mozilla.yourApplication.GleanMetrics.Auth;

void onLoginCancel() {
    Auth.INSTANCE.loginTime.cancel();
    // ...
}
func onLoginCancel() {
    Auth.loginTime.cancel()
    // ...
}
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

def on_login_cancel():
    metrics.auth.login_time.cancel()
    # ...

#![allow(unused)]
fn main() {
use fog::metrics;

fn login_cancel() {
    metrics::auth::login_time.cancel();
    // ...
}
}
import * as auth from "./path/to/generated/files/auth.js";

function onLoginCancel() {
    auth.login_time.cancel();
    // ...
}

C++

#include "mozilla/glean/GleanMetrics.h"
void OnLoginCancel() {
  mozilla::glean::auth::login_time.Cancel();
  // ...
}

JavaScript

function onLoginCancel() {
  Glean.auth.loginTime.cancel();
  // ...
}

measure

Some languages support convenient auto timing of blocks of code. measure is treated as a start and stop pair for the purposes of error recording. Exceptions (if present in the language) are treated as a cancel.

import org.mozilla.yourApplication.GleanMetrics.Auth

Auth.loginTime.measure {
    // Process login flow
}
import org.mozilla.yourApplication.GleanMetrics.Auth

Auth.INSTANCE.loginTime.measure() -> {
    // Process login flow
    return null;
});
Auth.loginTime.measure {
    // Process login flow
}
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

with metrics.auth.login_time.measure():
    # ... Do the login ...

setRawNanos

Explicitly sets the timespan's value.

Regardless of the time unit chosen for the metric, this API expects the raw value to be in nanoseconds.

Only use this if you have to

This API should only be used if the code being instrumented cannot make use of start, stop, and cancel or measure. Time is hard, and this API can't help you with it.

import org.mozilla.yourApplication.GleanMetrics.Auth

fun afterLogin(loginElapsedNs: Long) {
    Auth.loginTime.setRawNanos(loginElapsedNs)
    // ...
}
import org.mozilla.yourApplication.GleanMetrics.Auth;

void afterLogin(long loginElapsedNs) {
    Auth.INSTANCE.loginTime.setRawNanos(loginElapsedNs);
    // ...
}
func afterLogin(_ loginElapsedNs: UInt64) {
    Auth.loginTime.setRawNanos(loginElapsedNs)
    // ...
}
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

def after_login(login_elapsed_ns):
    metrics.auth.login_time.set_raw_nanos(login_elapsed_ns)
    # ...

#![allow(unused)]
fn main() {
use fog::metrics;
use std::time::duration;

fn after_login(login_elapsed: Duration) {
    metrics::auth::login_time.set_raw(login_elapsed);
    // ...
}
}
import * as auth from "./path/to/generated/files/auth.js";

function onAfterLogin(loginElapsedNs) {
    auth.loginTime.setRawNanos(loginElapsedNs);
    // ...
}

These are different

Firefox Desktop's setRaw uses the units specified in the metric definition. e.g. if the Timespan's time_unit is millisecond, then the duration parameter is a count of milliseconds.

C++

#include "mozilla/glean/GleanMetrics.h"

void AfterLogin(uint32_t aDuration) {
  mozilla::glean::auth::login_time.SetRaw(aDuration);
  // ...
}

JavaScript

function afterLogin(aDuration) {
  Glean.auth.loginTime.setRaw(aDuration);
  // ...
}

Recorded errors

Testing API

testGetValue

Get the currently-stored value.

import org.mozilla.yourApplication.GleanMetrics.Auth

assertTrue(Auth.loginTime.testGetValue() > 0)
import org.mozilla.yourApplication.GleanMetrics.Auth;

assertTrue(Auth.INSTANCE.loginTime.testGetValue() > 0);
@testable import Glean

XCTAssert(try Auth.loginTime.testGetValue() > 0)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.auth.login_time.test_get_value() > 0

#![allow(unused)]
fn main() {
use fog::metrics;

assert!(metrics::login_time.test_get_value().unwrap() > 0);
}
import * as auth from "./path/to/generated/files/auth.js";

assert(await auth.loginTime.testGetValue() > 0);

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_TRUE(mozilla::glean::auth::login_time.TestGetValue().isOk());
ASSERT_GE(mozilla::glean::auth::login_time.TestGetValue().unwrap().value(), 0);

JavaScript

// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.ok(Glean.auth.loginTime.testGetValue() > 0);

testHasValue

Test if the metric currently stores any value.

import org.mozilla.yourApplication.GleanMetrics.Auth

assertTrue(Auth.loginTime.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Auth;

assertTrue(Auth.INSTANCE.loginTime.testHasValue() > 0);
@testable import Glean

XCTAssert(try Auth.loginTime.testHasValue() > 0)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.auth.login_time.test_has_value() > 0

#![allow(unused)]
fn main() {
use fog::metrics;

assert!(metrics::login_time.test_has_value().unwrap() > 0);
}

testGetNumRecordedErrors

Gets the number of errors recorded during operations on this metric.

import org.mozilla.yourApplication.GleanMetrics.Auth

assertEquals(1, Auth.loginTime.testGetNumRecordedErrors(ErrorType.InvalidValue))
import org.mozilla.yourApplication.GleanMetrics.Auth;

assertEquals(
    1,
    Auth.INSTANCE.loginTime.testGetNumRecordedErrors(
        ErrorType.InvalidValue
    )
);
@testable import Glean

XCTAssertEqual(1, Auth.loginTime.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert 1 == metrics.auth.local_time.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)

#![allow(unused)]
fn main() {
use fog::metrics;

assert_eq!(1, login_time.test_get_num_recorded_errors(ErrorType::InvalidValue));
}
import * as auth from "./path/to/generated/files/auth.js";
import { ErrorType } from "@mozilla/glean/<platform>";;

assert.strictEqual(
  1,
  await auth.loginTime.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric parameters

Example timespan metric definition:

auth:
  login_time:
    type: timespan
    description: >
      Measures the time spent logging in.
    time_unit: millisecond
    bugs:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-01-01
    data_sensitivity:
      - interaction

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

time_unit

Timespans have a required time_unit parameter to specify the smallest unit of resolution that the timespan will record. The allowed values for time_unit are:

Consider the resolution that is required by your metric, and use the largest possible value that will provide useful information so as to not leak too much fine-grained information from the client.

Values are truncated

It is important to note that the value sent in the ping is truncated down to the nearest unit. Therefore, a measurement of 500 nanoseconds will be truncated to 0 microseconds.

Data questions

Reference

Timing Distribution

Timing distributions are used to accumulate and store time measurement, for analyzing distributions of the timing data.

To measure the distribution of single timespans, see Timespans. To record absolute times, see Datetimes.

Timing distributions are recorded in a histogram where the buckets have an exponential distribution, specifically with 8 buckets for every power of 2. That is, the function from a value \( x \) to a bucket index is:

\[ \lfloor 8 \log_2(x) \rfloor \]

This makes them suitable for measuring timings on a number of time scales without any configuration.

Note Check out how this bucketing algorithm would behave on the Simulator

Timings always span the full length between start and stopAndAccumulate. If the Glean upload is disabled when calling start, the timer is still started. If the Glean upload is disabled at the time stopAndAccumulate is called, nothing is recorded.

Multiple concurrent timespans in different threads may be measured at the same time.

Timings are always stored and sent in the payload as nanoseconds. However, the time_unit parameter controls the minimum and maximum values that will recorded:

Overflowing this range is considered an error and is reported through the error reporting mechanism. Underflowing this range is not an error and the value is silently truncated to the minimum value.

Additionally, when a metric comes from GeckoView (the geckoview_datapoint parameter is present), the time_unit parameter specifies the unit that the samples are in when passed to Glean. Glean will convert all of the incoming samples to nanoseconds internally.

Configuration

If you wanted to create a timing distribution to measure page load times, first you need to add an entry for it to the metrics.yaml file:

pages:
  page_load:
    type: timing_distribution
    description: >
      Counts how long each page takes to load
    ...

API

Now you can use the timing distribution from the application's code. Starting a timer returns a timer ID that needs to be used to stop or cancel the timer at a later point. Multiple intervals can be measured concurrently. For example, to measure page load time on a number of tabs that are loading at the same time, each tab object needs to store the running timer ID.

import mozilla.components.service.glean.GleanTimerId
import org.mozilla.yourApplication.GleanMetrics.Pages

val timerId : GleanTimerId

fun onPageStart(e: Event) {
    timerId = Pages.pageLoad.start()
}

fun onPageLoaded(e: Event) {
    Pages.pageLoad.stopAndAccumulate(timerId)
}

For convenience one can measure the time of a function or block of code:

Pages.pageLoad.measure {
    // Load a page
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the pageLoad example above, at this point the metric should have a sum == 11 and a count == 2:

import org.mozilla.yourApplication.GleanMetrics.Pages

// Was anything recorded?
assertTrue(Pages.pageLoad.testHasValue())

// Get snapshot.
val snapshot = Pages.pageLoad.testGetValue()

// Usually you don't know the exact timing values, but how many should have been recorded.
assertEquals(1L, snapshot.count)

// Assert that no errors were recorded.
assertEquals(0, Pages.pageLoad.testGetNumRecordedErrors(ErrorType.InvalidValue))
import mozilla.components.service.glean.GleanTimerId;
import org.mozilla.yourApplication.GleanMetrics.Pages;

GleanTimerId timerId;

void onPageStart(Event e) {
    timerId = Pages.INSTANCE.pageLoad.start();
}

void onPageLoaded(Event e) {
    Pages.INSTANCE.pageLoad.stopAndAccumulate(timerId);
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the pageLoad example above, at this point the metric should have a sum == 11 and a count == 2:

import org.mozilla.yourApplication.GleanMetrics.Pages;

// Was anything recorded?
assertTrue(pages.INSTANCE.pageLoad.testHasValue());

// Get snapshot.
DistributionData snapshot = pages.INSTANCE.pageLoad.testGetValue();

// Usually you don't know the exact timing values, but how many should have been recorded.
assertEquals(1L, snapshot.getCount);

// Assert that no errors were recorded.
assertEquals(
    0,
    pages.INSTANCE.pageLoad.testGetNumRecordedErrors(
        ErrorType.InvalidValue
    )
);
import Glean

var timerId : GleanTimerId

func onPageStart() {
    timerId = Pages.pageLoad.start()
}

func onPageLoaded() {
    Pages.pageLoad.stopAndAccumulate(timerId)
}

For convenience one can measure the time of a function or block of code:

Pages.pageLoad.measure {
    // Load a page
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the pageLoad example above, at this point the metric should have a sum == 11 and a count == 2:

@testable import Glean

// Was anything recorded?
XCTAssert(pages.pageLoad.testHasValue())

// Get snapshot.
let snapshot = try! pages.pageLoad.testGetValue()

// Usually you don't know the exact timing values, but how many should have been recorded.
XCTAssertEqual(1, snapshot.count)

// Assert that no errors were recorded.
XCTAssertEqual(0, pages.pageLoad.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

class PageHandler:
    def __init__(self):
        self.timer_id = None

    def on_page_start(self, event):
        # ...
        self.timer_id = metrics.pages.page_load.start()

    def on_page_loaded(self, event):
        # ...
        metrics.pages.page_load.stop_and_accumulate(self.timer_id)

The Python bindings also have a context manager for measuring time:

with metrics.pages.page_load.measure():
    # Load a page ...

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the page_load example above, at this point the metric should have a sum == 11 and a count == 2:

# Was anything recorded?
assert metrics.pages.page_load.test_has_value()

# Get snapshot.
snapshot = metrics.pages.page_load.test_get_value()

# Usually you don't know the exact timing values, but how many should have been recorded.
assert 1 == snapshot.count

# Assert that no errors were recorded.
assert 0 == metrics.pages.page_load.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)
using static Mozilla.YourApplication.GleanMetrics.Pages;

var timerId;

void onPageStart(Event e) {
    timerId = Pages.pageLoad.Start();
}

void onPageLoaded(Event e) {
    Pages.pageLoad.StopAndAccumulate(timerId);
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the pageLoad example above, at this point the metric should have a sum == 11 and a count == 2:

using static Mozilla.YourApplication.GleanMetrics.Pages;

// Was anything recorded?
Assert.True(Pages.pageLoad.TestHasValue());

// Get snapshot.
var snapshot = Pages.pageLoad.TestGetValue();

// Usually you don't know the exact timing values, but how many should have been recorded.
Assert.Equal(1, snapshot.Values.Count);

// Assert that no errors were recorded.
Assert.Equal(0, Pages.pageLoad.TestGetNumRecordedErrors(ErrorType.InvalidValue));

#![allow(unused)]
fn main() {
use glean_metrics;

fn on_page_start() {
    self.timer_id = pages::page_load.start();
}

fn on_page_loaded() {
    pages::page_load.stop_and_accumulate(self.timer_id);
}
}

There are test APIs available too.


#![allow(unused)]
fn main() {
use glean::ErrorType;
use glean_metrics;

// Was anything recorded?
assert!(pages::page_load.test_get_value(None).is_some());

// Assert no errors were recorded.
let errors = [
    ErrorType::InvalidValue,
    ErrorType::InvalidState,
    ErrorType::InvalidOverflow
];
for error in errors {
    assert_eq!(0, pages::page_load.test_get_num_recorded_errors(error));
}
}

Note: C++ APIs are only available in Firefox Desktop.

#include "mozilla/glean/GleanMetrics.h"

auto timerId = mozilla::glean::pages::page_load.Start();
PR_Sleep(PR_MillisecondsToInterval(10));
mozilla::glean::pages::page_load.StopAndAccumulate(std::move(timerId));

There are test APIs available too:

#include "mozilla/glean/GleanMetrics.h"

// Does it have an expected values?
const data = mozilla::glean::pages::page_load.TestGetValue().value().unwrap();
ASSERT_TRUE(data.sum > 0);

Note: JS APIs are only available in Firefox Desktop.

const timerId = Glean.pages.pageLoad.start();
await sleep(10);
Glean.pages.pageLoad.stopAndAccumulate(timerId);

There are test APIs available too:

Assert.ok(Glean.pages.pageLoad.testGetValue().sum > 0);

Limits

Examples

Recorded errors

Reference

Simulator

Please, insert your custom data below as a JSON array.

Data options

Properties

Note The data provided, is assumed to be in the configured time unit. The data recorded, on the other hand, is always in nanoseconds. This means that, if the configured time unit is not nanoseconds, the data will be transformed before being recorded. Notice this, by using the select field above to change the time unit and see the mean of the data recorded changing.

Memory Distribution

Memory distributions are used to accumulate and store memory sizes.

Memory distributions are recorded in a histogram where the buckets have an exponential distribution, specifically with 16 buckets for every power of 2. That is, the function from a value \( x \) to a bucket index is:

\[ \lfloor 16 \log_2(x) \rfloor \]

This makes them suitable for measuring memory sizes on a number of different scales without any configuration.

Note Check out how this bucketing algorithm would behave on the Simulator

Configuration

Memory distributions have a required memory_unit parameter, which specifies the unit the incoming memory size values are recorded in. The units are the power-of-2 units, so "kilobyte" is more correctly a "kibibyte".

- kilobyte == 2^10 ==         1,024 bytes
- megabyte == 2^20 ==     1,048,576 bytes
- gigabyte == 2^30 == 1,073,741,824 bytes

If you wanted to create a memory distribution to measure the amount of heap memory allocated, first you need to add an entry for it to the metrics.yaml file:

memory:
  heap_allocated:
    type: memory_distribution
    description: >
      The heap memory allocated
    memory_unit: kilobyte
    ...

API

Now you can use the memory distribution from the application's code.

Note The data provided to the accumulate method is in the configured memory unit specified in the metrics.yaml file. The data recorded, on the other hand, is always in bytes.

For example, to measure the distribution of heap allocations:

import org.mozilla.yourApplication.GleanMetrics.Memory

fun allocateMemory(nbytes: Int) {
    // ...
    Memory.heapAllocated.accumulate(nbytes / 1024)
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the heapAllocated example above, at this point the metric should have a sum == 11 and a count == 2:

import org.mozilla.yourApplication.GleanMetrics.Memory

// Was anything recorded?
assertTrue(Memory.heapAllocated.testHasValue())

// Get snapshot
val snapshot = Memory.heapAllocated.testGetValue()

// Does the sum have the expected value?
assertEquals(11, snapshot.sum)

// Usually you don't know the exact memory values, but how many should have been recorded.
assertEquals(2L, snapshot.count)

// Did this record a negative value?
assertEquals(1, Memory.heapAllocated.testGetNumRecordedErrors(ErrorType.InvalidValue))
func allocateMemory(nbytes: UInt64) {
    // ...
    Memory.heapAllocated.accumulate(nbytes / 1024)
}

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the heapAllocated example above, at this point the metric should have a sum == 11 and a count == 2:

@testable import Glean

// Was anything recorded?
XCTAssert(Memory.heapAllocated.testHasValue())

// Get snapshot
let snapshot = try! Memory.heapAllocated.testGetValue()

// Does the sum have the expected value?
XCTAssertEqual(11, snapshot.sum)

// Usually you don't know the exact memory values, but how many should have been recorded.
XCTAssertEqual(2, snapshot.count)

// Did this record a negative value?
XCTAssertEqual(1, Memory.heapAllocated.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

def allocate_memory(nbytes):
    # ...
    metrics.memory.heap_allocated.accumulate(nbytes / 1024)

There are test APIs available too. For convenience, properties sum and count are exposed to facilitate validating that data was recorded correctly.

Continuing the heapAllocated example above, at this point the metric should have a sum == 11 and a count == 2:

# Was anything recorded?
assert metrics.memory.head_allocated.test_has_value()

# Get snapshot
snapshot = metrics.memory.heap_allocated.test_get_value()

# Does the sum have the expected value?
assert 11 == snapshot.sum

# Usually you don't know the exact memory values, but how many should have been recorded.
assert 2 == snapshot.count

# Did this record a negative value?
assert 1 == metrics.memory.heap_allocated.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)
using static Mozilla.YourApplication.GleanMetrics.Memory;

fun allocateMemory(ulong nbytes) {
    // ...
    Memory.heapAllocated.Accumulate(nbytes / 1024);
}

There are test APIs available too. For convenience, properties Sum and Count are exposed to facilitate validating that data was recorded correctly.

Continuing the heapAllocated example above, at this point the metric should have a Sum == 11 and a Count == 2:

using static Mozilla.YourApplication.GleanMetrics.Memory;

// Was anything recorded?
Assert.True(Memory.heapAllocated.TestHasValue());

// Get snapshot
var snapshot = Memory.heapAllocated.TestGetValue();

// Does the sum have the expected value?
Assert.Equal(11, snapshot.Sum);

// Usually you don't know the exact memory values, but how many should have been recorded.
Assert.Equal(2L, snapshot.Count);

// Did this record a negative value?
Assert.Equal(1, Memory.heapAllocated.TestGetNumRecordedErrors(ErrorType.InvalidValue));

#![allow(unused)]
fn main() {
use glean_metrics;

fn allocate_memory(bytes: u64) {
    memory::heap_allocated.accumulate(bytes / 1024);
}
}

There are test APIs available too:


#![allow(unused)]
fn main() {
use glean::{DistributionData, ErrorType};
use glean_metrics;

// Was anything recorded?
assert!(memory::heap_allocated.test_get_value(None).is_some());

// Is the sum as expected?
let data = memory::heap_allocated.test_get_value(None).unwrap();
assert_eq!(11, data.sum)
// The actual buckets and counts live in `data.values`.

// Were there any errors?
assert_eq!(1, memory::heap_allocated.test_get_num_recorded_errors(InvalidValue));

}

Note: C++ APIs are only available in Firefox Desktop.

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::memory::heap_allocated.Accumulate(bytes / 1024);

There are test APIs available too:

#include "mozilla/glean/GleanMetrics.h"

// Does it have the expected value?
ASSERT_EQ(11 * 1024, mozilla::glean::memory::heap_allocated.TestGetValue().unwrap().value().sum);

Note: JS APIs are only available in Firefox Desktop.

Glean.memory.heapAllocated.accumulate(bytes / 1024);

There are test APIs available too:

const data = Glean.memory.heapAllocated.testGetValue();
Assert.equal(11 * 1024, data.sum);
// Does it have the right number of samples?
Assert.equal(1, Object.entries(data.values).reduce(([bucket, count], sum) => count + sum, 0));

Limits

Examples

Recorded errors

Reference

Simulator

Please, insert your custom data below as a JSON array.

Data options

Properties

Note The data provided, is assumed to be in the configured memory unit. The data recorded, on the other hand, is always in bytes. This means that, if the configured memory unit is not byte, the data will be transformed before being recorded. Notice this, by using the select field above to change the memory unit and see the mean of the data recorded changing.

UUID

UUIDs metrics are used to record values that uniquely identify some entity, such as a client id.

Recording API

generateAndSet

Sets a UUID metric to a randomly generated UUID value (UUID v4) .

import org.mozilla.yourApplication.GleanMetrics.User

// Generate a new UUID and record it
User.clientId.generateAndSet()
import org.mozilla.yourApplication.GleanMetrics.User;

// Generate a new UUID and record it
User.INSTANCE.clientId.generateAndSet();
// Generate a new UUID and record it
User.clientId.generateAndSet()
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Generate a new UUID and record it
metrics.user.client_id.generate_and_set()

#![allow(unused)]
fn main() {
use glean_metrics;
use uuid::Uuid;

// Generate a new UUID and record it
user::client_id.generate_and_set();
}
import * as user from "./path/to/generated/files/user.js";

user.clientId.generateAndSet();

C++

#include "mozilla/glean/GleanMetrics.h"

// Generate a new UUID and record it.
mozilla::glean::user::client_id.GenerateAndSet();

JavaScript

// Generate a new UUID and record it.
Glean.user.clientId.generateAndSet();

set

Sets a UUID metric to a specific value. Accepts any UUID version.

import org.mozilla.yourApplication.GleanMetrics.User

// Set a UUID explicitly
User.clientId.set(UUID.randomUUID())  // Set a UUID explicitly
import org.mozilla.yourApplication.GleanMetrics.User;

// Set a UUID explicitly
User.INSTANCE.clientId.set(UUID.randomUUID());
User.clientId.set(UUID())  // Set a UUID explicitly
import uuid

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Set a UUID explicitly
metrics.user.client_id.set(uuid.uuid4())

#![allow(unused)]
fn main() {
use glean_metrics;
use uuid::Uuid;

// Set a UUID explicitly
user::client_id.set(Uuid::new_v4());
}
import * as user from "./path/to/generated/files/user.js";

const uuid = "decafdec-afde-cafd-ecaf-decafdecafde";
user.clientId.set(uuid);

C++

#include "mozilla/glean/GleanMetrics.h"

// Set a specific value.
nsCString kUuid("decafdec-afde-cafd-ecaf-decafdecafde");
mozilla::glean::user::client_id.Set(kUuid);

JavaScript

// Set a specific value.
const uuid = "decafdec-afde-cafd-ecaf-decafdecafde";
Glean.user.clientId.set(uuid);

Recorded errors

Testing API

testGetValue

Gets the recorded value for a given UUID metric.

import org.mozilla.yourApplication.GleanMetrics.User

// Was it the expected value?
assertEquals(uuid, User.clientId.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.User;

// Was it the expected value?
assertEquals(uuid, User.INSTANCE.clientId.testGetValue());
@testable import Glean

// Was it the expected value?
XCTAssertEqual(uuid, try User.clientId.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was it the expected value?
assert uuid == metrics.user.client_id.test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;
use uuid::Uuid;

let u = Uuid::new_v4();
// Does it have the expected value?
assert_eq!(u, user::client_id.test_get_value(None).unwrap());
}
import * as user from "./path/to/generated/files/user.js";

const uuid = "decafdec-afde-cafd-ecaf-decafdecafde";
assert(uuid, await user.clientId.testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

// Is it clear of errors?
ASSERT_TRUE(mozilla::glean::user::client_id.TestGetValue().isOk());
// Does it have an expected values?
ASSERT_STREQ(kUuid.get(), mozilla::glean::user::client_id.TestGetValue().unwrap().value().get());

JavaScript

const uuid = "decafdec-afde-cafd-ecaf-decafdecafde";
// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.equal(Glean.user.clientId.testGetValue(), uuid);

testHasValue

Whether or not any value was recorded for a given UUID metric.

import org.mozilla.yourApplication.GleanMetrics.User

// Was anything recorded?
assertTrue(User.clientId.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.User;

// Was anything recorded?
assertTrue(User.INSTANCE.clientId.testHasValue());
@testable import Glean

// Was anything recorded?
XCTAssert(User.clientId.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was anything recorded?
assert metrics.user.client_id.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given UUID metric.

import org.mozilla.yourApplication.GleanMetrics.User

assertEquals(
    1, User.clientId.testGetNumRecordedErrors(ErrorType.InvalidValue)
)
import org.mozilla.yourApplication.GleanMetrics.User;

assertEquals(
    1, User.INSTANCE.clientId.testGetNumRecordedErrors(ErrorType.InvalidValue)
);
XCTAssertEqual(1, User.clientId.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

from glean.testing import ErrorType

assert 1 == metrics.user.client_id.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

assert_eq!(
  1,
  user::client_id.test_get_num_recorded_errors(
    ErrorType::InvalidValue
  )
);
}
import * as user from "./path/to/generated/files/user.js";
import { ErrorType } from "@mozilla/glean/<platform>";

// Was the string truncated, and an error reported?
assert.strictEqual(
  1,
  await user.clientId.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric Parameters

You first need to add an entry for it to the metrics.yaml file:

user:
  client_id:
    type: uuid
    description: >
      A unique identifier for the client's profile
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

N/A

Data questions

Reference

URL

URL metrics allow recording URL-like1 strings.

This metric type does not support recording data URLs - please get in contact with the Glean SDK team if you're missing a type.

Important

Be careful using arbitrary URLs and make sure they can't accidentally contain identifying data (like directory paths, user input or credentials).

1

The Glean SDKs specifically do not validate if a URL is fully spec compliant, all the validations performed are the ones listed in the "Recorded errors" section of this page.

Recording API

set

Set a URL metric to a specific string value.

import org.mozilla.yourApplication.GleanMetrics.Search

Search.template.set("https://mysearchengine.com/")
import org.mozilla.yourApplication.GleanMetrics.Search;

Search.INSTANCE.template.set("https://mysearchengine.com/");
Search.template.set("https://mysearchengine.com")

// Swift's URL type is supported
let url = URL(string: "https://mysearchengine.com")!
Search.template.set(url: url)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.search.template.set("https://mysearchengine.com/")

#![allow(unused)]
fn main() {
use glean_metrics;

search::template.set("https://mysearchengine.com/");
}
import * as search from "./path/to/generated/files/search.js";

search.template.set("https://mysearchengine.com/");

setUrl

Set a URL metric to a specific URL value.

import * as search from "./path/to/generated/files/search.js";

search.template.setUrl(new URL("https://mysearchengine.com/"));

Recorded errors

Limits

Testing API

testGetValue

Gets the recorded value for a given URL metric as a (unencoded) string.

import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals("https://mysearchengine.com/", Search.template.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals("https://mysearchengine.com/", Search.INSTANCE.template.testGetValue());
@testable import Glean

XCTAssertEqual("https://mysearchengine.com/", try Search.template.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert "https://mysearchengine.com/" == metrics.search.template.test_get_value()

#![allow(unused)]
fn main() {
use glean_metrics;

assert_eq!("https://mysearchengine.com/", search::template.test_get_value(None).unwrap());
}
import * as search from "./path/to/generated/files/search.js";

assert.strictEqual("https://mysearchengine.com/", await search.template.testGetValue());

testHasValue

Whether or not any value was recorded for a given UUID metric.

import org.mozilla.yourApplication.GleanMetrics.Search

assertTrue(Search.template.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Search

assertTrue(Search.INSTANCE.template.testHasValue());
@testable import Glean

XCTAssert(try Search.template.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.search.template.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Search

assertEquals(0, Search.template.testGetNumRecordedErrors(ErrorType.InvalidValue))

assertEquals(0, Search.template.testGetNumRecordedErrors(ErrorType.InvalidOverflow))
import org.mozilla.yourApplication.GleanMetrics.Search;

assertEquals(
    0,
    Search.INSTANCE.template.testGetNumRecordedErrors(
        ErrorType.InvalidValue
    )
);

assertEquals(
    0,
    Search.INSTANCE.template.testGetNumRecordedErrors(
        ErrorType.InvalidOverflow
    )
);
@testable import Glean

XCTAssertEqual(0, Search.template.testGetNumRecordedErrors(.invalidValue))
XCTAssertEqual(0, Search.template.testGetNumRecordedErrors(.invalidOverflow))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert 0 == metrics.search.template.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)

assert 0 == metrics.search.template.test_get_num_recorded_errors(
    ErrorType.INVALID_OVERFLOW
)

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

assert_eq!(
  0,
  search::template.test_get_num_recorded_errors(
    ErrorType::InvalidValue
  )
);

assert_eq!(
  0,
  search::template.test_get_num_recorded_errors(
    ErrorType::InvalidOverflow
  )
);
}
import * as search from "./path/to/generated/files/search.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  0,
  await search.template.testGetNumRecordedErrors(ErrorType.InvalidValue)
);
assert.strictEqual(
  0,
  await search.template.testGetNumRecordedErrors(ErrorType.InvalidOverflow)
);

Metric parameters

Example URL metric definition:

search:
  template:
    type: url
    description: >
      The base URL used to build the search query for the search engine.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    data_sensitivity:
      - web_activity

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML format reference page.

Note on data_sensitivity of URL metrics

URL metrics can only either be on categories 3 or 4, namely "Web activity data" or "Highly sensitive data".

Extra metric parameters

N/A

Data questions

Reference

Datetime

Datetimes are used to record an absolute date and time, for example the date and time that the application was first run.

The device's offset from UTC is recorded and sent with the Datetime value in the ping.

To record a single elapsed time, see Timespan. To measure the distribution of multiple timespans, see Timing Distributions.

Recording API

set

Sets a datetime metric to a specific date value. Defaults to now.

import org.mozilla.yourApplication.GleanMetrics.Install

Install.firstRun.set() // Records "now"
Install.firstRun.set(Calendar(2019, 3, 25)) // Records a custom datetime
import org.mozilla.yourApplication.GleanMetrics.Install;

Install.INSTANCE.firstRun.set(); // Records "now"
Install.INSTANCE.firstRun.set(Calendar(2019, 3, 25)); // Records a custom datetime
Install.firstRun.set() // Records "now"
let dateComponents = DateComponents(
                        calendar: Calendar.current,
                        year: 2004, month: 12, day: 9, hour: 8, minute: 3, second: 29
                     )
Install.firstRun.set(dateComponents.date!) // Records a custom datetime
import datetime

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.install.first_run.set() # Records "now"
metrics.install.first_run.set(datetime.datetime(2019, 3, 25)) # Records a custom datetime
use glean_metrics;

use chrono::{FixedOffset, TimeZone};

install::first_run.set(None); // Records "now"
let custom_date = FixedOffset::east(0).ymd(2019, 3, 25).and_hms(0, 0, 0);
install::first_run.set(Some(custom_date)); // Records a custom datetime
import * as install from "./path/to/generated/files/install.js";

install.firstRun.set(); // Records "now"
install.firstRun.set(new Date("March 25, 2019 00:00:00")); // Records a custom datetime

C++

#include "mozilla/glean/GleanMetrics.h"

PRExplodedTime date = {0, 35, 10, 12, 6, 10, 2020, 0, 0, {5 * 60 * 60, 0}};
mozilla::glean::install::first_run.Set(&date);

JavaScript

const value = new Date("2020-06-11T12:00:00");
Glean.install.firstRun.set(value.getTime() * 1000);

Recorded errors

Testing API

testGetValue

Get the recorded value for a given datetime metric as a language-specific Date object.

import org.mozilla.yourApplication.GleanMetrics.Install

assertEquals(Install.firstRun.testGetValue(), Date(2019, 3, 25))
import org.mozilla.yourApplication.GleanMetrics.Install;

assertEquals(Install.INSTANCE.firstRun.testGetValue(), Date(2019, 3, 25));
@testable import Glean

let expectedDate = DateComponents(
                      calendar: Calendar.current,
                      year: 2004, month: 12, day: 9, hour: 8, minute: 3, second: 29
                   )
XCTAssertEqual(expectedDate.date!, try Install.firstRun.testGetValue())
import datetime

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

value = datetime.datetime(1993, 2, 23, 5, 43, tzinfo=datetime.timezone.utc)
assert value == metrics.install.first_run.test_get_value()
use glean_metrics;

use chrono::{FixedOffset, TimeZone};

let expected_date = FixedOffset::east(0).ymd(2019, 3, 25).and_hms(0, 0, 0);
assert_eq!(expected_date, metrics.install.first_run.test_get_value(None));
import * as install from "./path/to/generated/files/install.js";

const expectedDate = new Date("March 25, 2019 00:00:00");
assert.deepStrictEqual(expectedDate, await install.firstRun.testGetValue());

C++

#include "mozilla/glean/GleanMetrics.h"

PRExplodedTime date{0, 35, 10, 12, 6, 10, 2020, 0, 0, {5 * 60 * 60, 0}};
ASSERT_TRUE(mozilla::glean::install::first_run.TestGetValue().isOk());
ASSERT_EQ(
    0,
    std::memcmp(
        &date,
        mozilla::glean::install::first_run.TestGetValue().unwrap().ptr(),
        sizeof(date)));

JavaScript

const value = new Date("2020-06-11T12:00:00");
// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.equal(Glean.install.firstRun.testGetValue().getTime(), value.getTime());

testGetValueAsString

Get the recorded value for a given datetime metric as an ISO Date String.

The returned string will be truncated to the metric's time unit and will include the timezone offset from UTC, e.g. 2019-03-25-05:00 (in this example, time_unit is day).

import org.mozilla.yourApplication.GleanMetrics.Install

assertEquals("2019-03-25-05:00", Install.firstRun.testGetValueAsString())
import org.mozilla.yourApplication.GleanMetrics.Install;

assertEquals("2019-03-25-05:00", Install.INSTANCE.firstRun.testGetValueAsString());
@testable import Glean

assertEquals("2019-03-25-05:00", try Install.firstRun.testGetValueAsString())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert "2019-03-25-05:00" == metrics.install.first_run.test_get_value_as_str()
import * as install from "./path/to/generated/files/install.js";

assert.strictEqual("2019-03-25-05:00", await install.firstRun.testGetValueAsString());

testHasValue

Whether or not any value was recorded for a given datetime metric.

import org.mozilla.yourApplication.GleanMetrics.Install

assertTrue(Install.firstRun.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Install;

assertTrue(Install.INSTANCE.firstRun.testHasValue());
@testable import Glean

XCTAssert(Install.firstRun.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.install.first_run.test_has_value()

testGetNumRecordedErrors

Get number of errors recorded for a given datetime metric.

import mozilla.telemetry.glean.testing.ErrorType
import org.mozilla.yourApplication.GleanMetrics.Install

assertEquals(0, Install.firstRun.testGetNumRecordedErrors(ErrorType.InvalidValue))
import mozilla.telemetry.glean.testing.ErrorType
import org.mozilla.yourApplication.GleanMetrics.Install;

assertEquals(0, Install.INSTANCE.firstRun.testGetNumRecordedErrors(ErrorType.InvalidValue));
@testable import Glean

XCTAssertEqual(0, Install.firstRun.getNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert 0 == metrics.install.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)

#![allow(unused)]
fn main() {
use glean::ErrorType;
use glean_metrics;

assert_eq!(0, install::first_run.test_get_num_recorded_errors(
    ErrorType::InvalidValue
));
}
import * as install from "./path/to/generated/files/install.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  1,
  await install.firstRun.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric parameters

Example datetime metric definition:

install:
  first_run:
    type: datetime
    time_unit: day
    description: >
      Records the date when the application was first run
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

time_unit

Datetimes have a required time_unit parameter to specify the smallest unit of resolution that the metric will record. The allowed values for time_unit are:

Carefully consider the required resolution for recording your metric, and choose the coarsest resolution possible.

Data questions

Reference

Events

Events allow recording of e.g. individual occurrences of user actions, say every time a view was open and from where.

Each event contains the following data:

Are you sure you need an event metric?

Events are best-suited to measuring user behavior, where the frequency of events is relatively low and the order of the events matters. Therefore, events should be the default choice for most user-behavior telemetry.

For other types of telemetry (e.g. performance or stability), events may be too expensive metric type to record, transmit, store and, most importantly, analyze. In those cases, consider lighter metrics, such as counters.

When in doubt, refer to the metric type choosing guide.

Recording API

record(object)

Added in: v38.0.0

Record a new event, with optional typed extra values. This requires type annotations in the definition. See Extra metrics parameters.

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with Extra added.

import org.mozilla.yourApplication.GleanMetrics.Views

Views.loginOpened.record(Views.loginOpenedExtra(sourceOfLogin = "toolbar"))

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with Extra added.

Views.loginOpened.record(LoginOpenedExtra(sourceOfLogin: "toolbar"))

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with _extra added.

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.views.login_opened.record(LoginOpenedExtra(sourceOfLogin="toolbar"))

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with Keys added.

use metrics::views::{self, LoginOpenedExtra};

let extra = LoginOpenedExtra { source_of_login: Some("toolbar".to_string()) };
views::login_opened.record(extra);
import * as views from "./path/to/generated/files/views.js";

views.loginOpened.record({ sourceOfLogin: "toolbar" });

C++

#include "mozilla/glean/GleanMetrics.h"

using mozilla::glean::views::LoginOpenedExtra;
LoginOpenedExtra extra = { .source_of_login = Some("value"_ns) };
mozilla::glean::views::login_opened.Record(std::move(extra))

JavaScript

const extra = { sourceOfLogin: "toolbar" };
Glean.views.loginOpened.record(extra);

record(map) (deprecated)

Deprecated in: v38.0.0

Record a new event, with optional extra values.

Deprecation notice

This API is used in v38.0.0 if an event has no type annotations in the definition. See Extra metrics parameters.

In future versions extra values will default to a string type and this API will be removed.
In Rust and Firefox Desktop this API is not supported.

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with Keys added.

import org.mozilla.yourApplication.GleanMetrics.Views

Views.loginOpened.record(mapOf(Views.loginOpenedKeys.sourceOfLogin to "toolbar"))
import org.mozilla.yourApplication.GleanMetrics.Views;

Views.INSTANCE.loginOpened.record();

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with Keys added.

Views.loginOpened.record(extra: [.sourceOfLogin: "toolbar"])

Note that an enum has been generated for handling the extra_keys: it has the same name as the event metric, with _keys added.

from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.views.login_opened.record(
    {
        metrics.views.login_opened_keys.SOURCE_OF_LOGIN: "toolbar"
    }
)
import * as views from "./path/to/generated/files/views.js";

views.loginOpened.record({ sourceOfLogin: "toolbar" });

Recorded errors

Testing API

testGetValue

Get the list of recorded events.

import org.mozilla.yourApplication.GleanMetrics.Views

val snapshot = Views.loginOpened.testGetValue()
assertEquals(2, snapshot.size)
val first = snapshot.single()
assertEquals("login_opened", first.name)
import org.mozilla.yourApplication.GleanMetrics.Views

assertEquals(Views.INSTANCE.loginOpened.testGetValue().size)
@testable import Glean

val snapshot = try! Views.loginOpened.testGetValue()
XCTAssertEqual(2, snapshot.size)
val first = snapshot[0]
XCTAssertEqual("login_opened", first.name)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

snapshot = metrics.views.login_opened.test_get_value()
assert 2 == len(snapshot)
first = snapshot[0]
assert "login_opened" == first.name
use metrics::views;

var snapshot = views::login_opened.test_get_value(None).unwrap();
assert_eq!(2, snapshot.len());
let first = &snapshot[0];
assert_eq!("login_opened", first.name);
import * as views from "./path/to/generated/files/views.js";

const snapshot = await views.loginOpened.testGetValue();
assert.strictEqual(2, snapshot.length);
const first = snapshot[0]
assert.strictEqual("login_opened", first.name)

C++

#include "mozilla/glean/GleanMetrics.h"

auto optEvents = mozilla::glean::views::login_opened.TestGetValue();
auto events = optEvents.extract();
ASSERT_EQ(2UL, events.Length());
ASSERT_STREQ("login_opened", events[0].mName.get());

JavaScript

var events = Glean.views.loginOpened.testGetValue();
Assert.equal(2, events.length);
Assert.equal("login_opened", events[0].name);

testHasValue

Whether or not any event was recorded for a given event metric.

import org.mozilla.yourApplication.GleanMetrics.Views

assertTrue(Views.loginOpened.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Views

assertTrue(Views.INSTANCE.loginOpened.testHasValue())
@testable import Glean

XCTAssert(Views.loginOpened.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

assert metrics.views.login_opened.test_has_value()

testGetNumRecordedErrors

Get the number of errors recorded for a given event metric.

import mozilla.telemetry.glean.testing.ErrorType
import org.mozilla.yourApplication.GleanMetrics.Views

assertEquals(0, Views.loginOpened.testGetNumRecordedErrors(ErrorType.InvalidOverflow))
import mozilla.telemetry.glean.testing.ErrorType
import org.mozilla.yourApplication.GleanMetrics.Views

assertEquals(0, Views.INSTANCE.loginOpened.testGetNumRecordedErrors(ErrorType.InvalidOverflow))
@testable import Glean

XCTAssertEqual(0, Views.loginOpened.testGetNumRecordedErrors(.invalidOverflow))
from glean import load_metrics
from glean.testing import ErrorType
metrics = load_metrics("metrics.yaml")

assert 0 == metrics.views.login_opened.test_get_num_recorded_errors(
    ErrorType.INVALID_OVERFLOW
)
use glean::ErrorType;
use metrics::views;

assert_eq!(
    0,
    views::login_opened.test_get_num_recorded_errors(ErrorType::InvalidOverflow, None)
);
import * as views from "./path/to/generated/files/views.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  1,
  await views.loginOpened.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric parameters

Example event metric definition:

views:
  login_opened:
    type: event
    description: |
      Recorded when the login view is opened.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    extra_keys:
      source_of_login:
        description: The source from which the login view was opened, e.g. "toolbar".
        type: string

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Events require lifetime: ping.

Recorded events are always sent in their respective pings and then cleared. They cannot be persisted longer. The glean_parser will reject any other lifetime.

Extra metric parameters

extra_keys

The acceptable keys on the "extra" object sent with events. A maximum of 10 extra keys is allowed.

Each extra key contains additional metadata:

Data questions

Limits

Reference

Custom Distribution

Custom distributions are used to record the distribution of arbitrary values.

It should be used only when direct control over how the histogram buckets are computed is required. Otherwise, look at the standard distribution metric types:

Note: Custom distributions are currently not universally supported. See below for available APIs.

Recording API

accumulateSamples

Accumulate the provided samples in the metric.

import org.mozilla.yourApplication.GleanMetrics.Graphics

Graphics.checkerboardPeak.accumulateSamples([23])
use glean_metrics;

graphics::checkerboard_peak.accumulate_samples_signed(vec![23]);

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::graphics::checkerboard_peak.AccumulateSamples({ 23 });

JavaScript

Glean.graphics.checkerboardPeak.accumulateSamples([23])

Limits

Recorded errors

Testing API

testGetValue

Gets the recorded value for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Graphics

// Get snapshot
val snapshot = Graphics.checkerboardPeak.testGetValue()

// Does the sum have the expected value?
assertEquals(11, snapshot.sum)

// Usually you don't know the exact timing values, but how many should have been recorded.
assertEquals(2L, snapshot.count())
use glean::ErrorType;
use glean_metrics::graphics;

// Does it have the expected value?
assert_eq!(23, graphics::checkerboard_peak.test_get_value(None).unwrap().sum);

C++

#include "mozilla/glean/GleanMetrics.h"

auto data = mozilla::glean::graphics::checkerboard_peak.TestGetValue().value();
ASSERT_EQ(23UL, data.sum);

JavaScript

let data = Glean.graphics.checkerboardPeak.testGetValue();
Assert.equal(23, data.sum);

testHasValue

Whether or not any value was recorded for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Graphics

// Was anything recorded?
assertTrue(Graphics.checkerboardPeak.testHasValue())

testGetNumRecordedErrors

Gets number of errors recorded for a given counter metric.

import org.mozilla.yourApplication.GleanMetrics.Graphics

/// Did the metric receive a negative value?
assertEquals(1, Graphics.checkerboardPeak.testGetNumRecordedErrors(ErrorType.InvalidValue))
use glean::ErrorType;
use glean_metrics::graphics;

// Were any of the values negative and thus caused an error to be recorded?
assert_eq!(
    0,
    graphics::checkerboard_peak.test_get_num_recorded_errors(ErrorType::InvalidValue));

Metric Parameters

Example custom distribution metric definition:

graphics:
  checkerboard_peak:
    type: custom_distribution
    description: >
      Peak number of CSS pixels checkerboarded during a checkerboard event.
    range_min: 1
    range_max: 66355200
    bucket_count: 50
    histogram_type: exponential
    unit: pixels
    gecko_datapoint: CHECKERBOARD_PEAK
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

Extra metric parameters

Custom distributions have the following required parameters:

Note Check out how these bucketing algorithms would behave on the Custom distribution simulator.

Custom distributions have the following optional parameters:

Reference

Simulator

Please, insert your custom data below as a JSON array.

Data options

Properties

Quantity

Used to record a single non-negative integer value or 0. For example, the width of the display in pixels.

Do not use Quantity for counting

If you need to count something (e.g. the number of times a button is pressed) prefer using the Counter metric type, which has a specific API for counting things.

Recording API

set

Sets a quantity metric to a specific value.

import org.mozilla.yourApplication.GleanMetrics.Display

Display.width.set(width)
import org.mozilla.yourApplication.GleanMetrics.Display;

Display.INSTANCE.width.set(width);
Display.width.set(width)
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

metrics.display.width.set(width)
import * as display from "./path/to/generated/files/display.js";

display.width.set(window.innerHeight);

#![allow(unused)]
fn main() {
use glean_metrics;

display::width.set(width);
}

C++

#include "mozilla/glean/GleanMetrics.h"

mozilla::glean::display::width.Set(innerHeight);

JavaScript

Glean.display.width.set(innerHeight);

Limits

Recorded errors

Testing API

testGetValue

Gets the recorded value for a given quantity metric.

import org.mozilla.yourApplication.GleanMetrics.Display

// Does the quantity have the expected value?
assertEquals(6, Display.width.testGetValue())
import org.mozilla.yourApplication.GleanMetrics.Display;

// Was anything recorded?
assertTrue(Display.INSTANCE.width.testHasValue());
// Does the quantity have the expected value?
assertEquals(6, Display.INSTANCE.width.testGetValue());
@testable import Glean

// Does the quantity have the expected value?
XCTAssertEqual(6, try Display.width.testGetValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Does the quantity have the expected value?
assert 6 == metrics.display.width.test_get_value()
import * as display from "./path/to/generated/files/display.js";

assert.strictEqual(433, await display.width.testGetValue());

#![allow(unused)]
fn main() {
use glean_metrics;

// Was anything recorded?
assert!(display::width.test_get_value(None).is_some());
}

C++

#include "mozilla/glean/GleanMetrics.h"

ASSERT_TRUE(mozilla::glean::display::width.TestGetValue().isOk());
ASSERT_EQ(433, mozilla::glean::display::width.TestGetValue().unwrap().value());

JavaScript

// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.equal(433, Glean.display.width.testGetValue());

testHasValue

Whether or not any value was recorded for a given quantity metric.

import org.mozilla.yourApplication.GleanMetrics.Display

// Was anything recorded?
assertTrue(Display.width.testHasValue())
import org.mozilla.yourApplication.GleanMetrics.Display;

// Was anything recorded?
assertTrue(Display.INSTANCE.width.testHasValue());
);
@testable import Glean

// Was anything recorded?
XCTAssert(Display.width.testHasValue())
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Was anything recorded?
assert metrics.display.width.test_has_value()

testGetNumRecordedErrors

Gets number of errors recorded for a given quantity metric.

import org.mozilla.yourApplication.GleanMetrics.Display

// Did it record an error due to a negative value?
assertEquals(1, Display.width.testGetNumRecordedErrors(ErrorType.InvalidValue))
import org.mozilla.yourApplication.GleanMetrics.Display;

// Did the quantity record a negative value?
assertEquals(
    1, Display.INSTANCE.width.testGetNumRecordedErrors(ErrorType.InvalidValue)
);
@testable import Glean

// Did the quantity record a negative value?
XCTAssertEqual(1, Display.width.testGetNumRecordedErrors(.invalidValue))
from glean import load_metrics
metrics = load_metrics("metrics.yaml")

# Did the quantity record an negative value?
from glean.testing import ErrorType
assert 1 == metrics.display.width.test_get_num_recorded_errors(
    ErrorType.INVALID_VALUE
)
import * as display from "./path/to/generated/files/display.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  0,
  await display.width.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

#![allow(unused)]
fn main() {
use glean::ErrorType;

use glean_metrics;

assert_eq!(
  1,
  display::width.test_get_num_recorded_errors(
    ErrorType::InvalidValue
  )
);
}

Metric parameters

Example quantity metric definition:

controls:
  refresh_pressed:
    type: quantity
    description: >
      The width of the display, in pixels.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01
    unit: pixels

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Extra metric parameters

unit

Quantities have the required unit parameter, which is a free-form string for documentation purposes.

Data questions

Reference

Rate

Used to count how often something happens relative to how often something else happens. Like how many documents use a particular CSS Property, or how many HTTP connections had an error. You can think of it like a fraction, with a numerator and a denominator.

All rates start without a value. A rate with a numerator of 0 is valid and will be sent to ensure we capture the "no errors happened" or "no use counted" cases.

Let the Glean metric do the counting

When using a rate metric, it is important to let the Glean metric do the counting. Using your own variable for counting and setting the metric yourself could be problematic: ping scheduling will make it difficult to ensure the metric is at the correct value at the correct time. Instead, count to the numerator and denominator as you go.

Recording API

addToNumerator / addToDenominator

Count numerator and denominator individually:

use glean_metrics::*;

if connection_had_error {
    network::http_connection_error.add_to_numerator(1);
}

network::http_connection_error.add_to_denominator(1);

External Denominators

If the rate uses an external denominator, adding to the denominator must be done through the denominator's counter API:

use glean_metrics;

if connection_had_error {
    network::http_connection_error.add_to_numerator(1);
}

network::http_connections.add(1);

C++

#include "mozilla/glean/GleanMetrics.h"

if (aHadError) {
  mozilla::glean::network::http_connection_error.add_to_numerator(1);
}
mozilla::glean::network::http_connection_error.add_to_denominator(1);

JavaScript

if (aHadError) {
  Glean.network.httpConnectionError.addToNumerator(1);
}
Glean.network.httpConnectionError.addToDenominator(1);

Recorded errors

Limits

Testing API

testGetValue

use glean_metrics::*;

assert_eq!((1, 1), network::http_connection_error.test_get_value(None).unwrap());

C++

#include "mozilla/glean/GleanMetrics.h"

auto pair = mozilla::glean::network::http_connection_error.TestGetValue().unwrap();
ASSERT_EQ(1, pair.first);
ASSERT_EQ(1, pair.second);

JavaScript

// testGetValue will throw NS_ERROR_LOSS_OF_SIGNIFICANT_DATA on error.
Assert.deepEqual(
  { numerator: 1, denominator: 1 },
  Glean.network.httpConnectionError.testGetValue()
);

testHasValue

testGetNumRecordedErrors

use glean_metrics::*;
use glean::ErrorType;

assert_eq!(
    0,
    network::http_connection_error.test_get_num_recorded_errors(
        ErrorType::InvalidValue
    )
);

Metric parameters

Example rate metric definition:

network:
  http_connection_error:
    type: rate
    description: >
      How many HTTP connections error out out of the total connections made.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

External Denominators

If several rates share the same denominator then the denominator should be defined as a counter and shared between rates using the denominator_metric property:

network:
  http_connections:
    type: counter
    description: >
      Total number of http connections made.
    ...

  http_connection_error:
    type: rate
    description: >
      How many HTTP connections error out out of the total connections made.
    denominator_metric: network.http_connections
    ...

  http_connection_slow:
    type: rate
    description: >
      How many HTTP connections were slow, out of the total connections made.
    denominator_metric: network.http_connections
    ...

Data Questions

Reference

Text

Records a single long Unicode text, used when the limits on String are too low.

Important

This type should only be used in special cases when other metrics don't fit. See limitations below.
Reach out to the Glean team before using this.

Recording API

set

Sets a text metric to a specific value.

import * as article from "./path/to/generated/files/article.js";

article.content.set(extractedText);

Limits

Recorded errors

Testing API

testGetValue

Gets the recorded value for a given text metric.

import * as article from "./path/to/generated/files/article.js";

assert.strictEqual("some content", await article.content.testGetValue());

testGetNumRecordedErrors

Gets number of errors recorded for a given text metric.

import * as article from "./path/to/generated/files/article.js";
import { ErrorType } from "@mozilla/glean/<platform>";

assert.strictEqual(
  0,
  await article.content.testGetNumRecordedErrors(ErrorType.InvalidValue)
);

Metric parameters

Example text metric definition:

article:
  content:
    type: text
    lifetime: ping
    send_in_pings:
      - research
    data_sensitivity:
      - web_activity
    description: >
      The plaintext content of the displayed article.
    bugs:
      - https://bugzilla.mozilla.org/000000
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=000000#c3
    notification_emails:
      - me@mozilla.com
    expires: 2020-10-01

For a full reference on metrics parameters common to all metric types, refer to the metrics YAML registry format reference page.

Data questions

Pings

Glean-owned pings are submitted automatically

Products do not need to submit Glean built-in pings, as their scheduling is managed internally. The APIs on this page are only relevant for products defining custom pings.

Submission API

submit

Collect and queue a custom ping for eventual uploading.

By default, if the ping doesn't currently have any events or metrics set, submit will do nothing. However, if the send_if_empty flag is set to true in the ping definition, it will always be submitted.

It is not necessary for the caller to check if Glean is disabled before calling submit. If Glean is disabled submit is a no-op.

For example, to submit the custom ping defined in Adding new custom pings:

import org.mozilla.yourApplication.GleanMetrics.Pings
Pings.search.submit(
    Pings.searchReasonCodes.performed
)
import org.mozilla.yourApplication.GleanMetrics.Pings

Pings.INSTANCE.search.submit(
    Pings.INSTANCE.searchReasonCodes.performed
);
import Glean

GleanMetrics.Pings.shared.search.submit(
    reason: .performed
)
from glean import load_pings

pings = load_pings("pings.yaml")

pings.search.submit(pings.search_reason_codes.PERFORMED)
use glean::Pings;

pings::search.submit(pings::SearchReasonCodes::Performed);
import * as pings from "./path/to/generated/files/pings.js";

pings.search.submit(pings.searchReasonCodes.Performed);

C++

mozilla::glean_pings::Search.Submit("performed"_ns);

JavaScript

GleanPings.search.submit("performed");

Testing API

testBeforeNextSubmit

Runs a validation function before the ping is collected.

import org.mozilla.yourApplication.GleanMetrics.Search
import org.mozilla.yourApplication.GleanMetrics.Pings

// Record some data.
Search.defaultEngine.add(5);

// Instruct the ping API to validate the ping data.
var validatorRun = false
Pings.search.testBeforeNextSubmit { reason ->
    assertEquals(Pings.searchReasonCodes.performed, reason)
    assertEquals(5, Search.defaultEngine.testGetValue())
    validatorRun = true
}

// Submit the ping.
Pings.search.submit(
    Pings.searchReasonCodes.performed
)

// Verify that the validator run.
assertTrue(validatorRun)
import org.mozilla.yourApplication.GleanMetrics.Search
import org.mozilla.yourApplication.GleanMetrics.Pings

// Record some data.
Search.INSTANCE.defaultEngine.add(5);

// Instruct the ping API to validate the ping data.
boolean validatorRun = false;
Pings.INSTANCE.search.testBeforeNextSubmit((reason) -> {
    assertEquals(Pings.searchReasonCodes.performed, reason);
    assertEquals(5, Search.INSTANCE.defaultEngine.testGetValue());
    validatorRun = true;
});

// Submit the ping.
Pings.INSTANCE.search.submit(
    Pings.INSTANCE.searchReasonCodes.performed
);

// Verify that the validator run.
assertTrue(validatorRun);
@testable import Glean

// Record some data.
Search.defaultEngine.add(5)

// Instruct the ping API to validate the ping data.
var validatorRun = false
GleanMetrics.pings.shared.search.testBeforeNextSubmit { reason in
    XCTAssertEqual(.performed, reason, "Unexpected reason for search ping submitted")
    XCTAssertEqual(5, try Search.defaultEngine.testGetValue(), "Unexpected value for default engine in search ping")
    validatorRun = true
}

// Submit the ping.
GleanMetrics.Pings.shared.search.submit(
    reason: .performed
)

// Verify that the validator run.
XCTAssert(validatorRun, "Expected validator to be called by now.")
from glean import load_metrics, load_pings

pings = load_pings("pings.yaml")
metrics = load_metrics("metrics.yaml")

# Record some data.
metrics.search.default_engine.add(5)

# Need a mutable object and plain booleans are not.
callback_was_called = [False]

def check_custom_ping(reason):
    assert reason == pings.search_reason_codes.PERFORMED
    assert 5 == metrics.search.default_engine.test_get_value()
    callback_was_called[0] = True

# Instruct the ping API to validate the ping data.
pings.search.test_before_next_submit(check_custom_ping)

# Submit the ping.
pings.search.submit(pings.search_reason_codes.PERFORMED)

# Verify that the validator run.
assert callback_was_called[0]
use glean::Pings;
use glean_metrics;

// Record some data.
search::default_engine.add(5);

// Instruct the ping API to validate the ping data.
pings::search.test_before_next_submit(move |reason| {
    assert_eq!(pings::SearchReasonCodes::Performed, reason);
    assert_eq!(5, search::default_engine.test_get_value(None).unwrap());
});

// When the `submit` API is not directly called by the
// test code, it may be worth checking that the validator
// function run by using a canary boolean in the closure
// used in `test_before_next_submit` and asserting on its
// value after submission.

// Submit the ping.
pings::search.submit(pings::SearchReasonCodes::Performed);
import * as search from "./path/to/generated/files/search.js";
import * as pings from "./path/to/generated/files/pings.js";

// Record some data.
search.defaultEngine.add(5);

// Instruct the ping API to validate the ping data.
let validatorRun = false;
const p = pings.search.testBeforeNextSubmit(async reason => {
  assert.strictEqual(reason, "performed");
  assert.strictEqual(await search.defaultEngine.testGetValue(), 5);
  validatorRun = true;
});

// Submit the ping.
pings.search.submit("performed");
// Wait for the validation to finish.
assert.doesNotThrow(async () => await p);

// Verify that the validator run.
assert.ok(validatorRun);

JavaScript:

Glean.search.defaultEngine.add(5);
let submitted = false;
GleanPings.search.testBeforeNextSubmit(reason => {
  submitted = true;
  Assert.equal(5, Glean.search.defaultEngine.testGetValue());
});
GleanPings.search.submit();
Assert.ok(submitted);

C++:

mozilla::glean::search::default_engine.Add(5);
bool submitted = false;
mozilla::glean_pings::Search.TestBeforeNextSubmit([&submitted](const nsACString& aReason) {
  submitted = true;
  ASSERT_EQ(false, mozilla::glean::search::default_engine.TestGetValue().unwrap().ref());
});
mozilla::glean_pings::Search.Submit();
ASSERT_TRUE(submitted);

Overview

The Glean SDK provides multiple language bindings for integration into different platforms and with different programming languages

Rust

The Rust bindings can be used with any Rust application. It can serve a wide variety of usage patterns, such as short-lived CLI applications as well as longer-running desktop or server applications. It can optionally send builtin pings at startup. It does not assume an interaction model and the integrating application is responsible to connect the respective hooks.

It is available as the glean crate on crates.io.

Kotlin

The Kotlin bindings are primarily used for integration with Android applications. It assumes a common interaction model for mobile applications. It sends builtin pings at startup of the integrating application.

It is available standalone as org.mozilla.telemetry:glean or via Android Components as org.mozilla.components:service-glean from the Mozilla Maven instance.

Note: The Kotlin bindings can also be used from Java.

See Android for more on integrating Glean on Android.

Swift

The Swift bindings are primarily used for integration with iOS applications. It assumes a common interaction model for mobile applications. It sends builtin pings at startup of the integrating application.

It is available as a standalone Xcode framework from the Glean releases page or bundled with the AppServices framework.

Python

The Python bindings allow integration with any Python application. It can serve a wide variety of usage patterns, such as short-lived CLI applications as well as longer-running desktop or server applications.

It is available as glean-sdk on PyPI.

Android-specific information

The Glean SDK can be used in Android applications. The integration into the build system for Android applications can be tuned to your needs. See the following chapters for details.

Android build script configuration options

This chapter describes build configuration options that control the behavior of the Glean SDK's Gradle plugin. These options are not usually required for normal use.

Options can be turned on by setting a variable on the Gradle ext object before applying the Glean Gradle plugin.

allowMetricsFromAAR

Normally, the Glean SDK looks for metrics.yaml and pings.yaml files in the root directory of the Glean-using project. However, in some cases, these files may need to ship inside the dependencies of the project. For example, this is used in the engine-gecko component to grab the metrics.yaml from the geckoview AAR.

ext.allowMetricsFromAAR = true

When this flag is set, every direct dependency of your library will be searched for a metrics.yaml file, and those metrics will be treated as the metrics as if they were defined by your library. That is, API wrappers accessible from your library will be generated for those metrics.

The metrics.yaml can be added to the dependency itself by calling this on each relevant build variant:

variant.packageLibraryProvider.get().from("${topsrcdir}/path/metrics.yaml")

gleanGenerateMarkdownDocs

The Glean SDK can automatically generate Markdown documentation for metrics and pings defined in the registry files, in addition to the metrics API code.

ext.gleanGenerateMarkdownDocs = true

Flipping the feature to true will generate a metrics.md file in $projectDir/docs at build-time. In general this is not necessary for projects using Mozilla's data ingestion infrastructure: in those cases human-readable documentation will automatically be viewable via the Glean Dictionary.

gleanDocsDirectory

The gleanDocsDirectory can be used to customize the path of the documentation output directory. If gleanGenerateMarkdownDocs is disabled, it does nothing. Please note that only the metrics.md will be overwritten: any other file available in the target directory will be preserved.

ext.gleanDocsDirectory = "$rootDir/docs/user/telemetry"

gleanYamlFiles

By default, the Glean Gradle plugin will look for metrics.yaml and pings.yaml files in the same directory that the plugin is included from in your application or library. To override this, ext.gleanYamlFiles may be set to a list of explicit paths.

ext.gleanYamlFiles = ["$rootDir/glean-core/metrics.yaml", "$rootDir/glean-core/pings.yaml"]

Offline builds of Android applications that use Glean

The Glean SDK has basic support for building Android applications that use Glean in offline mode.

The Glean SDK uses a Python script, glean_parser to generate code for metrics from the metrics.yaml and pings.yaml files when Glean-using applications are built. When online, the pieces necessary to run this script are installed automatically.

For offline builds, the Python environment, and packages of glean_parser and its dependencies must be provided prior to building the Glean-using application.

To build a Glean-using application in offline mode, do the following:

There are a couple of environment variables that control offline building:

Instrumenting Android crashes with the Glean SDK

One of the things that might be useful to collect data on in an Android application is crashes. This guide will walk through a basic strategy for instrumenting an Android application with crash telemetry using a custom ping.

Note: This is a very simple example of instrumenting crashes using the Glean SDK. There will be challenges to using this approach in a production application that should be considered. For instance, when an app crashes it can be in an unknown state and may not be able to do things like upload data to a server. The recommended way of instrumenting crashes with Android Components is called lib-crash, which takes into consideration things like multiple processes and persistence.

Before You Start

There are a few things that need to be installed in order to proceed, mainly Android Studio. If you include the Android SDK, Android Studio can take a little while to download and get installed. This walk-through assumes some knowledge of Android application development. Knowing where to go to create a new project and how to add dependencies to a Gradle file will be helpful in following this guide.

Setup Build Configuration

Please follow the instruction in the "Adding Glean to your project" chapter in order to set up Glean in an Android project.

Add A Custom Metric

Since crashes will be instrumented with some custom metrics, the next step will be to add a metrics.yaml file to define the metrics used to record the crash information and a pings.yaml file to define a custom ping which will give some control over the scheduling of the uploading. See "Adding new metrics" for more information about adding metrics.

What metric type should be used to represent the crash data? While this could be implemented several ways, an event is an excellent choice, simply because events capture information in a nice concise way and they have a built-in way of passing additional information using the extras field. If it is necessary to pass along the cause of the exception or a few lines of description, events let us do that easily (with some limitations).

Now that a metric type has been chosen to represent the metric, the next step is creating the metrics.yaml. Inside of the root application folder of the Android Studio project create a new file named metrics.yaml. After adding the schema definition and event metric definition, the metrics.yaml should look like this:

# Required to indicate this is a `metrics.yaml` file
$schema: moz://mozilla.org/schemas/glean/metrics/2-0-0

crash:
  exception:
    type: event
    description: |
      Event to record crashes caused by unhandled exceptions
    notification_emails:
      - crashes@example.com
    bugs:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=1582479
    data_reviews:
      - https://bugzilla.mozilla.org/show_bug.cgi?id=1582479
    expires:
      2021-01-01
    send_in_pings:
      - crash
    extra_keys:
      cause:
        description: The cause of the crash
      message:
        description: The exception message

As a brief explanation, this creates a metric called exception within a metric category called crash. There is a text description and the required notification_emails, bugs, data_reviews, and expires fields. The send_in_pings field is important to note here that it has a value of - crash. This means that the crash event metric will be sent via a custom ping named crash (which hasn't been created yet). Finally, note the extra_keys field which has two keys defined, cause and message. This allows for sending additional information along with the event to be associated with these keys.

Note: For Mozilla applications, a mandatory data review is required in order to collect information with the Glean SDK.

Add A Custom Ping

Define the custom ping that will help control the upload scheduling by creating a pings.yaml file in the same directory as the metrics.yaml file. For more information about adding custom pings, see the section on custom pings.
The name of the ping will be crash, so the pings.yaml file should look like this:

# Required to indicate this is a `pings.yaml` file
$schema: moz://mozilla.org/schemas/glean/pings/2-0-0

crash:
  description: >
    A ping to transport crash data
  include_client_id: true
  notification_emails:
    - crash@example.com
  bugs:
    - https://bugzilla.mozilla.org/show_bug.cgi?id=1582479
  data_reviews:
    - https://bugzilla.mozilla.org/show_bug.cgi?id=1582479

Before the newly defined metric or ping can be used, the application must first be built. This will cause the glean_parser to execute and generate the API files that represent the metric and ping that were newly defined.

Note: If changes to the YAML files aren't showing up in the project, try running the clean task on the project before building any time one of the Glean YAML files has been modified.

It is recommended that Glean be initialized as early in the application startup as possible, which is why it's good to use a custom Application, like the Glean Sample App GleanApplication.kt.

Initializing Glean in the Application.onCreate() is ideal for this purpose. Start by adding the import statement to allow the usage of the custom ping that was created, adding the following to the top of the file:

import org.mozilla.gleancrashexample.GleanMetrics.Pings

Next, register the custom ping by calling Glean.registerPings(Pings) in the onCreate() function, preferably before calling Glean.initialize(). The completed function should look something like this:

override fun onCreate() {
  super.onCreate()

  // Register the application's custom pings.
  Glean.registerPings(Pings)

  // Initialize the Glean library
  Glean.initialize(applicationContext)
}

This completes the registration of the custom ping with the Glean SDK so that it knows about it and can manage the storage and other important details of it like sending it when send() is called.

Instrument The App To Record The Event

In order to make the custom Application class handle uncaught exceptions, extend the class definition by adding Thread.UncaughtExceptionHandler as an inherited class like this:

class MainActivity : AppCompatActivity(), Thread.UncaughtExceptionHandler {
    ...
}

As part of implementing the Thread.UncaughtExceptionHandler interface, the custom Application needs to implement the override of the uncaughtException() function. An example of this override that records data and sends the ping could look something like this:

override fun uncaughtException(thread: Thread, exception: Throwable) {
    Crash.exception.record(
        mapOf(
            Crash.exceptionKeys.cause to exception.cause!!.toString(),
            Crash.exceptionKeys.message to exception.message!!
        )
    )
    Pings.crash.submit()
}

This records data to the Crash.exception metric from the metrics.yaml. The category of the metric is crash and the name is exception so it is accessed it by calling record() on the Crash.exception object. The extra information for the cause and the message is set as well. Finally, calling Pings.crash.submit() forces the crash ping to be scheduled to be sent.

The final step is to register the custom Application as the default uncaught exception handler by adding the following to the onCreate() function after Glean.initialize(this):

Thread.setDefaultUncaughtExceptionHandler(this)

Next Steps

This information didn't really get recorded by anything, as it would be rejected by the telemetry pipeline unless the application was already known. In order to collect telemetry from a new application, there is additional work that is necessary that is beyond the scope of this example. In order for data to be collected from your project, metadata must be added to the probe_scraper. The instructions for accomplishing this can be found in the probe_scraper documentation.

Glean JavaScript SDK

The Glean JavaScript SDK is not based on the same Rust component as the other Glean SDKs. Instead it is a full re-implementation of the Glean APIs in JavaScript.

It can be used in:

Support for other JavaScript environments such as websites, Electron apps and Node.js applications is not out of the question and if you would like to use the SDK in one of these environments reach out to our team.

Plugins

The Glean JavaScript SDK accepts a plugin array as an initialization parameter.

import Glean from "@mozilla/glean/webext"
// This is not a real available plugin,
// it is a hypothetical one for illustration purposes.
import HypotheticalPlugin from "@mozilla/glean/plugins/hypothetical"

Glean.initialize(
  "my.fancy.modified.app",
  uploadStatus,
  {
    plugins: [
      new HypotheticalPlugin("with", "hypothetical", "arguments")
    ]
  }
);

Plugins attach to specific internal events on the SDK and can modify its behavior.

A big advantage of plugins is that they can address very specific use cases of Glean without bloating the final size of the SDK or overloading Glean's configuration object.

On writing your own plugins

It is not currently possible for users to write their own plugins, as this feature is still in its infancy.

Available plugins

PingEncryptionPlugin

The PingEncryptionPlugin encrypts the pings payloads before pings are sent.

PingEncryptionPlugin

The PingEncryptionPlugin encrypts the pings payloads before pings are sent.

The encryption happens after a ping is collected and before it is sent, the scope of this plugin does not include data encryption before collection. In other words, Glean will still store plain data on the user's machine and the data will only be encrypted during transit.

Encrypted pings will not be compliant with the usual Glean ping schema. Instead they will follow a specific encrypted ping schema that looks like this:

{
  "payload": "eyJhbGciOiJFQ0RILUVTI..."
}

The schema has one field, payload, which is an unbounded string containing the output of the encryption of the common Glean payload. Since JSON is the supported transport for our data ingestion platform, the encrypted payload will be in the JWE Compact Serialization format and must include a key id (kid) header identifying the public key used for encryption. A matching key is derived from the document namespace that uniquely identifies the application instead of the key id derived from the public key.

Requesting an encryption key

The encryption key is provisioned by Data SRE and must be generated before new pings can be successfully ingested into a data store. Without a valid encryption key, the Glean pipeline will not be able to parse the pings and they will be thrown into the error stream.

The encryption key should be requested as part of the process of adding a Glean application id to the ingestion pipeline (see this checklist).

Usage

Entry point

//esm
import PingEncryptionPlugin from "@mozilla/glean/plugins/encryption"
// cjs
const { default: PingEncryptionPlugin } = require("@mozilla/glean/plugins/encryption");

Instantiating

The PingEncryptionPlugin constructor expects a JWK as a parameter. This JWK is the key provided by Data SRE during the "Requesting an encryption key" step.

Glean.initialize({
  "my.fancy.encrypted.app",
  uploadStatus,
  {
    plugins: [
         new PingEncryptionPlugin({
              "crv": "P-256",
              "kid": "fancy",
              "kty": "EC",
              "x": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
              "y": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
         })
    ]
  }
});

Note on logPings

The logPings debug feature can still be used if ping encryption is turned on. Pings will be logged in their plain format, right before encryption happens.

Glossary

A glossary with explanations and background for wording used in the Glean project.

Glean

According to the dictionary the word “glean” means:

to gather information or material bit by bit

Glean is the combination of the Glean SDK, the Glean pipeline & Glean tools.

See also: Glean - product analytics & telemetry.

Glean Pipeline

The general data pipeline is the infrastructure that collects, stores, and analyzes telemetry data from our products and logs from various services. See An overview of Mozilla’s Data Pipeline.

The Glean pipeline additionally consists of

Glean SDK

The Glean SDK is the bundle of libraries with support for different platforms. The source code is available at https://github.com/mozilla/glean.

Glean SDK book

This documentation.

Glean tools

Glean provides additional tools for its usage:

Metric

Metrics are the individual things being measured using Glean. They are defined in metrics.yaml files, also known as registry files.

Glean itself provides some metrics out of the box.

Ping

A ping is a bundle of related metrics, gathered in a payload to be transmitted. The Glean SDK provides default pings and allows for custom ping, see Glean Pings.

Submission

"To submit" means to collect & to enqueue a ping for uploading.

The Glean SDK stores locally all the metrics set by it or by its clients. Each ping has its own schedule to gather all its locally saved metrics and create a JSON payload with them. This is called "collection".

Upon successful collection, the payload is queued for upload, which may not happen immediately or at all (in case network connectivity is not available).

Unless the user has defined their own custom pings, they don’t need to worry too much about submitting pings.

All the default pings have their scheduling and submission handled by the SDK.

Measurement window

The measurement window of a ping is the time frame in which metrics are being actively gathered for it.

The measurement window start time is the moment the previous ping is submitted. In the absence of a previous ping, this time will be the time the application process started.

The measurement window end time is the moment the current ping gets submitted. Any new metric recorded after submission will be part of the next ping, so this pings measurement window is over.

This Week in Glean (TWiG)

This Week in Glean is a series of blog posts that the Glean Team at Mozilla is using to try to communicate better about our work.

Changelog

This section contains the changelog for both Glean clients.

Unreleased changes

Full changelog

v42.1.0 (2021-10-18)

Full changelog

v42.0.1 (2021-10-11)

Full changelog

v42.0.0 (2021-10-06)

Full changelog

v41.1.1 (2021-09-29)

Full changelog

v41.1.0 (2021-09-16)

Full changelog

v41.0.0 (2021-09-13)

Full changelog

v40.2.0 (2021-09-08)

Full changelog

v40.1.1 (2021-09-02)

Full changelog

v40.1.0 (2021-08-25)

Full changelog

v40.0.0 (2021-07-28)

Full changelog

v39.1.0 (2021-07-26)

Full changelog

v39.0.4 (2021-07-26)

Full changelog

v39.0.3 (2021-06-09)

Full changelog

v39.0.2 (2021-06-07)

Full changelog

v39.0.1 (2021-06-04)

Full changelog

v39.0.0 (2021-05-31)

Full changelog

v38.0.1 (2021-05-17)

Full changelog

v38.0.0 (2021-05-12)

Full changelog

v37.0.0 (2021-04-30)

Full changelog

v36.0.1 (2021-04-09)

Full changelog

v36.0.0 (2021-03-16)

Full changelog

v35.0.0 (2021-02-22)

Full changelog

v34.1.0 (2021-02-04)

Full changelog

v34.0.0 (2021-01-29)

Full changelog

v33.10.3 (2021-01-18)

Full changelog

v33.10.2 (2021-01-15)

Full changelog

v33.10.1 (2021-01-06)

Full changelog

No functional changes. v33.10.0 failed to generated iOS artifacts due to broken tests (#1421).

v33.10.0 (2021-01-06)

Full changelog

v33.9.1 (2020-12-17)

Full changelog

v33.9.0 (2020-12-15)

Full changelog

v33.8.0 (2020-12-10)

Full changelog

v33.7.0 (2020-12-07)

Full changelog

v33.6.0 (2020-12-02)

Full changelog

v33.5.0 (2020-12-01)

Full changelog

v33.4.0 (2020-11-17)

Full changelog

v33.3.0 (2020-11-12)

Full changelog

v33.2.0 (2020-11-10)

Full changelog

v33.1.2 (2020-11-04)

Full changelog

v33.1.1 (2020-11-04)

Full changelog

v33.1.0 (2020-11-04)

Full changelog

v33.0.4 (2020-09-28)

Full changelog

Note: Previous 33.0.z releases were broken. This release now includes all changes from 33.0.0 to 33.0.3.

v33.0.3 (2020-09-25)

Full changelog

v33.0.2 (2020-09-25)

Full changelog

v33.0.1 (2020-09-24)

Full changelog

v33.0.0 (2020-09-22)

Full changelog

v32.4.1 (2020-10-01)

Full changelog

v32.4.0 (2020-09-18)

Full changelog

v32.3.2 (2020-09-11)

Full changelog

v32.3.1 (2020-09-09)

Full changelog

v32.3.0 (2020-08-27)

Full changelog

v32.2.0 (2020-08-25)

Full changelog

v32.1.1 (2020-08-24)

Full changelog

v32.1.0 (2020-08-17)

Full changelog

v32.0.0 (2020-08-03)

Full changelog

v31.6.0 (2020-07-24)

Full changelog

v31.5.0 (2020-07-22)

Full changelog

v31.4.1 (2020-07-20)

Full changelog

v31.4.0 (2020-07-16)

Full changelog

v31.3.0 (2020-07-10)

Full changelog

v31.2.3 (2020-06-29)

Full changelog

v31.2.2 (2020-06-26)

Full changelog

v31.2.1 (2020-06-25)

Full changelog

v31.2.0 (2020-06-24)

Full changelog

v31.1.2 (2020-06-23)

Full changelog

v31.1.1 (2020-06-12)

Full changelog

v31.1.0 (2020-06-11)

Full changelog

v31.0.2 (2020-05-29)

Full changelog

v31.0.1 (2020-05-29)

Full changelog

v31.0.0 (2020-05-28)

Full changelog

v30.1.0 (2020-05-22)

Full changelog

v30.0.0 (2020-05-13)

Full changelog

v29.1.2 (2021-01-26)

Full changelog

This is an iOS release only, built with Xcode 11.7

Otherwise no functional changes.

v29.1.1 (2020-05-22)

Full changelog

v29.1.0 (2020-05-11)

Full changelog

v29.0.0 (2020-05-05)

Full changelog

v28.0.0 (2020-04-23)

Full changelog

v27.1.0 (2020-04-09)

Full changelog

v27.0.0 (2020-04-08)

Full changelog

v26.0.0 (2020-03-27)

Full changelog

v25.1.0 (2020-02-26)

Full changelog

v25.0.0 (2020-02-17)

Full changelog

v24.2.0 (2020-02-11)

Full changelog

v24.1.0 (2020-01-16)

Full changelog

v24.0.0 (2020-01-14)

Full changelog

v23.0.1 (2020-01-08)

Full changelog

v23.0.0 (2020-01-07)

Full changelog

v22.1.0 (2019-12-17)

Full changelog

v22.0.0 (2019-12-05)

Full changelog

v21.3.0 (2019-12-03)

Full changelog

v21.2.0 (2019-11-21)

Full changelog

v21.1.1 (2019-11-20)

Full changelog

v21.1.0 (2019-11-20)

Full changelog

v21.0.0 (2019-11-18)

Full changelog

v20.2.0 (2019-11-11)

Full changelog

v20.1.0 (2019-11-11)

Full changelog

v20.0.0 (2019-11-11)

Full changelog

v19.1.0 (2019-10-29)

Full changelog

v19.0.0 (2019-10-22)

Full changelog

First stable release of Glean in Rust (aka glean-core). This is a major milestone in using a cross-platform implementation of Glean on the Android platform.

v0.0.1-TESTING6 (2019-10-18)

Full changelog

v0.0.1-TESTING5 (2019-10-10)

Full changelog

v0.0.1-TESTING4 (2019-10-09)

Full changelog

v0.0.1-TESTING3 (2019-10-08)

Full changelog

v0.0.1-TESTING2 (2019-10-07)

Full changelog

v0.0.1-TESTING1 (2019-10-02)

Full changelog

General

First testing release.

Unreleased changes

Full changelog

v0.23.0 (2021-10-12)

Full changelog

v0.22.0 (2021-10-06)

Full changelog

v0.21.1 (2021-09-30)

Full changelog

v0.21.0 (2021-09-30)

Full changelog

v0.20.0 (2021-09-17)

Full changelog

v0.19.0 (2021-09-03)

Full changelog

v0.18.1 (2021-07-22)

Full changelog

v0.18.0 (2021-07-20)

Full changelog

v0.17.0 (2021-07-16)

Full changelog

v0.16.0 (2021-07-06)

Full changelog

v0.15.0 (2021-06-03)

Full changelog

v0.14.1 (2021-05-21)

Full changelog

v0.14.0 (2021-05-19)

Full changelog

v0.13.0 (2021-05-18)

Full changelog

v0.12.0 (2021-05-11)

Full changelog

v0.11.0 (2021-05-03)

Full changelog

v0.10.2 (2021-04-26)

Full changelog

v0.10.1 (2021-04-26)

Full changelog

v0.10.0 (2021-04-20)

Full changelog

v0.9.2 (2021-04-19)

Full changelog

v0.9.1 (2021-04-19)

Full changelog

v0.9.0 (2021-04-19)

Full changelog

v0.8.1 (2021-04-14)

Full changelog

v0.8.0 (2021-04-13)

Full changelog

v0.7.0 (2021-03-26)

Full changelog

v0.6.1 (2021-03-22)

Full changelog

v0.6.0 (2021-03-22)

Full changelog

v0.5.0 (2021-03-18)

Full changelog

v0.4.0 (2021-03-10)

Full changelog

v0.3.0 (2021-02-24)

Full changelog

v0.2.0 (2021-02-23)

Full changelog

v0.1.1 (2021-02-17)

Full changelog

v0.1.0 (2021-02-17)

Full changelog

This Week in Glean (TWiG)

“This Week in Glean” is a series of blog posts that the Glean Team at Mozilla is using to try to communicate better about our work. They could be release notes, documentation, hopes, dreams, or whatever: so long as it is inspired by Glean.

Blog posts

Contribution Guidelines

There are two important questions to answer before adding new content to this book:

This guide aims to provide context for answering both questions.

Table of contents

Where to add new content?

This book is divided in five different sections. Each section contains pages that are of a specific type. New content will fit in one of these section. Following is an explanation on what kind of content fits in each section.

Overview

Is the content you want to add an essay or high level explanation on some aspect of Glean?

The overview section is the place to provide important higher level context for users of Glean. This section may include essays about Glean’s views, principles, data practices, etc. It also contains primers on information such as what is the Glean SDK and Glean.js.

User Guides

Is the content you want to add a general purpose guide on a Glean aspect or feature?

This section is the place for Glean SDK user guides. Pages under this section contain prose format guides on how to include Glean in a project, how to add metrics, how to create pings, and so on.

Pages on this section may link to the API Reference pages, but should not themselves be API References.

Guides can be quite long, thus we should favor having one page per language binding instead of using tabs.

API Reference

Is the content you want to add a developer reference on a specific Glean API?

This section of the book contains reference for all of Glean’s user APIs. Its pages follow a strict structure.

Each API description contains:

The API Reference pages should not contain any guides in prose format, they should all be linked from the User’s Guide when convenient.

Language Binding Information

Is the content you want to add a language binding specific guide on a Glean feature?

Language bindings may require some dedicated pages, these section contains these pages. Each language binding has a top level section under this section, specific pages live under these titles.

Appendix

Is the content you want to add support content for the rest of the content on book?

The appendix contains support information related to the Glean SDK or the content of this book.

In which format to present content?

General guidelines

Each page of the book should be written as if it were the first page a user is visiting ever. There should be links to other pages of the book wherever there is missing context in the current page. This is important, because documentations are first and foremost reference books, manuals. They should not be expected to be read in order.

Prefer using headers whenever a new topic is introduced

mdbook (the tool used to build this book) turns all headers into links. Which is useful to refer to specific documentation sections.

Favor creating new pages, instead of adding unrelated content to an already existing page

This makes it easier to find content through the Summary.

Custom elements

Tabs

Tabs are useful for providing small code examples of Glean's APIs for each language binding. A tabs section starts with the tab_header include and ends with the tab_footer include. Each tab is declared in between these include statements.

Each tab content is placed inside an html div tag with the data-lang and class="tab" attributes. The data-lang attribute contains the title of the tab. Titles must match for different tabs on the same language binding. Whenever a user clicks in a tab with a specific title, all tabs with that same title will be opened by default, until the user clicks in a tab with a different title.

Every tab section should contain tabs for all Glean language bindings, even if a language binding does not provide the API in question. In this case, the tab div should still be there without any inner HTML. When that is the case that tab will be rendered in a disabled state.

These are the tabs every tab section is expected to contain, in order:

Finally, here is an example code for a tabs sections:

{{#include ../../shared/tab_header.md}}
<div data-lang="Kotlin" class="tab">
  Kotlin information...
</div>
<div data-lang="Java" class="tab">
  Java information...
</div>
<div data-lang="Swift" class="tab">
  Swift information...
</div>
<div data-lang="Python" class="tab">
  Python information...`
</div>
<div data-lang="Rust" class="tab">
  Rust information...
</div>
<!--
  In this example, JavaScript and Firefox Desktop
  would show up as disabled in the final page.
-->
<div data-lang="JavaScript" class="tab"></div>
<div data-lang="Firefox Desktop" class="tab"></div>
{{#include ../../shared/tab_footer.md}}

And this is how those tabs will look like:

Kotlin information...
Java information...
Swift information...
Python information...`
Rust information...

Tab tooltips

Tabs in a disabled i.e. tabs that do not have any content, will show a tooltip when hovered.

By default, this tooltip will show the message <lang> doe not provide this API. The following data-* attributes can be used to modify this message.

data-bug

This attribute expects a Bugzilla bug number. When this attribute is added a link to the provided bug will be added to the tooltip text.

data-info

This attribute expects free form text or valid HTML. Be careful when adding long texts here. If a text needs to be too long, consider adding it as an actual section / paragraph to the page instead of as a tooltip.

This is how you can use the above attributes.

{{#include ../../shared/tab_header.md}}
...

<!-- No attribute, default text will show up. -->
<div data-lang="Rust" class="tab"></div>
<!-- data-bug attribute, default text will show up + link to bug. -->
<div data-lang="JavaScript" class="tab" data-bug="000000"></div>
<!-- data-info attribute, free form text will show up. -->
<div data-lang="Firefox Desktop" class="tab" data-info="Hello, Glean world!"></div>
{{#include ../../shared/tab_footer.md}}

And this is how each tool tip is rendered.

Custom block quotes

Sometimes it is necessary to bring attention to a special piece of information, or simply to provide extra context related to the a given text.

In order to do that, there are three custom block quote formats available.

Info quote

An information block quote format, to provide useful extra context for a given text.

Warning quote

A warning block quote format, to provide useful warning related to a given text.

Stop quote

A stronger warning block quote format, to provide useful warning related to a given text in a more emphatic format. Use these sparingly.

To include such quotes, again you can use mdbook include statements.

For the above quotes, this is the corresponding code.

{{#include ../../shared/blockquote-info.html}}

##### Info quote

> An information blockquote format, to provide useful extra context for a given text.

{{#include ../../shared/blockquote-warning.html}}

##### Warning quote

> A warning blockquote format, to provide useful warning related to a given text.

{{#include ../../shared/blockquote-stop.html}}

##### Stop quote

> A stronger warning blockquote format, to provide useful warning related to a given text in a
> more emphatic format. Use these sparingly.

It is possible to use any level header with these special block quotes and also no header at all.