trace

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2022 License: BSD-3-Clause Imports: 18 Imported by: 2

Documentation

Overview

Package trace provides distributed tracing.

Initialization

In the config variable, add the "Config" struct:

var config struct {
	Trace trace.Config
}

The "Config" has the following values:

type Config struct {
	Exporter          string  `default:""` // empty string or "stackdriver"
	ProbabilitySample float64 `default:"0"` // [0, 1]
	Stackdriver       struct {
		ProjectID string
	}
}

Initialize your config using the "app.SetupConfig"

app.SetupConfig(&config)

Now, initialize your trace exporter using "trace.SetupTrace":

trace.SetupTrace(config.Trace)

Service

It will be used the following service as example:

type Service interface {
	Do(context.Context, Request) (Response, error)
}

type Request struct {
	// (...)
	trace.Trace
}

type Response struct {
	// (...)
	trace.Trace
}

And will be used the following job as example of job/event:

type Job interface {
	//(...)
	trace.Trace
}

HTTP Layer

Retrieve the Trace from the HTTP request and pass it along:

func decodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var req Request

	// (...)
	req.Trace = trace.GetTraceFromHTTRequest(r)

	return req, nil
}

func MakeEndpoint(s Service) endpoint.Endpoint {
	return func(ctx context.Context, r interface{}) (interface{}, error) {
		req := r.(Request)

		ctx = trace.WithTraceAndLabels(ctx, req.Trace, getLabelsFromRequest(req))

		response, err := s.Do(ctx, req)

		return response, err
	}
}

func getLabelsFromRequest(req Request) map[string]string{
	//(...)
}

Encode the trace in the HTTP respose:

func EncodeResponse(ctx context.Context, w http.ResponseWriter, r interface{}) error {
	response := r.(Response)
	trace.SetInHTTPResponse(response.Trace, w)
	// (...)
}

Using spans

Inside a service function:

func (s service) Do(ctx ontext.Context, req Request) (response Response, err error) {

	// When receive the trace through a job/event
	ctx = trace.WithTrace(ctx, job.Trace)

	// When is the first span in service
	span := trace.StartSpanWithParent(ctx)
	defer span.End(err)

	// When is not the first span in service
	span := trace.StartSpan(ctx)
	defer span.End(err)

	// Make a POST in another service
	var req *http.Request
	prepareRequest(req)
	trace.SetInHTTPRequest(ctx, req)

	// Create a job/event to send to a queue
	// or
	// Create the Service Response
	response.Trace = trace.GetFromContext(ctx)
	newJob.Trace = trace.GetFromContext(ctx)
}

func prepareRequest(req *http.Request) {
	//(...)
}

Logging

Use the function "GetIDFromContext" to log the Trace ID:

