data_source_factory

For general information on how the Python agent API calls relate to each other, see the API guide.

data_source_factory(name=None, **properties)
Wraps a data source defined as a factory.

Description

The data source APIs provide a way to generate metric timeslice data using a pull-style API rather than the push-style API implemented by record_custom_metric. For more about why and how to use data sources for custom metrics, see Custom metric data sources.

The data_source_factory decorator wraps a data source defined as a factory. The decorator can be applied to a class or a function. The class constructor or function must accept arguments of settings (configuration settings for the data source) and environ (information about context in which the data source is being used).

The resulting object must be a callable which directly returns an iterable/generator with the metrics for each sample.

Parameters

Parameter Description

name

string

Optional. The name of the data source. This is used only for logging purposes. If not provided, it defaults to the callable name derived from the decorated function.

properties

dictionary

Optional. Any additional properties to pass to the data source factory.

The possible fields for a dictionary are:

  • count
  • total
  • min
  • max
  • sum_of_squares

For explanations of these fields and some general usage tips, see the documentation for the New Relic Plugins custom metrics API.​

Return value(s)

Returns a function.

Example(s)

data_source_factory example

An example:

import os
import time
import multiprocessing

@newrelic.agent.data_source_factory(name='CPU Usage')
class CPUMetricsDataSource(object):

    def __init__(self, settings, environ):
        self.last_timestamp = None
        self.times = None
 
    def start(self):
        self.last_timestamp = time.time()
        self.times = os.times()
 
    def stop(self):
        self.last_timestamp = None
        self.times = None

    def __call__(self):
        if self.times is None:
            return

        now = time.time()
        new_times = os.times()
        elapsed_time = now - self.last_timestamp
        user_time = new_times[0] - self.times[0]
        utilization = user_time / (elapsed_time*multiprocessing.cpu_count())
        self.last_timestamp = now
        self.times = new_times

        yield ('Custom/CPU/User Time', user_time)
        yield ('Custom/CPU/User/Utilization', utilization)

newrelic.agent.register_data_source(CPUMetricsDataSource)

For more help

Recommendations for learning more: