instrumentation

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: May 3, 2023 License: MIT Imports: 12 Imported by: 1

README

Instrumentation Library

This is a simple wrapper for the New Relic API that makes it easier to interact with the New Relic service from your golang code.

Installation

You can install the New Relic wrapper using go get:

go get -u github.com/SimifiniiCTO/simfiny-core-lib/instrumentation

Usage

You need to to import the library

import github.com/SimifiniiCTO/simfiny-core-lib/instrumentation

Then initialize the Instrumentation Client with the following configuration

    opts := []instrumentation.Option{
        instrumentation.WithServiceName("test-service"),
        instrumentation.WithServiceVersion("v1.0.0"),
        instrumentation.WithServiceEnvironment("prod"),
        instrumentation.WithEnabled(true), // enables instrumentation
        instrumentation.WithNewrelicKey("newrelic-license-key"),
        instrumentation.WithLogger(zap.L()),
    }
    client, err := instrumentation.New(opts...)
    if err != nil {
        ... 
    }

Now you can user the client object to instrument your applicatuon. for example, to initiate a trace

    ctx := context.Background()
    tx := client.StartTransaction("test-transaction") // starts a new transaction
    span := client.NewChildSpan("test-span", tx)
    defer span.End()

Development

If you want to contribute to this project, you can clone the repository and install the development dependencies:

git clone github.com/SimifiniiCTO/simfiny-core-lib/instrumentation
cd simfiny-core-lib/instrumentation
go mod tidy

Please see the contributing guide for more information on how to contribute.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package instrumentation provides global access to instrumentation operations exposed by the core library The provided API is used to instrument any piece of code

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidServiceName error = fmt.Errorf("invalid input argument, service name cannot be nil")
)

Functions

func InterceptorLogger

func InterceptorLogger(l *zap.Logger) logging.Logger

`InterceptorLogger` is a function that returns a `logging.Logger` which is used as an interceptor for gRPC requests. The function takes a `zap.Logger` as input and returns a `logging.LoggerFunc`. The returned `logging.LoggerFunc` takes in a context, logging level, message, and fields as input and logs the message and fields using the `zap.Logger` with the appropriate logging level. It also adds a caller skip to the `zap.Logger` to skip the logging function call in the stack trace.

Types

type Client

type Client struct {
	// The name of the service
	ServiceName string `json:"service_name"`
	// The version of the service
	ServiceVersion string `json:"service_version"`
	// The environment of the service
	ServiceEnvironment string `json:"service_environment"`
	// wether telemetry is enabled
	Enabled bool `json:"metrics_enabled"`
	// wether metrics are enabled
	EnableMetrics bool `json:"enable_metrics"`
	// wether tracing is enabled
	EnableTracing bool `json:"enable_tracing"`
	// wether events are enabled
	EnableEvents bool `json:"enable_events"`

	// `NewrelicKey` is a field in the `Client` struct that holds the New Relic license key. The
	// `json:"newrelic_key"` tag is used to specify the name of the field when it is serialized to JSON.
	NewrelicKey string `json:"newrelic_key"`
	// `Logger      *zap.Logger `json:"-"` is a field in the `Client` struct that holds a pointer
	// to a `zap.Logger` object. The `json:"-"` tag is used to indicate that this field should not be
	// included when the struct is serialized to JSON. This field is used for logging purposes and allows
	// the `Client` object to log messages using the `zap` logging library.
	Logger *zap.Logger `json:"-"`
	// contains filtered or unexported fields
}

The `Client` type is a struct that holds information about a service, including its name, version, environment, telemetry settings, New Relic license key, and a logger object. @property {string} ServiceName - The name of the service that this client is associated with. @property {string} ServiceVersion - The version of the service. @property {string} ServiceEnvironment - The environment of the service, such as "production", "staging", or "development". @property {bool} Enabled - a boolean value indicating whether telemetry/metrics are enabled for the service. @property client - The `client` property is a pointer to a `newrelic.Application` object, which is used to interact with the New Relic API and send telemetry data. @property {string} NewrelicKey - `NewrelicKey` is a field in the `Client` struct that holds the New Relic license key. This key is used to authenticate and connect to the New Relic service for monitoring and reporting purposes. @property Logger - A pointer to a `zap.Logger` object, which is used for logging purposes and allows the `Client` object to log messages using the `zap` logging library. The `json:"-"` tag is used to indicate that this field should not be included when the struct is serialized to JSON.

func New

func New(opts ...Option) (*Client, error)

NewServiceTelemetry creates a new Client

func (*Client) GetServiceEnvironment

func (s *Client) GetServiceEnvironment() string

GetServiceEnvironment implements IServiceTelemetry

func (*Client) GetServiceName

func (s *Client) GetServiceName() string

GetServiceName implements IServiceTelemetry

func (*Client) GetServiceVersion

func (s *Client) GetServiceVersion() string

GetServiceVersion implements IServiceTelemetry

func (*Client) GetStreamClientInterceptors

func (s *Client) GetStreamClientInterceptors() []grpc.StreamClientInterceptor

GetStreamClientInterceptors implements IServiceTelemetry

func (*Client) GetStreamServerInterceptors

func (s *Client) GetStreamServerInterceptors() []grpc.StreamServerInterceptor

GetStreamServerInterceptors implements IServiceTelemetry

func (*Client) GetTraceFromContext

func (s *Client) GetTraceFromContext(ctx context.Context) *newrelic.Transaction

GetTraceFromContext implements IServiceTelemetry

func (*Client) GetTraceFromRequest

func (s *Client) GetTraceFromRequest(r *http.Request) *newrelic.Transaction

GetTraceFromRequest implements IServiceTelemetry

func (*Client) GetTracingEnabled

func (s *Client) GetTracingEnabled() bool

GetTracingEnabled implements IServiceTelemetry

func (*Client) GetUnaryClientInterceptors

func (s *Client) GetUnaryClientInterceptors() []grpc.UnaryClientInterceptor

GetUnaryClientInterceptors implements IServiceTelemetry

func (*Client) GetUnaryServerInterceptors

func (s *Client) GetUnaryServerInterceptors() []grpc.UnaryServerInterceptor

GetUnaryServerInterceptors implements IServiceTelemetry

func (*Client) IsEnabled

func (s *Client) IsEnabled() bool

Enabled implements IServiceTelemetry

func (*Client) NewChildSpan

func (s *Client) NewChildSpan(name string, parent newrelic.Transaction) *newrelic.Segment

NewChildSpan implements IServiceTelemetry

func (*Client) NewMuxRouter

func (s *Client) NewMuxRouter() *mux.Router

NewMuxRouter returns a new mux router

func (*Client) NewRoundtripper

func (s *Client) NewRoundtripper(txn *newrelic.Transaction) *http.RoundTripper

NewRoundTripper allows you to instrument external calls without calling StartExternalSegment by modifying the http.Client's Transport field. If the Transaction parameter is nil, the RoundTripper returned will look for a Transaction in the request's context (using FromContext). This is recommended because it allows you to reuse the same client for multiple transactions.

func (*Client) StartDatastoreSegment

func (s *Client) StartDatastoreSegment(txn *newrelic.Transaction, operation string) *newrelic.DatastoreSegment

StartDatastoreSegment starts a datastore segment

func (*Client) StartExternalSegment

func (s *Client) StartExternalSegment(txn *newrelic.Transaction, req *http.Request) *newrelic.ExternalSegment

StartExternalSegment starts an external segment

func (*Client) StartMessageQueueSegment

func (s *Client) StartMessageQueueSegment(txn *newrelic.Transaction, queueName string) *newrelic.MessageProducerSegment

StartMessageQueueSegment starts a message queue segment

func (*Client) StartNosqlDatastoreSegment

func (s *Client) StartNosqlDatastoreSegment(txn *newrelic.Transaction, operation, collectionName string) *newrelic.DatastoreSegment

StartDatastoreSegment starts a datastore segment

func (*Client) StartRedisDatastoreSegment

func (s *Client) StartRedisDatastoreSegment(txn *newrelic.Transaction, operation string) *newrelic.DatastoreSegment

StartRedisDatastoreSegment starts a redis datastore segment

func (*Client) StartSegment

func (s *Client) StartSegment(txn *newrelic.Transaction, name string) *newrelic.Segment

StartSegment implements IServiceTelemetry

