Code Instrumentation

This article explains what it takes to generate custom metrics data points in your code.

Let's look at a Python example in which we're instrumenting a process that retrieves financial data about Apple's stock prices from a third-party provider. We measure how many times it runs, how long it takes to run, and how many items of data it returns.

tags = ',exchange=NASDAQ,quote=AAPL,base=USD'
metrics.incr('data_feeds.task_runs' + tags)
with metrics.timer('data_feeds.task_duration' + tags):
    data = some_function_to_get_the_data(
        quote='AAPL', base='USD')
    metrics.gauge('data_feeds.items_count' + tags, len(data))

What does it take to set up the 'metrics' variable? It's quite simple:

import os
import statsd

if os.environ.get('ENV') == 'production':
    host = os.environ.get('HOSTED_METRICS_HOST')
else:
    host = None  # don't connect if not in PROD

metrics = statsd.StatsClient(
    host,
    os.environ.get('HOSTED_METRICS_PORT'),
    prefix=os.environ.get('HOSTED_METRICS_API_KEY'))

Lastly, you'll need to install the 'statsd' lib:

pip install statsd

Our implementation of measurement names for InfluxDB are tweaked to allow you specify both the measurement name and the field name. Please read the details on our Measurement Naming page.

Want to see it in action?

You can trial it risk-free with our InfluxDB solution.