newrelic-telemetry-sdk-go: github.com/newrelic/newrelic-telemetry-sdk-go/telemetry Index | Examples | Files

package telemetry

import "github.com/newrelic/newrelic-telemetry-sdk-go/telemetry"

Package telemetry is a client for the New Relic Metrics and Spans HTTP APIs.

This package stores metrics and spans, harvests them on a given schedule, and handles errors from the API response.

Code:

h, err := NewHarvester(
    // APIKey is the only required field and refers to your New Relic Insert API key.
    ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")),
    ConfigCommonAttributes(map[string]interface{}{
        "app.name": "myApplication",
    }),
    ConfigBasicErrorLogger(os.Stderr),
    ConfigBasicDebugLogger(os.Stdout),
)
if err != nil {
    fmt.Println(err)
}

// Record Gauge, Count, and Summary metrics using RecordMetric. These
// metrics are not aggregated.  This is useful for exporting metrics
// recorded by another system.
h.RecordMetric(Gauge{
    Timestamp: time.Now(),
    Value:     1,
    Name:      "myMetric",
    Attributes: map[string]interface{}{
        "color": "purple",
    },
})

// Record spans using RecordSpan.
h.RecordSpan(Span{
    ID:          "12345",
    TraceID:     "67890",
    Name:        "purple-span",
    Timestamp:   time.Now(),
    Duration:    time.Second,
    ServiceName: "ExampleApplication",
    Attributes: map[string]interface{}{
        "color": "purple",
    },
})

// Aggregate individual datapoints into metrics using the
// MetricAggregator.  You can do this in a single line:
h.MetricAggregator().Count("myCounter", map[string]interface{}{"color": "pink"}).Increment()
// Or keep a metric reference for fast accumulation:
counter := h.MetricAggregator().Count("myCounter", map[string]interface{}{"color": "pink"})
for i := 0; i < 100; i++ {
    counter.Increment()
}

Index

Examples

Package Files

aggregated_metrics.go attributes.go config.go doc.go events.go harvester.go metrics.go request.go spans.go utilities.go version.go

func ConfigAPIKey Uses

func ConfigAPIKey(key string) func(*Config)

ConfigAPIKey sets the Config's APIKey which is required and refers to your New Relic Insert API key.

func ConfigBasicAuditLogger Uses

func ConfigBasicAuditLogger(w io.Writer) func(*Config)

ConfigBasicAuditLogger sets the audit logger to a simple logger that logs to the writer provided.

func ConfigBasicDebugLogger Uses

func ConfigBasicDebugLogger(w io.Writer) func(*Config)

ConfigBasicDebugLogger sets the debug logger to a simple logger that logs to the writer provided.

func ConfigBasicErrorLogger Uses

func ConfigBasicErrorLogger(w io.Writer) func(*Config)

ConfigBasicErrorLogger sets the error logger to a simple logger that logs to the writer provided.

func ConfigCommonAttributes Uses

func ConfigCommonAttributes(attributes map[string]interface{}) func(*Config)

ConfigCommonAttributes adds the given attributes to the Config's CommonAttributes.

func ConfigEventsURLOverride Uses

func ConfigEventsURLOverride(url string) func(*Config)

ConfigEventsURLOverride sets the Config's EventsURLOverride field which overrides the events endpoint if not empty.

func ConfigHarvestPeriod Uses

func ConfigHarvestPeriod(period time.Duration) func(*Config)

ConfigHarvestPeriod sets the Config's HarvestPeriod field which controls the rate data is reported to New Relic. If it is set to zero then the Harvester will never report data unless HarvestNow is called.

func ConfigSpansURLOverride Uses

func ConfigSpansURLOverride(url string) func(*Config)

ConfigSpansURLOverride sets the Config's SpansURLOverride field which overrides the spans endpoint if not empty.

Code:

h, _ := NewHarvester(
    ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")),
    // Use ConfigSpansURLOverride to enable Infinite Tracing on the New
    // Relic Edge by passing it your Trace Observer URL, including scheme
    // and path.
    ConfigSpansURLOverride("https://nr-internal.aws-us-east-1.tracing.edge.nr-data.net/trace/v1"),
)
h.RecordSpan(Span{
    ID:          "12345",
    TraceID:     "67890",
    Name:        "purple-span",
    Timestamp:   time.Now(),
    Duration:    time.Second,
    ServiceName: "ExampleApplication",
    Attributes: map[string]interface{}{
        "color": "purple",
    },
})