func (*Client) StartTransaction

func (s *Client) StartTransaction(name string) *newrelic.Transaction

StartTransaction implements IServiceTelemetry

func (*Client) Validate

func (t *Client) Validate() error

func (*Client) WithContext

func (s *Client) WithContext(ctx context.Context, trace newrelic.Transaction) context.Context

WithContext implements IServiceTelemetry

func (*Client) WithRequest

func (s *Client) WithRequest(r *http.Request, trace newrelic.Transaction) *http.Request

WithRequest implements IServiceTelemetry

type Counter

type Counter struct {
	Metric
}

Counter a metric type that only linearly increases

type Gauge

type Gauge struct {
	Metric
}

Gauge a metric type that can increase and decrease

type IServiceTelemetry

type IServiceTelemetry interface {
	GetServiceName() string
	GetServiceVersion() string
	GetServiceEnvironment() string
	IsEnabled() bool
	GetTraceFromContext(ctx context.Context) *newrelic.Transaction
	GetTraceFromRequest(r *http.Request) *newrelic.Transaction
	WithContext(ctx context.Context, trace newrelic.Transaction) context.Context
	WithRequest(r *http.Request, trace newrelic.Transaction) *http.Request
	StartTransaction(name string) *newrelic.Transaction
	NewChildSpan(name string, parent newrelic.Transaction) *newrelic.Segment
	StartExternalSegment(txn *newrelic.Transaction, req *http.Request) *newrelic.ExternalSegment
	StartDatastoreSegment(txn *newrelic.Transaction, operation string) *newrelic.DatastoreSegment
	StartMessageQueueSegment(txn *newrelic.Transaction, queueName string) *newrelic.MessageProducerSegment
	StartSegment(txn *newrelic.Transaction, name string) *newrelic.Segment
	NewRoundtripper(txn *newrelic.Transaction) *http.RoundTripper
	StartNosqlDatastoreSegment(txn *newrelic.Transaction, operation, collectionName string) *newrelic.DatastoreSegment
	GetUnaryServerInterceptors() []grpc.UnaryServerInterceptor
	GetStreamServerInterceptors() []grpc.StreamServerInterceptor
	GetUnaryClientInterceptors() []grpc.UnaryClientInterceptor
	GetStreamClientInterceptors() []grpc.StreamClientInterceptor
	NewMuxRouter() *mux.Router
}

The IServiceTelemetry interface defines methods for collecting telemetry data for a service, including tracing, segments, and roundtrippers. @property {string} GetServiceName - Returns the name of the service that is being monitored for telemetry data. @property {string} GetServiceVersion - This method returns the version of the service being monitored by the telemetry service. @property {string} GetServiceEnvironment - This method returns the environment in which the service is running, such as "production", "staging", or "development". @property {bool} IsEnabled - A boolean property that indicates whether the telemetry service is enabled or not. @property GetTraceFromContext - This method retrieves a newrelic.Transaction object from a given context.Context object, which can be used to trace a transaction across multiple services or components. @property GetTraceFromRequest - This method retrieves a newrelic.Transaction object from an HTTP request. This object can be used to instrument and trace the performance of the request and any subsequent operations. @property WithContext - A method that takes a context.Context and a newrelic.Transaction as input parameters and returns a new context.Context with the newrelic.Transaction added to it. This is useful for propagating the transaction across different function calls within the same request. @property WithRequest - WithRequest is a method that takes an HTTP request and a newrelic.Transaction object and returns a new HTTP request with the transaction information added to its context. This is useful for propagating tracing information across service boundaries. @property StartTransaction - StartTransaction is a method that starts a new transaction with the given name and returns a pointer to the newrelic.Transaction object. This method is used to instrument a new transaction in the code. @property NewChildSpan - Creates a new child span within a given transaction. This can be used to track a specific operation or function within a larger transaction. The parent parameter specifies the transaction to which the child span belongs. @property StartExternalSegment - StartExternalSegment is a method that starts a new external segment in a New Relic transaction. It takes in the transaction object and the HTTP request object as parameters and returns a newrelic.ExternalSegment object. This method is used to track external calls made by the service, such as API calls @property StartDatastoreSegment - StartDatastoreSegment is a method that starts a new segment for a datastore operation within a transaction. It takes in the transaction object and the name of the operation being performed as parameters and returns a newrelic.DatastoreSegment object. This segment can be used to record metrics and trace the performance of @property StartMessageQueueSegment - StartMessageQueueSegment is a method that starts a new segment for a message queue operation within a New Relic transaction. It takes in the transaction object and the name of the message queue as parameters and returns a newrelic.MessageProducerSegment object. This segment can be used to record metrics and trace @property StartSegment - StartSegment is a method that starts a new custom segment within a transaction. It takes in the transaction object and a name for the segment as parameters and returns a newrelic.Segment object. This method can be used to track specific parts of a transaction that may not be automatically instrumented by New @property NewRoundtripper - NewRoundtripper is a method that returns an http.RoundTripper that instruments outgoing HTTP requests with New Relic tracing. This allows for tracing of external service calls made by the service. The returned RoundTripper should be used in place of the default RoundTripper in the http.Client used to @property StartNosqlDatastoreSegment - This method starts a new segment for a NoSQL datastore operation in a transaction. It takes in the transaction object, the operation being performed, and the name of the collection being accessed. It returns a newrelic.DatastoreSegment object that can be used to add additional information and end the segment.

