libhoney

package module
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2018 License: Apache-2.0 Imports: 19 Imported by: 0

README

libhoney Build Status

Go library for sending events to Honeycomb. (For more information, see the documentation and Go SDK guide.)

Installation:

go get -v github.com/honeycombio/libhoney-go

Documentation

A godoc API reference is available at https://godoc.org/github.com/honeycombio/libhoney-go

Example

Honeycomb can calculate all sorts of statistics, so send the values you care about and let us crunch the averages, percentiles, lower/upper bounds, cardinality -- whatever you want -- for you.

import "github.com/honeycombio/libhoney-go"

// Call Init to configure libhoney
libhoney.Init(libhoney.Config{
  WriteKey: "YOUR_WRITE_KEY",
  Dataset: "honeycomb-golang-example",
})
defer libhoney.Close() // Flush any pending calls to Honeycomb

libhoney.SendNow(map[string]interface{}{
  "duration_ms": 153.12,
  "method": "get",
  "hostname": "appserver15",
  "payload_length": 27,
})

See the examples directory for sample code demonstrating how to use events, builders, fields, and dynamic fields.

Contributions

Features, bug fixes and other changes to libhoney are gladly accepted. Please open issues or a pull request with your change. Remember to add your name to the CONTRIBUTORS file!

All contributions will be released under the Apache License 2.0.

Documentation

Overview

Package libhoney is a client library for sending data to https://honeycomb.io

Summary

libhoney aims to make it as easy as possible to create events and send them on into Honeycomb.

See https://honeycomb.io/docs for background on this library.

Look in the examples/ directory for a complete example using libhoney.

Example
// call Init before using libhoney
Init(Config{
	WriteKey:   "abcabc123123defdef456456",
	Dataset:    "Example Service",
	SampleRate: 1,
})
// when all done, call close
defer Close()

// create an event, add fields
ev := NewEvent()
ev.AddField("duration_ms", 153.12)
ev.AddField("method", "get")
// send the event
ev.Send()
Output:

Index

Examples

Constants

View Source
const (

	// DefaultMaxBatchSize how many events to collect in a batch
	DefaultMaxBatchSize = 50
	// DefaultBatchTimeout how frequently to send unfilled batches
	DefaultBatchTimeout = 100 * time.Millisecond
	// DefaultMaxConcurrentBatches how many batches to maintain in parallel
	DefaultMaxConcurrentBatches = 80
	// DefaultPendingWorkCapacity how many events to queue up for busy batches
	DefaultPendingWorkCapacity = 10000
)

Variables

View Source
var UserAgentAddition string

UserAgentAddition is a variable set at compile time via -ldflags to allow you to augment the "User-Agent" header that libhoney sends along with each event. The default User-Agent is "libhoney-go/<version>". If you set this variable, its contents will be appended to the User-Agent string, separated by a space. The expected format is product-name/version, eg "myapp/1.0"

Functions

func Add

func Add(data interface{}) error

Add adds its data to the global scope. It adds all fields in a struct or all keys in a map as individual Fields. These metrics will be inherited by all builders and events.

func AddDynamicField

func AddDynamicField(name string, fn func() interface{}) error

AddDynamicField takes a field name and a function that will generate values for that metric. The function is called once every time a NewEvent() is created and added as a field (with name as the key) to the newly created event.

Example
// adds the number of goroutines running at event
// creation time to every event sent to Honeycomb.
AddDynamicField("num_goroutines",
	func() interface{} { return runtime.NumGoroutine() })
Output:

func AddField

func AddField(name string, val interface{})

AddField adds a Field to the global scope. This metric will be inherited by all builders and events.

func Close

func Close()

Close waits for all in-flight messages to be sent. You should call Close() before app termination.

func Init

func Init(config Config) error

Init is called on app initialization and passed a Config struct, which configures default behavior. Use of package-level functions (e.g. SendNow()) require that WriteKey and Dataset are defined.

Otherwise, if WriteKey and DataSet are absent or a Config is not provided, they may be specified later, either on a Builder or an Event. WriteKey, Dataset, SampleRate, and APIHost can all be overridden on a per-Builder or per-Event basis.

Make sure to call Close() to flush buffers.

func Responses

func Responses() chan Response

Responses returns the channel from which the caller can read the responses to sent events.

func SendNow

func SendNow(data interface{}) error

SendNow is a shortcut to create an event, add data, and send the event.

func VerifyWriteKey added in v1.5.0

func VerifyWriteKey(config Config) (string, error)

VerifyWriteKey calls out to the Honeycomb API to validate the write key, so we can exit immediately if desired instead of happily sending events that are all rejected.

Types

type Builder

type Builder struct {
	// WriteKey, if set, overrides whatever is found in Config
	WriteKey string
	// Dataset, if set, overrides whatever is found in Config
	Dataset string
	// SampleRate, if set, overrides whatever is found in Config
	SampleRate uint
	// APIHost, if set, overrides whatever is found in Config
	APIHost string
	// contains filtered or unexported fields
}

