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 ¶
- Constants
- Variables
- func Add(data interface{}) error
- func AddDynamicField(name string, fn func() interface{}) error
- func AddField(name string, val interface{})
- func Close()
- func Flush()
- func Init(config Config) error
- func Responses() chan Response
- func SendNow(data interface{}) error
- func VerifyWriteKey(config Config) (team string, err error)
- type Builder
- func (f *Builder) Add(data interface{}) error
- func (b *Builder) AddDynamicField(name string, fn func() interface{}) error
- func (f *Builder) AddField(key string, val interface{})
- func (f *Builder) AddFunc(fn func() (string, interface{}, error)) error
- func (b *Builder) Clone() *Builder
- func (f *Builder) Fields() map[string]interface{}
- func (b *Builder) NewEvent() *Event
- func (b *Builder) SendNow(data interface{}) error
- type Config
- type DefaultLogger
- type DiscardOutput
- type Event
- func (f *Event) Add(data interface{}) error
- func (f *Event) AddField(key string, val interface{})
- func (f *Event) AddFunc(fn func() (string, interface{}, error)) error
- func (f *Event) Fields() map[string]interface{}
- func (e *Event) MarshalJSON() ([]byte, error)
- func (e *Event) Send() error
- func (e *Event) SendPresampled() (err error)
- type Logger
- type MockOutput
- type Output
- type Response
- type WriterOutput
Examples ¶
Constants ¶
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 ¶
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 ¶
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 Flush ¶ added in v1.7.0
func Flush()
Flush closes and reopens the Output interface, ensuring events are sent without waiting on the batch to be sent asyncronously. Generally, it is more efficient to rely on asyncronous batches than to call Flush, but certain scenarios may require Flush if asynchronous sends are not guaranteed to run (i.e. running in AWS Lambda) Flush is not thread safe - use it only when you are sure that no other parts of your program are calling Send
func Init ¶
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 deprecated and may be removed in a future major release. Contrary to its name, SendNow does not block and send data immediately, but only enqueues to be sent asynchronously. It is equivalent to:
ev := libhoney.NewEvent() ev.Add(data) ev.Send()
func VerifyWriteKey ¶ added in v1.5.0
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 ¶
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 ¶
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 ¶
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 ¶
NewEvent creates a new Event prepopulated with fields, dynamic field values, and configuration inherited from the builder.
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 // Logger defaults to nil and the SDK is silent. If you supply a logger here // (or set it to &DefaultLogger{}), some debugging output will be emitted. // Intended for human consumption during development to understand what the // SDK is doing and diagnose trouble emitting events. Logger Logger }
Config specifies settings for initializing the library.
type DefaultLogger ¶ added in v1.8.0
type DefaultLogger struct{}
DefaultLogger implements Logger and prints messages to stdout prepended by a timestamp (RFC3339 formatted)
func (*DefaultLogger) Printf ¶ added in v1.8.0
func (d *DefaultLogger) Printf(msg string, args ...interface{})
Printf prints the message to stdout.
type DiscardOutput ¶ added in v1.7.0
type DiscardOutput struct {
*WriterOutput
}
DiscardOutput implements the Output interface and drops all events.
func (*DiscardOutput) Add ¶ added in v1.7.0
func (d *DiscardOutput) Add(ev *Event)
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 ¶
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 ¶
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 ¶
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 ¶
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 Logger ¶ added in v1.8.0
type Logger interface { // Printf accepts the same msg, args style as fmt.Printf(). Printf(msg string, args ...interface{}) }
Logger is used to log extra info within the SDK detailing what's happening. You can set a logger during initialization. If you leave it unititialized, no logging will happen. If you set it to the DefaultLogger, you'll get timestamped lines sent to STDOUT. Pass in your own implementation of the interface to send it in to your own logger. An instance of the go package log.Logger satisfies this interface.
type MockOutput ¶ added in v1.4.0
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
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 ¶
type WriterOutput ¶ added in v1.4.0
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