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')
    host = None  # don't connect if not in PROD

metrics = statsd.StatsClient(

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.

Have questions? Need advice?

Pick a slot from the calendar to chat with one of our engineers. Whether you just need high-level advice on metrics and monitoring or have specific questions about HostedMetrics, we're here to help you!
Schedule a Chat