libtrace

package module
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2023 License: Apache-2.0 Imports: 15 Imported by: 3

Documentation

Overview

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

Summary

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

See https://opsramp.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 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

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 TxResponses deprecated

func TxResponses() chan transmission.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 Responses() chan Response {
	oneResp.Do(func() {
		if transitionResponses == nil {
			txResponses := dc.TxResponses()
			transitionResponses = make(chan Response, cap(txResponses))
			go func() {
				for txResp := range txResponses {
					resp := Response{}
					resp.Response = txResp
					transitionResponses <- resp
				}
				close(transitionResponses)
			}()
		}
	})
	return transitionResponses
}

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

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

func (b *Builder) NewEvent() *Event

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

type Client

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

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

NewClient creates a Client with defaults correctly set

func (*Client) AddField

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

func (c *Client) Close()

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

func (*Client) Flush

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

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

func (c *Client) NewEvent() *Event

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

func (*Client) TxResponses

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

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

type ClientConfig

type ClientConfig struct {

	// Dataset is the name of the opsramp 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 Opsramp API server to which to send this
	// event. default: https://api.opsramp.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
	// Opsramp 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 {

	// Dataset is the name of the Opsramp 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 Opsramp API server to which to send this
	// event. default: https://api.Opsramp.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 Opsramp. 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
	// Opsramp 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.

type DefaultLogger

type DefaultLogger struct{}

DefaultLogger implements Logger and prints messages to stdout prepended by a timestamp (RFC3339 formatted)

func (*DefaultLogger) Printf

func (d *DefaultLogger) Printf(msg string, args ...interface{})

Printf prints the message to stdout.

type DiscardOutput deprecated

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

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
	// Opsramp with the event.
	Metadata interface{}

	APIToken    string
	APITenantId string
	// contains filtered or unexported fields
}

Event is used to hold data that can be sent to Opsramp. 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) 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) SendPresampled

func (e *Event) SendPresampled() (err error)

SendPresampled dispatches the event to be sent to Opsramp.

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.

type Logger

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

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

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

type Output deprecated

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

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

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

Directories

Path Synopsis
proto
proxypb
Package trace_proxy is a reverse proxy.
Package trace_proxy is a reverse proxy.

Jump to

Keyboard shortcuts

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