API Reference

New Relic HTTP Clients

class newrelic_telemetry_sdk.client.EventClient(license_key, host=None, port=443)[source]

HTTP Client for interacting with the New Relic Event API

This class is used to send events to the New Relic Event API over HTTP.

Parameters:
  • license_key (str) – New Relic license key

  • host (str) – (optional) Override the host for the event API endpoint.

  • port (int) – (optional) Override the port for the client. Default: 443

Usage:

>>> import os
>>> license_key = os.environ.get("NEW_RELIC_LICENSE_KEY", "")
>>> event_client = EventClient(license_key)
>>> response = event_client.send({})
>>> event_client.close()
POOL_CLS

alias of HTTPSConnectionPool

add_version_info(product, product_version)

Adds product and version information to a User-Agent header

This method implements https://tools.ietf.org/html/rfc7231#section-5.5.3

Parameters:
  • product (str) – The product name using the SDK

  • product_version (str) – The version string of the product in use

close()

Close all open connections and disable internal connection pool.

send(item, timeout=None)

Send a single item

Parameters:
  • item (dict) – The object to send

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

send_batch(items, timeout=None)[source]

Send a batch of items

Parameters:
  • items (list or tuple) – An iterable of items to send to New Relic.

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

exception newrelic_telemetry_sdk.client.HTTPError[source]

Unexpected HTTP Status

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class newrelic_telemetry_sdk.client.MetricClient(license_key, host=None, port=443)[source]

HTTP Client for interacting with the New Relic Metric API

This class is used to send metrics to the New Relic Metric API over HTTP.

Parameters:
  • license_key (str) – New Relic license key

  • host (str) – (optional) Override the host for the metric API endpoint.

  • port (int) – (optional) Override the port for the client. Default: 443

Usage:

>>> import os
>>> license_key = os.environ.get("NEW_RELIC_LICENSE_KEY", "")
>>> metric_client = MetricClient(license_key)
>>> response = metric_client.send({})
>>> metric_client.close()
POOL_CLS

alias of HTTPSConnectionPool

add_version_info(product, product_version)

Adds product and version information to a User-Agent header

This method implements https://tools.ietf.org/html/rfc7231#section-5.5.3

Parameters:
  • product (str) – The product name using the SDK

  • product_version (str) – The version string of the product in use

close()

Close all open connections and disable internal connection pool.

send(item, timeout=None)

Send a single item

Parameters:
  • item (dict) – The object to send

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

send_batch(items, common=None, timeout=None)

Send a batch of items

Parameters:
  • items (list or tuple) – An iterable of items to send to New Relic.

  • common (dict) – (optional) A map of attributes that will be set on each item.

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

class newrelic_telemetry_sdk.client.SpanClient(license_key, host=None, port=443)[source]

HTTP Client for interacting with the New Relic Span API

This class is used to send spans to the New Relic Span API over HTTP.

Parameters:
  • license_key (str) – New Relic license key

  • host (str) – (optional) Override the host for the span API endpoint.

  • port (int) – (optional) Override the port for the client. Default: 443

Usage:

>>> import os
>>> license_key = os.environ.get("NEW_RELIC_LICENSE_KEY", "")
>>> span_client = SpanClient(license_key)
>>> response = span_client.send({})
>>> span_client.close()
POOL_CLS

alias of HTTPSConnectionPool

add_version_info(product, product_version)

Adds product and version information to a User-Agent header

This method implements https://tools.ietf.org/html/rfc7231#section-5.5.3

Parameters:
  • product (str) – The product name using the SDK

  • product_version (str) – The version string of the product in use

close()

Close all open connections and disable internal connection pool.

send(item, timeout=None)

Send a single item

Parameters:
  • item (dict) – The object to send

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

send_batch(items, common=None, timeout=None)

Send a batch of items

Parameters:
  • items (list or tuple) – An iterable of items to send to New Relic.

  • common (dict) – (optional) A map of attributes that will be set on each item.

  • timeout (int) – (optional) a timeout in seconds for sending the request

Return type:

HTTPResponse

class newrelic_telemetry_sdk.client.HTTPResponse[source]

Response object with helper methods

Variables:
  • headers – The HTTP headers

  • status – The HTTP status code

  • data – The raw byte encoded response data

json()[source]

Returns the json-encoded content of a response.

Return type:

dict

property ok

Return true if status code indicates success

raise_for_status()[source]

Raise an exception for an unsuccessful HTTP status code

Raises:

HTTPError – if response status is not successful

Metrics

class newrelic_telemetry_sdk.metric.CountMetric(name, value, interval_ms, tags=None, end_time_ms=<object object>)[source]

Count Metric

This metric is of a “count” type. The metric holds an integer indicating a count of events which have taken place.

Parameters:
  • name (str) – The name of the metric.

  • value (int or float) – The metric count value.

  • interval_ms (int) – The interval of time in milliseconds over which the metric was recorded.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

  • end_time_ms (int) – (optional) A unix timestamp in milliseconds representing the end time of the metric. Defaults to time.time() * 1000

Usage:

