• /
  • Log in
  • Free account

data_source_factory (Python agent API)


data_source_factory(name=None, **properties)

Wraps a data source defined as a factory.


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.






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.



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

Return values

Returns a function.


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:
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)

For more help

If you need more help, check out these support and learning resources:

Create issueEdit page
Copyright © 2021 New Relic Inc.