type Metric

type Metric struct {
	MetricName       string
	Name             string
	Help             string
	Subsystem        Subsystem
	Namespace        Namespace
	ServiceName      string
	MetricPartitions map[string]string
}

Metric encompasses the relative metadata associated with a service level metric being emitted

type MetricName

type MetricName struct {
	ServiceName     string
	OperationName   string
	IsDistributedTx bool
	IsDatabaseTx    bool
	IsError         bool
}

type MetricType

type MetricType string
const (
	Count         MetricType = "count"
	ErrorCount    MetricType = "error_count"
	Latency       MetricType = "latency"
	MetricSummary MetricType = "summary"
)
var (
	OperationLatencyMetric MetricType = "service.operation.latency"
	OperationStatusMetric  MetricType = "service.operation.status"
	RpcStatusMetric        MetricType = "service.rpc.status"
)

type Namespace

type Namespace string
const (
	RequestNamespace                   Namespace = "request.namespace"
	DistributedTxNamespace             Namespace = "dtx.namespace"
	DistributedSagaTxNamespace         Namespace = "dtx.saga.namespace"
	DistributedTx2PhaseCommitNamespace Namespace = "dtx.2phase_commit.namespace"
	DistributedTxTccNamespace          Namespace = "dtx.tcc.namespace"
	ServiceNamespace                   Namespace = "service.namespace"
	DatabaseNamespace                  Namespace = "database.namespace"
)

type Option

type Option func(*Client)

Option is a function that configures a Client

func WithEnableEvents

func WithEnableEvents(enableEvents bool) Option

WithEnableEvents configures wether or not events are enabled

func WithEnableMetrics

func WithEnableMetrics(enableMetrics bool) Option

WithEnableMetrics configures wether or not metrics are enabled

func WithEnableTracing

func WithEnableTracing(enableTracing bool) Option

WithEnableTracing configures wether or not tracing is enabled

func WithEnabled

func WithEnabled(enabled bool) Option

WithEnabled configures wether or not instrumentation is enabled

func WithLogger

func WithLogger(logger *zap.Logger) Option

WithLogger configures the logger

func WithNewrelicKey

func WithNewrelicKey(key string) Option

WithNewrelicKey configures the newrelic key

func WithServiceEnvironment

func WithServiceEnvironment(environment string) Option

WithServiceEnvironment configures the service environment

func WithServiceName

func WithServiceName(name string) Option

WithServiceName configures the service name

func WithServiceVersion

func WithServiceVersion(version string) Option

WithServiceVersion configures the service version

type Subsystem

type Subsystem string
const (
	GrpcSubSystem       Subsystem = "grpc.subsystem"
	ThirdPartySubSystem Subsystem = "thirdparty.subsystem"
	ErrorSubSystem      Subsystem = "error.subsystem"
	DbSubSystem         Subsystem = "database.subsystem"
)

type Summary

type Summary struct {
	Metric
}

Summary summarizes numerous facets of a metric

Jump to

Keyboard shortcuts

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