Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Automatic Instrumentation

This section covers middleware patterns for automatically tracking metrics and telemetry in your application.

Request metrics

In web application frameworks, you can automatically track metrics for errors and request duration/latency.

The following examples show automatic metrics implementations:

This method works best when you implement automatic context management.

Wrapping releases

Creating wrapper functions can be a useful way to encapsulate guarded releases outside of web frameworks.

Here is an example in JavaScript for a client-side application:

function guard(ldClient, fn, thisArg) {
  const trackDuration = (start) => {
    const duration = performance.now() - start
    ldClient.track('duration', duration)
    return duration
  }

  return function () {
    const start = performance.now()
    let result

    try {
      result = fn.apply(thisArg ?? this, arguments)
    } catch (e) {
      trackDuration(start)
      ldClient.track('error')
      throw e
    }
    // handle async functions
    if (result && typeof result.then === 'function') {
      return result
        .then((value) => {
          trackDuration(start)
          return value
        })
        .catch((e) => {
          trackDuration(start)
          ldClient.track('error')
          throw e
        })
    } else {
      trackDuration(start)
      return result
    }
  }
}

// Usage
const getNotifications = guard(ldClient, async (count) => {
  const apiPath = ldClient.variation('release-notifications-v2', false) ? '/api/v2/notifications' : '/api/v1/notifications'
  const response = await fetch(apiPath + `?count=${count}`)
  if (!response.ok) throw new Error('Failed to fetch notifications')
  return await response.json()
})

// Error and latency metrics are tracked automatically and associated
// with the feature flags we evaluated
const notifications = await getNotifications(10)