type AggregatedCount Uses

type AggregatedCount struct {
    // contains filtered or unexported fields
}

AggregatedCount is the metric type that counts the number of times an event occurred. This counter is reset every time the data is reported, meaning the value reported represents the difference in count over the reporting time window.

Example possible uses:

* the number of messages put on a topic
* the number of HTTP requests
* the number of errors thrown
* the number of support tickets answered

func (*AggregatedCount) Increase Uses

func (c *AggregatedCount) Increase(val float64)

Increase increases the Count value by the number given. The value must be non-negative.

func (*AggregatedCount) Increment Uses

func (c *AggregatedCount) Increment()

Increment increases the Count value by one.

type AggregatedGauge Uses

type AggregatedGauge struct {
    // contains filtered or unexported fields
}

AggregatedGauge is the metric type that records a value that can increase or decrease. It generally represents the value for something at a particular moment in time. One typically records a AggregatedGauge value on a set interval.

Only the most recent AggregatedGauge metric value is reported over a given harvest period, all others are dropped.

Example possible uses:

* the temperature in a room
* the amount of memory currently in use for a process
* the bytes per second flowing into Kafka at this exact moment in time
* the current speed of your car

func (*AggregatedGauge) Value Uses

func (g *AggregatedGauge) Value(val float64)

Value records the value given.

type AggregatedSummary Uses

type AggregatedSummary struct {
    // contains filtered or unexported fields
}

AggregatedSummary is the metric type used for reporting aggregated information about discrete events. It provides the count, average, sum, min and max values over time. All fields are reset to 0 every reporting interval.

The final metric reported at the end of a harvest period is an aggregation. Values reported are the count of the number of metrics recorded, sum of all their values, minimum value recorded, and maximum value recorded.

Example possible uses:

* the duration and count of spans
* the duration and count of transactions
* the time each message spent in a queue

func (*AggregatedSummary) Record Uses

func (s *AggregatedSummary) Record(val float64)

Record adds an observation to a summary.

func (*AggregatedSummary) RecordDuration Uses

func (s *AggregatedSummary) RecordDuration(val time.Duration)

RecordDuration adds a duration observation to a summary. It records the value in milliseconds, New Relic's recommended duration units.

type Config Uses

type Config struct {
    // APIKey is required and refers to your New Relic Insert API key.
    APIKey string
    // Client is the http.Client used for making requests.
    Client *http.Client
    // HarvestTimeout is the total amount of time including retries that the
    // Harvester may use trying to harvest data.  By default, HarvestTimeout
    // is set to 15 seconds.
    HarvestTimeout time.Duration
    // CommonAttributes are the attributes to be applied to all metrics that
    // use this Config. They are not applied to spans.
    CommonAttributes map[string]interface{}
    // HarvestPeriod controls how frequently data will be sent to New Relic.
    // If HarvestPeriod is zero then NewHarvester will not spawn a goroutine
    // to send data and it is incumbent on the consumer to call
    // Harvester.HarvestNow when data should be sent. By default, HarvestPeriod
    // is set to 5 seconds.
    HarvestPeriod time.Duration
    // ErrorLogger receives errors that occur in this sdk.
    ErrorLogger func(map[string]interface{})
    // DebugLogger receives structured debug log messages.
    DebugLogger func(map[string]interface{})
    // AuditLogger receives structured log messages that include the
    // uncompressed data sent to New Relic.  Use this to log all data sent.
    AuditLogger func(map[string]interface{})
    // MetricsURLOverride overrides the metrics endpoint if not empty.
    MetricsURLOverride string
    // SpansURLOverride overrides the spans endpoint if not empty.
    //
    // To enable Infinite Tracing on the New Relic Edge, set this field to your
    // Trace Observer URL.  See
    // https://docs.newrelic.com/docs/understand-dependencies/distributed-tracing/enable-configure/enable-distributed-tracing
    SpansURLOverride string
    // EventsURLOverride overrides the events endpoint if not empty
    EventsURLOverride string
    // Product is added to the User-Agent header. eg. "NewRelic-Go-OpenCensus"
    Product string
    // ProductVersion is added to the User-Agent header. eg. "0.1.0".
    ProductVersion string
}

