Adam Rush

@Adam9Rush

29 August, 2022

Introduction

MetricKit is a new framework to monitor App Performance and Battery Usage within your application. It was released in 2019, and you can read more about this framework here.

One of the fantastic things you can do with MetricKit is track custom metrics using Apple’s APIs so that you can consume this data and make better technical or engineering decisions based on the results.

Let’s start by going over a real-life example.

You are about to start working on a significant new feature in your app. You don’t know how your users react, and it will touch some critical parts of your application’s logic. You’d like to roll out this feature slowly, and you’d like to monitor the performance of this feature and how it will affect your app’s performance.

The question is, how are you going to achieve this? Well, it’s possible with MetricKit.

Custom Metrics with MetricKit

So, you have built this new feature, and the part is adding a checkout process to your application; your code looks something like this:

import MetricKit

let checkoutProcessBucket = MXMetricManager.makeLogHandle(category: "Checkout")

private func checkout() {
  mxSignpost(.begin, log: checkoutProcessBucket, name: "Checkout")
    
  // Checkout Code
  // Here
    
  mxSignpost(.end, log: checkoutProcessBucket, name: "Checkout")
}

So, you start by importing the MetricKit framework.

You then create a new LogHandle, which is essentially a bucket that will contain all of these metrics.

You can then use the mxSignpost() API and pass in the .begin and .end enum value which defines when this logic started and when it ended. This is important because MetricKit will calculate the performance during this period.

It’s also possible to pass in .event enum value which is a single event that will be logged within your Metrics, for example, a user clicking on the “Checkout” button.

Getting this data

As mentioned in my original MetricKit – Getting Started article, your metrics here will be passed through the MetricKit delegate as either a JSON or Dictionary object that you can parse and render in your services or save to disk.

What Next?

MetricKit is a powerful way to monitor your app performance and battery usage. Using custom metrics will allow you to use both your metrics and Apple’s predefined metrics and combine them to monitor performance.

Apple has invested so much effort in creating some fantastic tutorials and even how to understand those metrics better and make meaningful updates.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.