Documentation ¶
Overview ¶
Package signalfx provides several mechanisms to easily send datapoints to SignalFx
Users of this package will primarily interact with the Reporter type. Reporter is an object that tracks DataPoints and manages a Client.
For most cases, a reporter is created as follows (assuming $SFX_API_TOKEN is set in the environment)
reporter := signalfx.Newreporter(signalfx.NewConfig(), nil)
DataPoints are created and tracked via various methods on Reporter like:
inc, _ := reporter.NewInc("SomeIncrementer", nil) inc.Inc(1)
And when ready to send the datapoints to SignalFx, just run
_, err := reporter.Report(context.Background())
There are several types of metrics available, Gauge, Counter, CumulativeCounter and Bucket. Bucket is provided to track multiple aspects of a single metric such as number of times data has been added, the sum of each value added, the min and max values added, etc.
The value for Gauge, Counter and CumulativeCounter may be any type of int, float, string, nil or pointer or a Getter that returns one of those types. If val is a pointer type, its value should not be changed, when tracked by a Reporter, except within a PreReportCallback, for goroutine safety.
The Getter interface can also be used to as a value for a DataPoint. It may only return any kind of int, float, string, nil or a pointer to one of those types. Get will be called when Reporter.Report() is executed. Getters must implement their own goroutine safety with Get as required. There are a few types that implement Getter that can be used directly.
GetterFunc can wrap a function with the correct signature so that it satisfies the Getter interface:
f := signalfx.GetterFunc(func() (interface{}, error) { return 5, nil }) reporter.NewGauge("GetterFunc", f, nil)
Value can wrap the basic types (ints, floats, strings, nil and pointers to them) but is not goroutine safe. Changes should only be made in a PreReportCallback.
i := 5 reporter.NewCounter("SomeCounter", signalfx.Value(&i), nil) reporter.AddPreReportCallback(func() { i++ })
There are also Int32, Int64, Uint32 and Uint64 types available whose methods are goroutine safe and can also be safely changed if via atomic methods.
val := signalfx.NewInt64(0) counter := reporter.NewCounter("SomeOtherCounter", val, nil) val.Inc(1) atomic.AddInt64((*int64)(val), 1)
Index ¶
- Constants
- Variables
- type Bucket
- func (b *Bucket) Add(val int64)
- func (b *Bucket) Clone() *Bucket
- func (b *Bucket) Count() uint64
- func (b *Bucket) DataPoints() []DataPoint
- func (b *Bucket) Dimensions() map[string]string
- func (b *Bucket) Disable(metrics ...int)
- func (b *Bucket) Equal(r *Bucket) bool
- func (b *Bucket) Max() int64
- func (b *Bucket) Metric() string
- func (b *Bucket) Min() int64
- func (b *Bucket) RemoveDimension(keys ...string)
- func (b *Bucket) SetDimension(key, value string)
- func (b *Bucket) SetDimensions(dims map[string]string)
- func (b *Bucket) SetMetric(name string)
- func (b *Bucket) Sum() int64
- func (b *Bucket) SumOfSquares() int64
- type Client
- type Config
- type Counter
- type CumulativeCounter
- type DataPoint
- type DataPointCallback
- type ErrContext
- type ErrInvalidBody
- type ErrJSON
- type ErrMarshal
- type ErrPost
- type ErrResponse
- type ErrStatus
- type Gauge
- type Getter
- type GetterFunc
- type GoMetrics
- type HookedMetric
- type Int32
- type Int64
- type Metric
- type MetricType
- type Reporter
- func (r *Reporter) Add(dp DataPoint)
- func (r *Reporter) AddDataPointsCallback(f DataPointCallback)
- func (r *Reporter) AddPreReportCallback(f func())
- func (r *Reporter) DeleteDimension(key string)
- func (r *Reporter) Inc(metric string, dimensions map[string]string, delta uint64) error
- func (r *Reporter) NewBucket(metric string, dimensions map[string]string) *Bucket
- func (r *Reporter) Record(metric string, dimensions map[string]string, value int64) error
- func (r *Reporter) RemoveBucket(bs ...*Bucket)
- func (r *Reporter) Report(ctx context.Context) ([]DataPoint, error)
- func (r *Reporter) RunInBackground(interval time.Duration) (cancel func())
- func (r *Reporter) Sample(metric string, dimensions map[string]string, value uint64) error
- func (r *Reporter) SetDimension(key, value string)
- func (r *Reporter) SetPrefix(prefix string)
- func (r *Reporter) Track(m ...Metric)
- func (r *Reporter) Untrack(m ...Metric)
- type StableGauge
- type Subtractor
- type Uint32
- type Uint64
- type WrappedCounter
- type WrappedCumulativeCounter
- type WrappedGauge
Examples ¶
Constants ¶
const ( // BucketMetricCount represents the count of datapoints seen BucketMetricCount = iota // BucketMetricMin represents the smallest datapoint seen BucketMetricMin = iota // BucketMetricMax represents the largest datapoint seen BucketMetricMax = iota // BucketMetricSum represents the sum of all datapoints seen BucketMetricSum = iota // BucketMetricSumOfSquares represents the sum of squares of all datapoints seen BucketMetricSumOfSquares = iota )
const ( // ClientVersion is the version of this package, sent as part of the default // user agent ClientVersion = "0.1.0" // DefaultMaxIdleConnections is the maximum idle (keep-alive) connections to // maintain with the signalfx server. DefaultMaxIdleConnections = 2 // DefaultTimeoutDuration is the timeout used for connecting to the signalfx // server, including name resolution, as well as weaiting for headers DefaultTimeoutDuration = 60 * time.Second // DefaultURL is the URL used to send datapoints to signalfx DefaultURL = "https://ingest.signalfx.com/v2/datapoint" // DefaultUserAgent is the user agent sent to signalfx DefaultUserAgent = "go-signalfx/" + ClientVersion )
const (
// TokenHeader is the header on which SignalFx looks for the api token
TokenHeader = "X-SF-TOKEN"
)
Variables ¶
var ( // ErrIllegalType is returned when trying to set the Datum value using an // unsupported type ErrIllegalType = fmt.Errorf("illegal value type") // ErrNoMetricName is returned when trying to create a DataPoint without a // Metric name ErrNoMetricName = fmt.Errorf("no metric name") )
Functions ¶
This section is empty.
Types ¶
type Bucket ¶
type Bucket struct {
// contains filtered or unexported fields
}
A Bucket trakcs groups of values, reporting metrics as gauges and resetting each time it reports. All operations on Buckets are goroutine safe.
Example ¶
reporter := NewReporter(NewConfig(), map[string]string{ "test_dimension0": "value0", "test_dimension1": "value1", }) bucket := reporter.NewBucket("TestBucket", map[string]string{ "test_bucket_dimension0": "bucket0", "test_bucket_dimension1": "bucket1", }) bucket.Add(5) bucket.Add(9) fmt.Printf("Metric: %s\n", bucket.Metric()) fmt.Printf("Count: %d\n", bucket.Count()) fmt.Printf("Min: %d\n", bucket.Min()) fmt.Printf("Max: %d\n", bucket.Max()) fmt.Printf("Sum: %d\n", bucket.Sum()) fmt.Printf("SumOfSquares: %d\n", bucket.SumOfSquares()) dps, err := reporter.Report(context.Background()) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Metrics:", len(dps)) }
Output: Metric: TestBucket Count: 2 Min: 5 Max: 9 Sum: 14 SumOfSquares: 106 Metrics: 5
func NewBucket ¶
NewBucket creates a new Bucket. Because the passed in dimensions can not be locked by this method, it is important that the caller ensures its state does not change for the duration of the operation.
func (*Bucket) Add ¶
Add an item to the Bucket, later reporting the result in the next report cycle.
func (*Bucket) DataPoints ¶
DataPoints returns a DataPoints object with DataPoint values for Count, Sum, SumOfSquares, Min and Max (if set). Note that this resets all values. If no values have been added to the bucket since the last report, it returns 0 for count, sum and sum-of-squares, omitting max and min. If the count is higher than may be represented in an int64, then the count will be omitted.
func (*Bucket) Dimensions ¶
Dimensions returns a copy of the dimensions of the Bucket. Changes are not reflected inside the Bucket itself.
func (*Bucket) Disable ¶
Disable disables the given metrics for this bucket. They will be collected, but not reported.
func (*Bucket) RemoveDimension ¶
RemoveDimension removes one or more dimensions with the given keys
func (*Bucket) SetDimension ¶
SetDimension adds or overwrites the dimension at key with value. If the key or value is empty, no changes are made
func (*Bucket) SetDimensions ¶
SetDimensions adds or overwrites multiple dimensions. Because the passed in dimensions can not be locked by this method, it is important that the caller ensures its state does not change for the duration of the operation.
func (*Bucket) SumOfSquares ¶
SumOfSquares returns the sum of the square of all items added to the Bucket
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
A Client is used to send datapoints to SignalFx
type Config ¶
type Config struct { MaxIdleConnections uint32 TimeoutDuration time.Duration URL string AuthToken string UserAgent string TLSInsecureSkipVerify bool Logger io.Writer }
Config is used to configure a Client. It should be created with New to have default values automatically set.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
A Counter represents a Counter metric (i.e., its internal value is reset to zero by its PostReportHook, although this should not be meaningful to client code).
func NewCounter ¶
NewCounter returns a new Counter with the specified parameters. It does not copy the dimensions; client code should take care not to modify them in a goroutine-unsafe manner.
func (*Counter) DataPoint ¶
DataPoint returns a DataPoint reflecting the Counter's internal state. It does not reset that state, leaving that to PostReportHook.
func (*Counter) PostReportHook ¶
PostReportHook resets a Counter's internal state. It does this intelligently, by subtracting the successfully-reported value from the state (this way, the Counter may have been incremented in between the create of the reported DataPoint and the reset, and the state will be consistent). Calling PostReportHook with a negative value will result in a panic: counters may never take negative values.
In the normal case, PostReportHook should only be called by Reporter.Report. Its argument must always be the value of a DataPoint previously returned by Counter.DataPoint.
type CumulativeCounter ¶
type CumulativeCounter struct {
// contains filtered or unexported fields
}
A CumulativeCounter represents a cumulative counter, that is a counter whose internal state monotonically increases, and which never reports a value it has previously reported. It may be useful in order to track the value of counters over which one has no control.
func NewCumulativeCounter ¶
func NewCumulativeCounter(metric string, dimensions map[string]string, value uint64) *CumulativeCounter
NewCumulativeCounter returns a newly-created CumulativeCounter with the indicated initial state. It neither copies nor modifies the dimensions; client code should not modify dimensions in a goroutine-unsafe manner.
func (*CumulativeCounter) DataPoint ¶
func (cc *CumulativeCounter) DataPoint() *DataPoint
DataPoint returns a DataPoint reflecting the internal state of the CumulativeCounter. If that state has previously been successfully reported (as recorded by PostReportHook), it will simply return nil.
func (*CumulativeCounter) PostReportHook ¶
func (cc *CumulativeCounter) PostReportHook(v int64)
PostReportHook records a reported value of a CumulativeCounter. It will do the right thing if a yet-higher value has been reported in the interval since DataPoint was called. Calling PostReportHook with a negative value will result in a panic: counters may never take negative values.
In the normal case, PostReportHook should only be called by Reporter.Report. Its argument must always be the value of a DataPoint previously returned by CumulativeCounter.DataPoint.
func (*CumulativeCounter) Sample ¶
func (cc *CumulativeCounter) Sample(delta uint64)
Sample updates the CumulativeCounter's internal state.
type DataPoint ¶
type DataPoint struct { Metric string Type MetricType Value int64 Timestamp time.Time Dimensions map[string]string }
A DataPoint represents a single datum within a metric time series.
type DataPointCallback ¶
type DataPointCallback func() []DataPoint
DataPointCallback is a functional callback that can be passed to DataPointCallback as a way to have the caller calculate and return their own datapoints
type ErrContext ¶
type ErrContext error
ErrContext is returned when the context is canceled or times out
type ErrInvalidBody ¶
type ErrInvalidBody struct {
Body string
}
ErrInvalidBody is returned when the signalfx response is anything other than "OK"
func (ErrInvalidBody) Error ¶
func (e ErrInvalidBody) Error() string
type ErrJSON ¶
type ErrJSON struct {
Body []byte
}
ErrJSON is returned when there is an error parsing the signalfx JSON response
type ErrMarshal ¶
type ErrMarshal error
ErrMarshal is returned when there is an error marshaling the DataPoints
type ErrPost ¶
type ErrPost error
ErrPost is returned when there is an error posting data to signalfx
type ErrResponse ¶
type ErrResponse error
ErrResponse is returned when there is an error reading the signalfx response
type Gauge ¶
type Gauge struct {
// contains filtered or unexported fields
}
A Gauge represents a metric which tracks a single value. This value may be positive or negative, and may increase or decrease over time. It neither copies nor modifies its dimension; client code should ensure that it does not modify them in a thread-unsafe manner. Unlike counters and cumulative counters, gauges are always reported.
type Getter ¶
type Getter interface {
Get() (interface{}, error)
}
Getter is an interface that is used by DataPoint. Get must return any kind of int, float, nil or pointer to those types (a nil indicates an absent value). Any other type is invalid. It no longer supports strings.
func Value ¶
func Value(val interface{}) Getter
Value is a convenience function for making a value satisfy the Getter interface. val can be any type of int, float, nil or pointer to those types. If val is a pointer type, its value should not be changed, when in a Reporter, except within a PreReportCallback, for goroutine safety.
Example ¶
val := 5 cumulative := WrapCumulativeCounter("cumulative", nil, Value(&val)) val = 9 cdp := cumulative.DataPoint() fmt.Println(cdp.Value)
Output: 9
type GetterFunc ¶
type GetterFunc func() (interface{}, error)
The GetterFunc type is an adapter to allow the use of ordinary functions as DataPoint Getters. If f is a function with the appropriate signature, GetterFunc(f) is a Getter object that calls f. f() must return a value that is any type of int, float, nil or pointer to those types.
Example ¶
val := 5 count := WrapGauge("count", nil, GetterFunc(func() (interface{}, error) { return val, nil })) val++ cdp := count.DataPoint() fmt.Println(cdp.Value)
Output: 6
type GoMetrics ¶
type GoMetrics struct {
// contains filtered or unexported fields
}
GoMetrics gathers and reports generally useful go system stats for the reporter
func NewGoMetrics ¶
NewGoMetrics registers the reporter to report go system metrics. You should provide enough dims to differentiate this set of metrics.
type HookedMetric ¶
type HookedMetric interface { Metric // PostReportHook is intended to only be called by // Reporter.Report. Its argument should be the same as the // value of a DataPoint previously returned by // Metric.DataPoint; it should only be called once per such // DataPoint. If it is called with any other value, results // are undefined (explicitly: PostReportHook may panic if // called with an invalid value). // // Clients of go-signalfx should not normally call // PostReportHook, unless it's doing something like // implementing its own reporting functionality. PostReportHook(reportedValue int64) }
A HookedMetric has a PostReportHook method, which is called by Reporter.Report after successfully reporting a value. The intended use case is with Counters and CumulativeCounters, which need to reset some saved state once it's been reported, but it might be useful for other user-specified metric types.
type Int32 ¶
type Int32 int32
Int32 satisfies the Getter interface using an atomic operation. Therefore it is safe to modify, when in a Reporter, outside the PreReportCallback as long as it is done so atomically.
type Int64 ¶
type Int64 int64
Int64 satisfies the Getter interface using an atomic operation. Therefore it is safe to modify, when in a Reporter, outside the PreReportCallback as long as it is done so atomically.
type Metric ¶
type Metric interface { // DataPoint returns the value of the metric at the current // point in time. If it has no value at the present point in // time, return nil. A Reporter will add its metric prefix // and default dimensions to the metric and dimensions // indicated in the DataPoint. DataPoint() *DataPoint }
A Metric represents a producer of datapoints (i.e., a metric time series). While individual datapoints are not goroutine-safe (they are owned by one goroutine at a time), metrics should be.
type MetricType ¶
type MetricType sfxproto.MetricType
MetricType exports sfxproto.MetricType to client code.
const ( CounterType MetricType = MetricType(sfxproto.MetricType_COUNTER) CumulativeCounterType MetricType = MetricType(sfxproto.MetricType_CUMULATIVE_COUNTER) GaugeType MetricType = MetricType(sfxproto.MetricType_GAUGE) )
Only counters, cumulative counters and gauges are currently-supported metric types.
type Reporter ¶
type Reporter struct {
// contains filtered or unexported fields
}
Reporter is an object that tracks DataPoints and manages a Client. It is the recommended way to send data to SignalFX.
Example ¶
// auth token will be taken from $SFX_API_TOKEN if it exists // for this example, it must be set correctly reporter := NewReporter(NewConfig(), map[string]string{ "test_dimension0": "value0", "test_dimension1": "value1", }) gval := 0 gauge := WrapGauge( "TestGauge", map[string]string{ "test_gauge_dimension0": "gauge0", "test_gauge_dimension1": "gauge1", }, Value(&gval), ) reporter.Track(gauge) i := NewCounter( "TestInt64", map[string]string{ "test_incrementer_dimension0": "incrementer0", "test_incrementer_dimension1": "incrementer1", }, 0, ) reporter.Track(i) cval := int64(0) cumulative := WrapCumulativeCounter( "TestCumulative", map[string]string{ "test_cumulative_dimension0": "cumulative0", "test_cumulative_dimension1": "cumulative1", }, Value(&cval), ) reporter.Track(cumulative) atomic.AddInt64(&cval, 1) reporter.AddPreReportCallback(func() { // modify these values safely within this callback // modification of pointer values otherwise is not goroutine safe gval = 7 }) // incrementers are goroutine safe i.Inc(1) i.Inc(5) dps, err := reporter.Report(context.Background()) if err != nil { fmt.Printf("Error: %v\n", err) } else { // find the associated datapoints for each metric var gval, ival, cval int64 for _, dp := range dps { switch dp.Metric { case "TestGauge": gval = dp.Value case "TestInt64": ival = dp.Value case "TestCumulative": cval = dp.Value default: panic("this should never happen") } } fmt.Printf("Gauge: %d\n", gval) fmt.Printf("Incrementer: %d\n", ival) fmt.Printf("Cumulative: %d\n", cval) fmt.Printf("Metrics: %d\n", len(dps)) // FIXME: Fix this line… }
Output: Gauge: 7 Incrementer: 6 Cumulative: 1 Metrics: 3
func NewReporter ¶
NewReporter returns a new Reporter object. Any dimensions supplied will be appended to all DataPoints sent to SignalFX. config is copied, so future changes to the external config object are not reflected within the reporter.
func (*Reporter) Add ¶
Add adds a single DataPoint to a Reporter; it will be reported and, once successfully reported, deleted.
func (*Reporter) AddDataPointsCallback ¶
func (r *Reporter) AddDataPointsCallback(f DataPointCallback)
AddDataPointsCallback adds a callback that itself will generate datapoints to report/
func (*Reporter) AddPreReportCallback ¶
func (r *Reporter) AddPreReportCallback(f func())
AddPreReportCallback adds a function that is called before Report(). This is useful for refetching things like runtime.Memstats() so they are only fetched once per report() call. If a DataPoint
func (*Reporter) DeleteDimension ¶
DeleteDimension deletes a default dimension.
func (*Reporter) Inc ¶
Inc adds a one-shot data point for a counter with the indicated delta since the last report. If delta is greater than the maximum possible int64, Inc will panic.
func (*Reporter) NewBucket ¶
NewBucket creates a new Bucket object that is tracked by the Reporter. Buckets are goroutine safe.
func (*Reporter) Record ¶
Record adds a one-shot data point for a gauge with the indicated value at this point in time.
func (*Reporter) RemoveBucket ¶
RemoveBucket takes Bucket(s) out of the set being tracked by the Reporter
func (*Reporter) Report ¶
Report sends all tracked DataPoints to SignalFX. PreReportCallbacks will be run before building the dataset to send. DataPoint callbacks will be executed and added to the dataset, but do not become tracked by the Reporter.
func (*Reporter) RunInBackground ¶
RunInBackground starts a goroutine which calls Reporter.Report on the specified interval. It returns a function which may be used to cancel the backgrounding.
func (*Reporter) Sample ¶
Sample adds a one-shot data point for a cumulative counter with the indicated value at this point in time.
func (*Reporter) SetDimension ¶
SetDimension sets a default dimension which will be reported for all data points.
func (*Reporter) SetPrefix ¶
SetPrefix sets a particular prefix for all metrics reported by this reporter.
type StableGauge ¶
type StableGauge struct {
// contains filtered or unexported fields
}
A StableGauge is the same as a Guage, but will not report the same value multiple times sequentially.
func NewStableGauge ¶
func NewStableGauge(metric string, dimensions map[string]string, value int64) *StableGauge
NewStableGauge returns a new StableGauge with the indicated initial state.
func (*StableGauge) DataPoint ¶
func (g *StableGauge) DataPoint() *DataPoint
DataPoint returns a DataPoint reflecting the StableGauge's internal state at the current point in time, if it differs since the last call.
func (*StableGauge) Record ¶
func (g *StableGauge) Record(value int64)
Record sets a gauge's internal state to the indicated value.
type Subtractor ¶
A Subtractor is a Getter which is also subtractable.
type Uint32 ¶
type Uint32 uint32
Uint32 satisfies the Getter interface using an atomic operation. Therefore it is safe to modify, when in a Reporter, outside the PreReportCallback as long as it is done so atomically.
type Uint64 ¶
type Uint64 uint64
Uint64 satisfies the Getter interface using an atomic operation. Therefore it is safe to modify, when in a Reporter, outside the PreReportCallback as long as it is done so atomically.
type WrappedCounter ¶
type WrappedCounter struct {
// contains filtered or unexported fields
}
A WrappedCounter wraps Subtractor—a type of Value which may be gotten from or subtracted from—in order to provide an easy-to-use way to monitor state elsewhere within an application. Of note to client code, this means that the wrapped counter's value will be reset after each successful report. Clients wishing to have a monotonically-increasing counter should instead use a WrappedCumulativeCounter.
func WrapCounter ¶
func WrapCounter( metric string, dimensions map[string]string, value Subtractor, ) *WrappedCounter
WrapCounter returns a WrappedCounter wrapping value.
func (*WrappedCounter) DataPoint ¶
func (c *WrappedCounter) DataPoint() *DataPoint
DataPoint returns a DataPoint representing the current state of the wrapped counter value. If that current state is negative or zero, then no DataPoint will be returned.
func (*WrappedCounter) PostReportHook ¶
func (c *WrappedCounter) PostReportHook(v int64)
PostReportHook resets a counter by subtracting the successfully-reported value from its internal state. Passing in a negative value will result in a panic, as a WrappedCounter's internal state may not be negative.
type WrappedCumulativeCounter ¶
type WrappedCumulativeCounter struct {
// contains filtered or unexported fields
}
A WrappedCumulativeCounter wraps a value elsewhere in memory. That value must monotonically increase.
func WrapCumulativeCounter ¶
func WrapCumulativeCounter( metric string, dimensions map[string]string, value Getter, ) *WrappedCumulativeCounter
WrapCumulativeCounter wraps a cumulative counter elsewhere in memory, returning a newly-allocated WrappedCumulativeCounter. Dimensions are neither copied nor modified; client code should take care not to modify them in a goroutine-unsafe manner.
func (*WrappedCumulativeCounter) DataPoint ¶
func (cc *WrappedCumulativeCounter) DataPoint() *DataPoint
DataPoint returns a DataPoint reflecting the internal state of the WrappedCumulativeCounter at a particular point in time. It will return nil of the counter's value or higher has been previously reported.
func (*WrappedCumulativeCounter) PostReportHook ¶
func (cc *WrappedCumulativeCounter) PostReportHook(v int64)
PostReportHook records that a particular value has been successfully reported. If that value is negative, it will panic, as cumulative counter values may never be negative. It is goroutine-safe.
type WrappedGauge ¶
type WrappedGauge struct {
// contains filtered or unexported fields
}
A WrappedGauge wraps a Getter elsewhere in memory.
func WrapGauge ¶
func WrapGauge( metric string, dimensions map[string]string, value Getter, ) *WrappedGauge
WrapGauge wraps a value in memory. It neither copies nor updates its dimensions; client code should take care not to modify them in a goroutine-unsafe manner.
func (*WrappedGauge) DataPoint ¶
func (c *WrappedGauge) DataPoint() *DataPoint
DataPoint returns a DataPoint reflecting the current value of the WrappedGauge.