>>> from newrelic_telemetry_sdk import CountMetric
>>> metric = CountMetric('response_code', 1, interval_ms=1, tags={'code': 200})
>>> metric.value
1
class newrelic_telemetry_sdk.metric.GaugeMetric(name, value, tags=None, end_time_ms=<object object>)[source]

Basic Metric type

This metric is of a “gauge” type. It records values at a point in time.

Parameters:
  • name (str) – The name of the metric.

  • value (int or float) – The metric value.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

  • end_time_ms (int) – (optional) A unix timestamp in milliseconds representing the end time of the metric. Defaults to time.time() * 1000

Usage:

>>> from newrelic_telemetry_sdk import GaugeMetric
>>> metric = GaugeMetric('temperature', 20, tags={'units': 'C'})
>>> metric.value
20
class newrelic_telemetry_sdk.metric.SummaryMetric(name, count, sum, min, max, interval_ms, tags=None, end_time_ms=<object object>)[source]

Summary Metric

This metric is of a “summary” type. It tracks the count, sum, min, and max values when recording values. These values can be used to compute averages and distributions over time.

Parameters:
  • name (str) – The name of the metric.

  • count (int) – The count in the summary metric.

  • sum (int or float) – The sum in the summary metric.

  • min (int or float) – The minimum value in the summary metric.

  • max (int or float) – The maximum value in the summary metric.

  • interval_ms (int) – The interval of time in milliseconds over which the metric was recorded.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

  • end_time_ms (int) – (optional) A unix timestamp in milliseconds representing the end time of the metric. Defaults to time.time() * 1000

Usage:

>>> from newrelic_telemetry_sdk import SummaryMetric
>>> metric = SummaryMetric('response_time',
...     count=1, sum=0.2, min=0.2, max=0.2, interval_ms=1)
>>> sorted(metric.value.items())
[('count', 1), ('max', 0.2), ('min', 0.2), ('sum', 0.2)]

Events

class newrelic_telemetry_sdk.event.Event(event_type, tags=None, timestamp_ms=None)[source]

An event represented in New Relic Insights

Parameters:
  • event_type (str) – The type of event to report

  • tags (dict) – (optional) A set of tags that can be used to filter this event in the New Relic UI.

  • timestamp_ms (int) – (optional) A unix timestamp in milliseconds representing the timestamp in ms at which the event occurred. Defaults to time.time() * 1000

copy() a shallow copy of D[source]
property event_type

Event Type

property timestamp_ms

Event Timestamp

Logs

class newrelic_telemetry_sdk.log.Log(message, timestamp=None, **attributes)[source]

A log representing a log event in the New Relic logging UI

This data structure represents a single log event. These objects, when JSON serialized, can be sent to New Relic’s log api.

Parameters:
  • message (str) – The log message.

  • timestamp – (optional) The unix timestamp in milliseconds indicating when the log message was generated. Defaults to now.

  • **attributes – Additional attribute name=value pairs provided as keyword arguments.

static extract_record_data(record)[source]

Extracts data from a logging.LogRecord into a flat dictionary

Parameters:

record (logging.LogRecord) – The LogRecord from which to extract data.

>>> import logging
>>> record = logging.makeLogRecord({"msg": "Hello World"})
>>> result = Log.extract_record_data(record)
>>> isinstance(result, dict)
True
>>> result["message"]
'Hello World'
Return type:

dict

classmethod from_record(record)[source]

Convert a logging.LogRecord into a Log

This converts a logging.LogRecord to a New Relic Log, extracting any dimensions/labels from the record.

Parameters:

record (logging.LogRecord) – The LogRecord to convert.

>>> import logging
>>> record = logging.makeLogRecord({"msg": "Hello World"})
>>> log = Log.from_record(record)
>>> log["message"]
'Hello World'
class newrelic_telemetry_sdk.log.NewRelicLogFormatter(*args, **kwargs)[source]

New Relic Log Formatter

The New Relic log formatter converts LogRecord instances to strings via the format method.

The New Relic log format allows for arbitrary key/value pairs to be logged. This formatter automatically extracts all relevant information from the LogRecord (including extras) and places those key/values into a JSON object.

Since the format is not configurable, all formatter constructor arguments are ignored.

Usage:

>>> import logging
>>> record = logging.makeLogRecord({})
>>> formatter = NewRelicLogFormatter()
>>> result = formatter.format(record)
>>> isinstance(result, str)
True
format(record)[source]

Format the specified record as text

Parameters:

record (logging.LogRecord) – The LogRecord to format.

Return type:

str

Spans

class newrelic_telemetry_sdk.span.Span(name, tags=None, guid=None, trace_id=None, parent_id=None, start_time_ms=None, duration_ms=None)[source]

A span represented in the New Relic Distributed Tracing UI

This data structure represents a single event with duration as part of a distributed trace. Generally, this class should be used as a context manager.

Parameters:
  • name (str) – The name of the span.

  • tags (dict) – (optional) A set of tags that can be used to filter this span in the New Relic UI.

  • guid (str) – (optional) A random, unique identifier used to locate exactly 1 span in New Relic. This must be a unique identifier across all spans in a New Relic account.

  • trace_id (str) – (optional) A random identifier representing a group of spans known as a “trace”. Spans having the same trace_id are grouped into a single view.

  • parent_id (str) – (optional) The guid of the span that called this span.

  • start_time_ms (int) – (optional) A unix timestamp in milliseconds representing the start time of the span. Defaults to time.time() * 1000

  • duration_ms (int) – (optional) Total duration of the span in milliseconds.

Usage:

>>> import newrelic_telemetry_sdk
>>> with newrelic_telemetry_sdk.Span('span_name') as s:
...     pass
finish(finish_time_ms=None)[source]

Record the duration on this span.

Parameters:

finish_time_ms (int) – (optional) Timestamp in milliseconds. Defaults to time.time() * 1000

Batches

class newrelic_telemetry_sdk.metric_batch.MetricBatch(tags=None)[source]

Maps a metric identity to its aggregated value

This is used to hold unfinalized metrics for further aggregation until they are flushed to a backend.

Parameters:

tags (dict) – (optional) A dictionary of tags to attach to all flushes.

static create_identity(name, tags=None, typ=None)[source]

Creates a deterministic hashable identity for a metric

Parameters:
  • name (str) – The name of the metric.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

  • typ (str) – (optional) The metric type. One of “summary”, “count”, “gauge” or None. Default: None (gauge type).

flush()[source]

Flush all metrics from the batch

This method returns all metrics in the batch and a common block representing timestamp as the start time for the period since creation or last flush, and interval representing the total amount of time in milliseconds between flushes.

As a side effect, the batch’s interval is reset in anticipation of subsequent calls to flush.

Returns:

A tuple of (metrics, common)

Return type:

tuple

record_count(name, value, tags=None)[source]

Records a count metric

Parameters:
  • name (str) – The name of the metric.

  • value (int or float) – The metric value.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

record_gauge(name, value, tags=None)[source]

Records a gauge metric

Parameters:
  • name (str) – The name of the metric.

  • value (int or float) – The metric value.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

record_summary(name, value, tags=None)[source]

Records a summary metric

Parameters:
  • name (str) – The name of the metric.

  • value (int or float) – The metric value.

  • tags (dict) – (optional) A set of tags that can be used to filter this metric in the New Relic UI.

class newrelic_telemetry_sdk.batch.EventBatch[source]

Aggregates events, providing a record / flush interface.

flush()[source]

Flush all items from the batch

This method returns all items in the batch.

The batch is cleared as part of this operation.

Returns:

A tuple of (items,)

Return type:

tuple

record(item)

Merge an item into the batch

Parameters:

item – The item to merge into the batch.

class newrelic_telemetry_sdk.batch.LogBatch(tags=None)[source]

Aggregates logs, providing a record / flush interface.

Parameters:

tags (dict) – (optional) A dictionary of tags to attach to all flushes.

flush()

Flush all items from the batch

This method returns all items in the batch and a common block representing any tags if applicable.

The batch is cleared as part of this operation.

Returns:

A tuple of (items, common)

Return type:

tuple

record(item)

Merge an item into the batch

Parameters:

item – The item to merge into the batch.

class newrelic_telemetry_sdk.batch.SpanBatch(tags=None)[source]

Aggregates spans, providing a record / flush interface.

Parameters:

tags (dict) – (optional) A dictionary of tags to attach to all flushes.

flush()

Flush all items from the batch

This method returns all items in the batch and a common block representing any tags if applicable.

The batch is cleared as part of this operation.

Returns:

A tuple of (items, common)

Return type:

tuple

record(item)

Merge an item into the batch

Parameters:

item – The item to merge into the batch.

Harvester

class newrelic_telemetry_sdk.harvester.Harvester(client, batch, harvest_interval=5)[source]

Bases: Thread

Report data to New Relic at a fixed interval

The Harvester is a thread implementation which sends data to New Relic every harvest_interval seconds or until the data buffers are full.

The reporter will automatically handle error conditions which may occur such as:

  • Network timeouts

  • New Relic errors

Parameters:
Variables:
  • client (Client) – The telemetry SDK client where the harvester sends data.

  • batch (MetricBatch or EventBatch or SpanBatch) – The telemetry SDK batch where data is flushed from.

Example:

>>> import os
>>> license_key = os.environ.get("NEW_RELIC_LICENSE_KEY", "")
>>> from newrelic_telemetry_sdk import MetricBatch, MetricClient
>>> metric_client = MetricClient(license_key)
>>> metric_batch = MetricBatch()
>>> harvester = Harvester(metric_client, metric_batch)
>>> harvester.start()
>>> harvester.stop()
getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

stop(timeout=None)[source]

Terminate the harvester.

This will request and wait for the thread to terminate. The thread will not terminate immediately since any pending data will be sent.

When the timeout argument is present, this function will exit after at most timeout seconds. The thread may still be alive after this function exits if the timeout is reached but the thread hasn’t yet terminated.

Parameters:

timeout (int or float) – (optional) A timeout in seconds to wait for the thread to shut down or None to block until the thread exits (default: None)