Config customizes the behavior of a Harvester.

type Count Uses

type Count struct {
    // Name is the name of this metric.
    Name string
    // Attributes is a map of attributes for this metric.
    Attributes map[string]interface{}
    // AttributesJSON is a json.RawMessage of attributes for this metric. It
    // will only be sent if Attributes is nil.
    AttributesJSON json.RawMessage
    // Value is the value of this metric.
    Value float64
    // Timestamp is the start time of this metric's interval.  If Timestamp
    // is unset then the Harvester's period start will be used.
    Timestamp time.Time
    // Interval is the length of time for this metric.  If Interval is unset
    // then the time between Harvester harvests will be used.
    Interval time.Duration
}

Count is the metric type that counts the number of times an event occurred. This counter should be reset every time the data is reported, meaning the value reported represents the difference in count over the reporting time window.

Example possible uses:

* the number of messages put on a topic
* the number of HTTP requests
* the number of errors thrown
* the number of support tickets answered

type Event Uses

type Event struct {
    // Required Fields:
    //
    // EventType is the name of the event
    EventType string
    // Timestamp is when this event happened.  If Timestamp is not set, it
    // will be assigned to time.Now() in Harvester.RecordEvent.
    Timestamp time.Time

    // Recommended Fields:
    //
    // Attributes is a map of user specified data on this event.  The map
    // values can be any of bool, number, or string.
    Attributes map[string]interface{}
    // AttributesJSON is a json.RawMessage of attributes for this metric. It
    // will only be sent if Attributes is nil.
    AttributesJSON json.RawMessage
}

Event is a unique set of data that happened at a specific point in time

type Gauge Uses

type Gauge struct {
    // Name is the name of this metric.
    Name string
    // Attributes is a map of attributes for this metric.
    Attributes map[string]interface{}
    // AttributesJSON is a json.RawMessage of attributes for this metric. It
    // will only be sent if Attributes is nil.
    AttributesJSON json.RawMessage
    // Value is the value of this metric.
    Value float64
    // Timestamp is the time at which this metric was gathered.  If
    // Timestamp is unset then the Harvester's period start will be used.
    Timestamp time.Time
}

Gauge is the metric type that records a value that can increase or decrease. It generally represents the value for something at a particular moment in time. One typically records a Gauge value on a set interval.

Example possible uses:

* the temperature in a room
* the amount of memory currently in use for a process
* the bytes per second flowing into Kafka at this exact moment in time
* the current speed of your car

type Harvester Uses

type Harvester struct {
    // contains filtered or unexported fields
}

Harvester aggregates and reports metrics and spans.

func NewHarvester Uses

func NewHarvester(options ...func(*Config)) (*Harvester, error)

NewHarvester creates a new harvester.

Code:

h, err := NewHarvester(
    ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")),
)
if err != nil {
    fmt.Println(err)
}
h.RecordMetric(Gauge{
    Timestamp: time.Now(),
    Value:     1,
    Name:      "myMetric",
    Attributes: map[string]interface{}{
        "color": "purple",
    },
})

func (*Harvester) HarvestNow Uses

func (h *Harvester) HarvestNow(ct context.Context)

HarvestNow sends metric and span data to New Relic. This method blocks until all data has been sent successfully or the Config.HarvestTimeout timeout has elapsed. This method can be used with a zero Config.HarvestPeriod value to control exactly when data is sent to New Relic servers.

func (*Harvester) MetricAggregator Uses

func (h *Harvester) MetricAggregator() *MetricAggregator

MetricAggregator returns a metric aggregator. Use this instead of RecordMetric if you have individual data points that you would like to combine into metrics.

func (*Harvester) RecordEvent Uses

func (h *Harvester) RecordEvent(e Event) error

RecordEvent records the given event.

func (*Harvester) RecordMetric Uses

func (h *Harvester) RecordMetric(m Metric)

RecordMetric adds a fully formed metric. This metric is not aggregated with any other metrics and is never dropped. The Timestamp field must be specified on Gauge metrics. The Timestamp/Interval fields on Count and Summary are optional and will be assumed to be the harvester batch times if unset. Use MetricAggregator() instead to aggregate metrics.

Code:

h, _ := NewHarvester(
    ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")),
)
start := time.Now()
h.RecordMetric(Count{
    Name:           "myCount",
    AttributesJSON: json.RawMessage(`{"zip":"zap"}`),
    Value:          123,
    Timestamp:      start,
    Interval:       5 * time.Second,
})

func (*Harvester) RecordSpan Uses

func (h *Harvester) RecordSpan(s Span) error

RecordSpan records the given span.

type Metric Uses

type Metric interface {
    // contains filtered or unexported methods
}

Metric is implemented by Count, Gauge, and Summary.

type MetricAggregator Uses

type MetricAggregator struct {
    // contains filtered or unexported fields
}

MetricAggregator is used to aggregate individual data points into metrics.

func (*MetricAggregator) Count Uses

func (ag *MetricAggregator) Count(name string, attributes map[string]interface{}) *AggregatedCount

Count creates a new AggregatedCount metric.

Code:

h, _ := NewHarvester(ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")))
count := h.MetricAggregator().Count("myCount", map[string]interface{}{"zip": "zap"})
count.Increment()

func (*MetricAggregator) Gauge Uses

func (ag *MetricAggregator) Gauge(name string, attributes map[string]interface{}) *AggregatedGauge

Gauge creates a new AggregatedGauge metric.

Code:

h, _ := NewHarvester(ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")))
gauge := h.MetricAggregator().Gauge("temperature", map[string]interface{}{"zip": "zap"})
gauge.Value(23.4)

func (*MetricAggregator) Summary Uses

func (ag *MetricAggregator) Summary(name string, attributes map[string]interface{}) *AggregatedSummary

Summary creates a new AggregatedSummary metric.

Code:

h, _ := NewHarvester(ConfigAPIKey(os.Getenv("NEW_RELIC_INSERT_API_KEY")))
summary := h.MetricAggregator().Summary("mySummary", map[string]interface{}{"zip": "zap"})
summary.RecordDuration(3 * time.Second)

type Span Uses

type Span struct {
    // Required Fields:
    //
    // ID is a unique identifier for this span.
    ID  string
    // TraceID is a unique identifier shared by all spans within a single
    // trace.
    TraceID string
    // Timestamp is when this span started.  If Timestamp is not set, it
    // will be assigned to time.Now() in Harvester.RecordSpan.
    Timestamp time.Time

    // Recommended Fields:
    //
    // Name is the name of this span.
    Name string
    // ParentID is the span id of the previous caller of this span.  This
    // can be empty if this is the first span.
    ParentID string
    // Duration is the duration of this span.  This field will be reported
    // in milliseconds.
    Duration time.Duration
    // ServiceName is the name of the service that created this span.
    ServiceName string

    // Additional Fields:
    //
    // Attributes is a map of user specified tags on this span.  The map
    // values can be any of bool, number, or string.
    Attributes map[string]interface{}
    // AttributesJSON is a json.RawMessage of attributes for this metric. It
    // will only be sent if Attributes is nil.
    AttributesJSON json.RawMessage
    // Events is a slice of events that occurred during the execution of a span.
    // This feature is a work in progress.
    Events []Event
}

Span is a distributed tracing span.

type Summary Uses

type Summary struct {
    // Name is the name of this metric.
    Name string
    // Attributes is a map of attributes for this metric.
    Attributes map[string]interface{}
    // AttributesJSON is a json.RawMessage of attributes for this metric. It
    // will only be sent if Attributes is nil.
    AttributesJSON json.RawMessage
    // Count is the count of occurrences of this metric for this time period.
    Count float64
    // Sum is the sum of all occurrences of this metric for this time period.
    Sum float64
    // Min is the smallest value recorded of this metric for this time period.
    Min float64
    // Max is the largest value recorded of this metric for this time period.
    Max float64
    // Timestamp is the start time of this metric's interval.   If Timestamp
    // is unset then the Harvester's period start will be used.
    Timestamp time.Time
    // Interval is the length of time for this metric.  If Interval is unset
    // then the time between Harvester harvests will be used.
    Interval time.Duration
}

Summary is the metric type used for reporting aggregated information about discrete events. It provides the count, average, sum, min and max values over time. All fields should be reset to 0 every reporting interval.

Example possible uses:

* the duration and count of spans
* the duration and count of transactions
* the time each message spent in a queue

Package telemetry imports 14 packages (graph) and is imported by 13 packages. Updated 2020-12-15. Refresh now. Tools for package owners.