Builder is used to create templates for new events, specifying default fields and override settings.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new event builder. The builder inherits any Dynamic or Static Fields present in the global scope.

func (*Builder) Add

func (f *Builder) Add(data interface{}) error

Add adds a complex data type to the event or builder on which it's called. For structs, it adds each exported field. For maps, it adds each key/value. Add will error on all other types.

func (*Builder) AddDynamicField

func (b *Builder) AddDynamicField(name string, fn func() interface{}) error

AddDynamicField adds a dynamic field to the builder. Any events created from this builder will get this metric added.

func (*Builder) AddField

func (f *Builder) AddField(key string, val interface{})

AddField adds an individual metric to the event or builder on which it is called. Note that if you add a value that cannot be serialized to JSON (eg a function or channel), the event will fail to send.

func (*Builder) AddFunc

func (f *Builder) AddFunc(fn func() (string, interface{}, error)) error

AddFunc takes a function and runs it repeatedly, adding the return values as fields. The function should return error when it has exhausted its values

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone creates a new builder that inherits all traits of this builder and creates its own scope in which to add additional static and dynamic fields.

func (*Builder) Fields added in v1.4.0

func (f *Builder) Fields() map[string]interface{}

Fields returns a reference to the map of fields that have been added to an event. Caution: it is not safe to manipulate the returned map concurrently with calls to AddField, Add or AddFunc.

func (*Builder) NewEvent

func (b *Builder) NewEvent() *Event

NewEvent creates a new Event prepopulated with fields, dynamic field values, and configuration inherited from the builder.

func (*Builder) SendNow

func (b *Builder) SendNow(data interface{}) error

SendNow is a shortcut to create an event from this builder, add data, and send the event.

type Config

type Config struct {

	// WriteKey is the Honeycomb authentication token. If it is specified during
	// libhoney initialization, it will be used as the default write key for all
	// events. If absent, write key must be explicitly set on a builder or
	// event. Find your team write key at https://ui.honeycomb.io/account
	WriteKey string

	// Dataset is the name of the Honeycomb dataset to which to send these events.
	// If it is specified during libhoney initialization, it will be used as the
	// default dataset for all events. If absent, dataset must be explicitly set
	// on a builder or event.
	Dataset string

	// SampleRate is the rate at which to sample this event. Default is 1,
	// meaning no sampling. If you want to send one event out of every 250 times
	// Send() is called, you would specify 250 here.
	SampleRate uint

	// APIHost is the hostname for the Honeycomb API server to which to send this
	// event. default: https://api.honeycomb.io/
	APIHost string

	// BlockOnSend determines if libhoney should block or drop packets that exceed
	// the size of the send channel (set by PendingWorkCapacity). Defaults to
	// False - events overflowing the send channel will be dropped.
	BlockOnSend bool

	// BlockOnResponse determines if libhoney should block trying to hand
	// responses back to the caller. If this is true and there is nothing reading
	// from the Responses channel, it will fill up and prevent events from being
	// sent to Honeycomb. Defaults to False - if you don't read from the Responses
	// channel it will be ok.
	BlockOnResponse bool

	// Output allows you to override what happens to events after you call
	// Send() on them. By default, events are asynchronously sent to the
	// Honeycomb API. You can use the MockOutput included in this package in
	// unit tests, or use the WriterOutput to write events to STDOUT or to a
	// file when developing locally.
	Output Output

	// Configuration for the underlying sender. It is safe (and recommended) to
	// leave these values at their defaults. You cannot change these values
	// after calling Init()
	MaxBatchSize         uint          // how many events to collect into a batch before sending. Overrides DefaultMaxBatchSize.
	SendFrequency        time.Duration // how often to send off batches. Overrides DefaultBatchTimeout.
	MaxConcurrentBatches uint          // how many batches can be inflight simultaneously. Overrides DefaultMaxConcurrentBatches.
	PendingWorkCapacity  uint          // how many events to allow to pile up. Overrides DefaultPendingWorkCapacity

	// Transport can be provided to the http.Client attempting to talk to
	// Honeycomb servers. Intended for use in tests in order to assert on
	// expected behavior.
	Transport http.RoundTripper
}

Config specifies settings for initializing the library.

type Event

type Event struct {
	// WriteKey, if set, overrides whatever is found in Config
	WriteKey string
	// Dataset, if set, overrides whatever is found in Config
	Dataset string
	// SampleRate, if set, overrides whatever is found in Config
	SampleRate uint
	// APIHost, if set, overrides whatever is found in Config
	APIHost string
	// Timestamp, if set, specifies the time for this event. If unset, defaults
	// to Now()
	Timestamp time.Time
	// Metadata is a field for you to add in data that will be handed back to you
	// on the Response object read off the Responses channel. It is not sent to
	// Honeycomb with the event.
	Metadata interface{}
	// contains filtered or unexported fields
}

