libhoney

package module
v1.23.1 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2024 License: Apache-2.0 Imports: 19 Imported by: 189

README

libhoney

OSS Lifecycle CircleCI

Go library for sending events to Honeycomb, a service for debugging your software in production.

For tracing support and automatic instrumentation of Gorilla, httprouter, sqlx, and other common libraries, check out our Beeline for Go.

Dependencies

Golang 1.19+

Contributions

See DEVELOPMENT.md

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 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 GetTeamAndEnvironment added in v1.16.0

func GetTeamAndEnvironment(config Config) (team string, environment string, err error)

GetTeamAndEnvironment calls out to the Honeycomb API to validate the API key and retrieve the associated team and environment names.

func Init

func Init(conf 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 IsClassicKey added in v1.22.0

func IsClassicKey(key string) bool

func Responses deprecated

func Responses() chan Response

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

Deprecated: Responses is deprecated; please use TxResponses instead.

func SendNow deprecated

func SendNow(data interface{}) error

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()

Deprecated: SendNow is deprecated and may be removed in a future major release.

func TxResponses added in v1.9.0

func TxResponses() chan transmission.Response

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

func VerifyAPIKey added in v1.9.0

func VerifyAPIKey(config Config) (team string, err error)

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

func VerifyWriteKey deprecated added in v1.5.0

func VerifyWriteKey(config Config) (team string, err error)

VerifyWriteKey is the deprecated call to validate a Honeycomb API key.

Deprecated: Please use VerifyAPIKey instead.

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) NewEventSized added in v1.20.0

func (b *Builder) NewEventSized(size int) *Event

NewEventSized() can be used instead of NewEvent() where the number of additional event fields is known and performance is a concern This will preallocate the internal field map based on the size and avoid unnecessary copying and reallocation of the map

func (*Builder) SendNow deprecated

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

Contrary to its name, SendNow does not block and send data immediately, but only enqueues to be sent asynchronously. It is equivalent to:

ev := builder.NewEvent()
ev.Add(data)
ev.Send()

Deprecated: SendNow is deprecated and may be removed in a future major release.

func (*Builder) String added in v1.15.0

func (f *Builder) String() string

returns a human friendly string representation of the fieldHolder

type Client added in v1.9.0

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

Client represents an object that can create new builders and events and send them somewhere. It maintains its own sending queue for events, distinct from both the package-level libhoney queue and any other client. Clients should be created with NewClient(config). A manually created Client{} will function as a nil output and drop everything handed to it (so can be safely used in dev and tests). For more complete testing you can create a Client with a MockOutput transmission then inspect the events it would have sent.

func NewClient added in v1.9.0

func NewClient(conf ClientConfig) (*Client, error)

NewClient creates a Client with defaults correctly set

func (*Client) Add added in v1.9.0

func (c *Client) Add(data interface{}) error

Add adds its data to the Client's 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 (*Client) AddDynamicField added in v1.9.0

func (c *Client) 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.

func (*Client) AddField added in v1.9.0

func (c *Client) AddField(name string, val interface{})

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

func (*Client) Close added in v1.9.0

func (c *Client) Close()

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

func (*Client) Flush added in v1.9.0

func (c *Client) 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)

func (*Client) NewBuilder added in v1.9.0

func (c *Client) NewBuilder() *Builder

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

func (*Client) NewEvent added in v1.9.0

func (c *Client) NewEvent() *Event

NewEvent creates a new event prepopulated with any Fields present in the Client's scope.

func (*Client) TxResponses added in v1.9.0

func (c *Client) TxResponses() chan transmission.Response

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

type ClientConfig added in v1.9.0

type ClientConfig struct {
	// APIKey is the Honeycomb authentication token. If it is specified during
	// libhoney initialization, it will be used as the default API key for all
	// events. If absent, API key must be explicitly set on a builder or
	// event. Find your team's API keys at https://ui.honeycomb.io/account
	APIKey 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

	// Transmission 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 transmission.WriterSender to write events to
	// STDOUT or to a file when developing locally.
	Transmission transmission.Sender

	// 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
}

ClientConfig is a subset of the global libhoney config that focuses on the configuration of the client itself. The other config options are specific to a given transmission Sender and should be specified there if the defaults need to be overridden.

type Config

type Config struct {

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

	// WriteKey is the deprecated name for the Honeycomb authentication token.
	//
	// Deprecated: Use APIKey instead. If both are set, APIKey takes precedence.
	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 is the deprecated method of manipulating how libhoney sends
	// events.
	//
	// Deprecated: Please use Transmission instead.
	Output Output

	// Transmission 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 transmission.WriterSender to write events to
	// STDOUT or to a file when developing locally.
	Transmission transmission.Sender

	// 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

	// Deprecated: Transport is deprecated and should not be used. To set the HTTP Transport
	// set the Transport elements on the Transmission Sender instead.
	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.

func (*Config) IsClassic added in v1.21.0

func (c *Config) IsClassic() bool

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 deprecated added in v1.7.0

type DiscardOutput struct {
	WriterOutput
}

DiscardWriter implements the Output interface and drops all events.

Deprecated: Please use the transmission.DiscardSender directly instead. It is provided here for backwards compatibility and will be removed eventually.

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 (e *Event) Add(data interface{}) error

Add adds a complex data type to the event 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.

Adds to an event that happen after it has been sent will return without having any effect.

func (*Event) AddField

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

AddField adds an individual metric to the event 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.

Adds to an event that happen after it has been sent will return without having any effect.

func (*Event) AddFunc

func (e *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

Adds to an event that happen after it has been sent will return without having any effect.

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) 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.

Once you Send an event, any addition calls to add data to that event will return without doing anything. Once the event is sent, it becomes immutable.

func (*Event) SendPresampled

func (e *Event) SendPresampled() (err 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.

Once you Send an event, any addition calls to add data to that event will return without doing anything. Once the event is sent, it becomes immutable.

func (*Event) String added in v1.15.0

func (e *Event) String() string

returns a human friendly string representation of the event

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 deprecated added in v1.4.0

type MockOutput struct {
	transmission.MockSender
}

MockOutput implements the Output interface and passes it along to the transmission.MockSender.

Deprecated: Please use the transmission.MockSender directly instead. It is provided here for backwards compatibility and will be removed eventually.

func (*MockOutput) Add added in v1.4.0

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

func (*MockOutput) Events added in v1.4.0

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

type Output deprecated added in v1.4.0

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

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

Deprecated: Output is deprecated; use Transmission instead.

type Response deprecated

type Response struct {
	transmission.Response
}

Deprecated: Response is deprecated; please use transmission.Response instead.

type WriterOutput deprecated added in v1.4.0

type WriterOutput struct {
	transmission.WriterSender
}

WriterOutput implements the Output interface and passes it along to the transmission.WriterSender.

Deprecated: Please use the transmission.WriterSender directly instead. It is provided here for backwards compatibility and will be removed eventually.

func (*WriterOutput) Add added in v1.4.0

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

Directories

Path Synopsis
examples
webapp Module

Jump to

Keyboard shortcuts

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