func (l *logging) Do(ctx ontext.Context, req Request) (response Response, err error) {
	logger := log.Logger.With().
		EmbedObject(trace.GetIDFromContext(ctx)).
		Logger()
	// (...)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IDIsEmpty

func IDIsEmpty(id ID) bool

IDIsEmpty returns true if the @id is nil, empty or composed solely by zeroes.

func SetInHTTPRequest

func SetInHTTPRequest(ctx context.Context, request *http.Request)

SetInHTTPRequest sets the header of @request using the trace in the @ctx. If @trace is empty or @request is nil, nothing will happen

func SetInHTTPResponse

func SetInHTTPResponse(trace Trace, response http.ResponseWriter)

SetInHTTPResponse sets the header of @response using @trace. If @trace is empty or @response is nil, nothing will happen

func SetTraceInHTTPRequest deprecated

func SetTraceInHTTPRequest(ctx context.Context, request *http.Request)

SetTraceInHTTPRequest sets the header of @request using the trace in the @ctx. If @trace is empty or @request is nil, nothing will happen

Deprecated: use SetInHTTPRequest instead

func SetTraceInHTTPResponse deprecated

func SetTraceInHTTPResponse(trace Trace, response http.ResponseWriter)

SetTraceInHTTPResponse sets the header of @response using @trace. If @trace is empty or @response is nil, nothing will happen

Deprecated: use SetInHTTPResponse instead

func SetupTrace

func SetupTrace(c Config)

SetupTrace configure a trace exporter, defined in @c

func WithLabels

func WithLabels(parent context.Context, labels map[string]string) context.Context

WithLabels returns the @parent context with the labels @labels If there are already labels in the context, the new labels will be merged into the existing one. If a label with the same key already exists, it will be overwritten

func WithNewTrace

func WithNewTrace(ctx context.Context) context.Context

WithNewTrace returns the same as WithTrace, but instead of receiving a trace, it creates a new one.

func WithTrace

func WithTrace(ctx context.Context, trace Trace) context.Context

WithTrace if there is no trace in the context, returns the @ctx with the @trace else returns the @ctx unchanged

func WithTraceAndLabels

func WithTraceAndLabels(parent context.Context, trace Trace, labels map[string]string) context.Context

WithTraceAndLabels returns the @parent context with the Trace @trace and the labels @labels

func WithTraceID deprecated

func WithTraceID(parent context.Context, traceID ID) context.Context

WithTraceID instantiates a new child context from @parent with the given @traceID value set

Deprecated: Should use WithTrace instead

Types

type Config

type Config struct {
	Exporter          string  `default:""`
	ProbabilitySample float64 `default:"0"`
	Stackdriver       struct {
		ProjectID string
	}
}

Config represents the informations that must be set to configure the trace

type Generator

type Generator interface {
	NewTraceID() ID
}

Generator is a interface to generate trace ids

type ID

type ID [16]byte

ID is an unique identifier (trace id) that can be use to identify one or more requests between distinct systems. It is a random-generated 16 bytes word, encoded as hexadecimal characters when in string format.

func EnsureIDNotEmpty

func EnsureIDNotEmpty(id ID) ID

EnsureIDNotEmpty checks if the ID is not empty and return it, else it returns NewID(). The empty check follows the same rules as the IDIsEmpty function.

func GetIDFromContext

func GetIDFromContext(ctx context.Context) ID

GetIDFromContext returns the Trace ID in the context. Will return a empty ID if a Trace is not set in context

func GetTraceIDFromContext deprecated

func GetTraceIDFromContext(ctx context.Context) ID

GetTraceIDFromContext returns the trace ID set in the context, if any, or an empty trace id if none is set

Deprecated: Should use GetFromContext instead

func GetTraceIDFromHTTPRequest deprecated

func GetTraceIDFromHTTPRequest(r *http.Request) ID

GetTraceIDFromHTTPRequest attempts to return a trace ID read from the @r http request by obtaining the value in the `X-TRACEID` http header field.

Deprecated: should use GetFromHTTRequest instead

func NewID

func NewID() ID

NewID generates a new random trace id

func NewTraceID deprecated

func NewTraceID() ID

NewTraceID generates a new random trace id

Deprecated: use NewID instead

func Parse

func Parse(input string) ID

Parse returns an ID instance from a serialized traceID

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON converts ID to a 32 hexadecimal characters string.

func (ID) MarshalZerologObject

func (id ID) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject implements the zerolog marshaler so it can be logged using: log.With().EmbededObject(id).Msg("Some message")

func (ID) String

func (id ID) String() string

String will return the ID as 32 hexadecimal characters string

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(b []byte) error

UnmarshalJSON parses an ID from a json. The ID is expected to a 32 hexadecimal characters string. This operation is case-insensitive.

type Span

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

Span represents a span of a trace

func StartSpan

func StartSpan(ctx context.Context, spanNameArgs ...string) (newCtx context.Context, s Span)

StartSpan starts a span from @ctx and return it with a new context. The span returned has some labels defined in method setSpanLabels

func StartSpanWithParent

func StartSpanWithParent(ctx context.Context, spanNameArgs ...string) (newCtx context.Context, s Span)

StartSpanWithParent returns a context and a span with the name @spanNameArgs. If exists a Trace in @ctx, the method will return a span with it as parent. Otherwise, the method will create a new span and return it

func (*Span) End

func (s *Span) End(err error)

End ends the span and sets a label for @err, if exists

type Trace

type Trace struct {
	// ID represents the Trace ID used in logging and
	// trace views. It will be used as the main span in
	ID ID

	// ProbabilitySample represents if the span will be
	// sampled or not. The two possibles values are 0 and 1
	ProbabilitySample *float64
}

Trace represents the informations that should be passed through systems

func GetFromContext

func GetFromContext(ctx context.Context) Trace

GetFromContext returns the Trace saved in @ctx

func GetFromHTTPRequest

func GetFromHTTPRequest(r *http.Request) Trace

GetFromHTTPRequest returns a Trace using the trace ID and the probability sample get from the header of @r

func GetFromHTTPResponse

func GetFromHTTPResponse(r *http.Response) Trace

GetFromHTTPResponse returns a Trace using the trace ID and the probability sample get from the header of @r

func GetTraceFromContext deprecated

func GetTraceFromContext(ctx context.Context) Trace

GetTraceFromContext returns the Trace saved in @ctx

Deprecated: use GetFromContext instead

func GetTraceFromHTTPRequest deprecated

func GetTraceFromHTTPRequest(r *http.Request) Trace

GetTraceFromHTTPRequest returns a Trace using the trace ID and the probability sample get from the header of @r

Deprecated: use GetFromHTTPRequest

func GetTraceFromHTTPResponse deprecated

func GetTraceFromHTTPResponse(r *http.Response) Trace

GetTraceFromHTTPResponse returns a Trace using the trace ID and the probability sample get from the header of @r

Deprecated: use GetFromHTTPResponse instead

func (Trace) MarshalZerologObject

func (t Trace) MarshalZerologObject(e *zerolog.Event)

MarshalZerologObject implements the zerolog marshaler so it can be logged using: log.With().EmbededObject(t).Msg("Some message")

Jump to

Keyboard shortcuts

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