Event is used to hold data that can be sent to Honeycomb. It can also specify overrides of the config settings.

func NewEvent

func NewEvent() *Event

NewEvent creates a new event prepopulated with any Fields present in the global scope.

func (*Event) Add

func (f *Event) Add(data interface{}) error

Add adds a complex data type to the event or builder on which it's called. For structs, it adds each exported field. For maps, it adds each key/value. Add will error on all other types.

func (*Event) AddField

func (f *Event) AddField(key string, val interface{})

AddField adds an individual metric to the event or builder on which it is called. Note that if you add a value that cannot be serialized to JSON (eg a function or channel), the event will fail to send.

func (*Event) AddFunc

func (f *Event) AddFunc(fn func() (string, interface{}, error)) error

AddFunc takes a function and runs it repeatedly, adding the return values as fields. The function should return error when it has exhausted its values

func (*Event) Fields added in v1.4.0

func (f *Event) Fields() map[string]interface{}

Fields returns a reference to the map of fields that have been added to an event. Caution: it is not safe to manipulate the returned map concurrently with calls to AddField, Add or AddFunc.

func (*Event) MarshalJSON

func (e *Event) MarshalJSON() ([]byte, error)

Marshaling an Event for batching up to the Honeycomb servers. Omits fields that aren't specific to this particular event, and allows for behavior like omitempty'ing a zero'ed out time.Time.

func (*Event) Send

func (e *Event) Send() error

Send dispatches the event to be sent to Honeycomb, sampling if necessary.

If you have sampling enabled (i.e. SampleRate >1), Send will only actually transmit data with a probability of 1/SampleRate. No error is returned whether or not traffic is sampled, however, the Response sent down the response channel will indicate the event was sampled in the errors Err field.

Send inherits the values of required fields from Config. If any required fields are specified in neither Config nor the Event, Send will return an error. Required fields are APIHost, WriteKey, and Dataset. Values specified in an Event override Config.

func (*Event) SendPresampled

func (e *Event) SendPresampled() error

SendPresampled dispatches the event to be sent to Honeycomb.

Sampling is assumed to have already happened. SendPresampled will dispatch every event handed to it, and pass along the sample rate. Use this instead of Send() when the calling function handles the logic around which events to drop when sampling.

SendPresampled inherits the values of required fields from Config. If any required fields are specified in neither Config nor the Event, Send will return an error. Required fields are APIHost, WriteKey, and Dataset. Values specified in an Event override Config.

type MockOutput added in v1.4.0

type MockOutput struct {
	sync.Mutex
	// contains filtered or unexported fields
}

MockOutput implements the Output interface by retaining a slice of added events, for use in unit tests.

func (*MockOutput) Add added in v1.4.0

func (m *MockOutput) Add(ev *Event)

func (*MockOutput) Events added in v1.4.0

func (m *MockOutput) Events() []*Event

func (*MockOutput) Start added in v1.4.0

func (m *MockOutput) Start() error

func (*MockOutput) Stop added in v1.4.0

func (m *MockOutput) Stop() error

type Output added in v1.4.0

type Output interface {
	Add(ev *Event)
	Start() error
	Stop() error
}

Output is responsible for handling events after Send() is called. Implementations of Add() must be safe for concurrent calls.

type Response

type Response struct {

	// Err contains any error returned by the httpClient on sending or an error
	// indicating queue overflow
	Err error

	// StatusCode contains the HTTP Status Code returned by the Honeycomb API
	// server
	StatusCode int

	// Body is the body of the HTTP response from the Honeycomb API server.
	Body []byte

	// Duration is a measurement of how long the HTTP request to send an event
	// took to process. The actual time it takes libhoney to send an event may
	// be longer due to any time the event spends waiting in the queue before
	// being sent.
	Duration time.Duration

	// Metadata is whatever content you put in the Metadata field of the event for
	// which this is the response. It is passed through unmodified.
	Metadata interface{}
}

Response is a record of an event sent. It includes information about sending the event - how long it took, whether it succeeded, and so on. It also has a metadata field that is just a pass through - populate an Event's Metadata field and what you put there will be on the Response that corresponds to that Event. This allows you to track specific events.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(b []byte) error

type WriterOutput added in v1.4.0

type WriterOutput struct {
	W io.Writer

	sync.Mutex
}

WriterOutput implements the Output interface by marshalling events to JSON and writing to STDOUT, or to the writer W if one is specified.

func (*WriterOutput) Add added in v1.4.0

func (w *WriterOutput) Add(ev *Event)

func (*WriterOutput) Start added in v1.4.0

func (w *WriterOutput) Start() error

func (*WriterOutput) Stop added in v1.4.0

func (w *WriterOutput) Stop() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL