metrics

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2023 License: Apache-2.0 Imports: 15 Imported by: 0

README

krakend-newrelic-v2

Go Reference Go codecov Go Report Card

A NewRelic middleware that uses the NewRelic Go Agent v3

Installation

go get -u github.com/jbactad/krakend-newrelic-v2

Quick Start

To enable NewRelic instrumentation in your krakend api gateway, you need to make sure and call metrics.Register function to initialize the newrelic.Application from your gateway.

There are 3 middlewares where you can enable instrumentation in your krakend api gateway, Handler, Proxy and Backend.

package main

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	metrics "github.com/jbactad/krakend-newrelic-v2"
	"github.com/luraproject/lura/v2/config"
	"github.com/luraproject/lura/v2/logging"
	"github.com/luraproject/lura/v2/proxy"
	router "github.com/luraproject/lura/v2/router/gin"
	serverhttp "github.com/luraproject/lura/v2/transport/http/server"
	server "github.com/luraproject/lura/v2/transport/http/server/plugin"
)

func main() {
	cfg := config.ServiceConfig{}
	logger := logging.NoOp

	// Initializes the metrics collector.
	metrics.Register(context.Background(), cfg.ExtraConfig, logger)

	backendFactory := proxy.HTTPProxyFactory(&http.Client{})

	// Wrap the default BackendFactory with instrumented BackendFactory 
	backendFactory = metrics.BackendFactory("backend", backendFactory)

	pf := proxy.NewDefaultFactory(backendFactory, logger)

	// Wrap the default ProxyFactory with instrumented ProxyFactory
	pf = metrics.ProxyFactory("proxy", pf)

	handlerFactory := router.CustomErrorEndpointHandler(logger, serverhttp.DefaultToHTTPError)

	// Wrap the default HandlerFactory with instrumented HandlerFactory
	handlerFactory = metrics.HandlerFactory(handlerFactory)

	engine := gin.New()

	// setup the krakend router
	routerFactory := router.NewFactory(
		router.Config{
			Engine:         engine,
			ProxyFactory:   pf,
			Logger:         logger,
			RunServer:      router.RunServerFunc(server.New(logger, serverhttp.RunServer)),
			HandlerFactory: handlerFactory,
		},
	)

	// start the engines
	logger.Info("Starting the KrakenD instance")
	routerFactory.NewWithContext(context.Background()).Run(cfg)
}

Then in your gateway's config file make sure to add github_com/jbactad/krakend_newrelic_v2 in the service extra_config section.

{
  "version": 3.0,
  "extra_config": {
    "github_com/jbactad/krakend_newrelic_v2": {
      "rate": 100
    }
  }
}

Configuring

NewRelic related configurations are all read from environment variables. Refer to newrelic go agent package to know more of which NewRelic options can be configure.

From krakend configuration file, these are the following options you can configure.

Name Type Description
rate int The rate the middlewares instrument your application.

Development

Requirements

To start development, make sure you have the following dependencies installed in your development environment.

  • golang >=v1.17
Setup

Run the following to install the necessary tools to run tests.

make setup
Generate mocks for unit tests
make gen
Running unit tests

To run the unit tests, execute the following command.

make test-unit

Documentation

Index

Examples

Constants

View Source
const Namespace = "github_com/jbactad/krakend_newrelic_v2"

Namespace for krakend_newrelic

Variables

This section is empty.

Functions

func BackendFactory

func BackendFactory(segmentName string, next proxy.BackendFactory) proxy.BackendFactory

BackendFactory creates an instrumented backend factory

func HandlerFactory

func HandlerFactory(handlerFactory router.HandlerFactory) router.HandlerFactory

HandlerFactory includes NewRelic transaction specific configuration endpoint naming

func Middleware

func Middleware() gin.HandlerFunc

Middleware adds NewRelic middleware

func NewBackend

func NewBackend(segmentName string, next proxy.Proxy) proxy.Proxy

NewBackend includes NewRelic segmentation

func NewProxyMiddleware

func NewProxyMiddleware(segmentName string) proxy.Middleware

NewProxyMiddleware adds NewRelic segmentation

func ProxyFactory

func ProxyFactory(segmentName string, next proxy.Factory) proxy.FactoryFunc

ProxyFactory creates an instrumented proxy factory

func Register

func Register(
	ctx context.Context,
	cfg config.ExtraConfig,
	logger logging.Logger,
) *newrelic.Application

Register initializes the metrics collector. Returns a newrelic.Application instance.

Example
package main

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	metrics "github.com/jbactad/krakend-newrelic-v2"
	"github.com/luraproject/lura/v2/config"
	"github.com/luraproject/lura/v2/logging"
	"github.com/luraproject/lura/v2/proxy"

	router "github.com/luraproject/lura/v2/router/gin"

	serverhttp "github.com/luraproject/lura/v2/transport/http/server"

	server "github.com/luraproject/lura/v2/transport/http/server/plugin"
)

func main() {
	cfg := config.ServiceConfig{
		ExtraConfig: map[string]interface{}{
			"github_com/jbactad/krakend_newrelic_v2": map[string]interface{}{
				"rate": 100,
			},
		},
	}
	logger := logging.NoOp

	metrics.Register(context.Background(), cfg.ExtraConfig, logger)

	backendFactory := proxy.HTTPProxyFactory(&http.Client{})
	backendFactory = metrics.BackendFactory("backend", backendFactory)

	pf := proxy.NewDefaultFactory(backendFactory, logger)
	pf = metrics.ProxyFactory("proxy", pf)

	handlerFactory := router.CustomErrorEndpointHandler(logger, serverhttp.DefaultToHTTPError)
	handlerFactory = metrics.HandlerFactory(handlerFactory)

	engine := gin.New()

	// setup the krakend router
	routerFactory := router.NewFactory(
		router.Config{
			Engine:         engine,
			ProxyFactory:   pf,
			Logger:         logger,
			RunServer:      router.RunServerFunc(server.New(logger, serverhttp.RunServer)),
			HandlerFactory: handlerFactory,
		},
	)

	// start the engines
	logger.Info("Starting the KrakenD instance")
	routerFactory.NewWithContext(context.Background()).Run(cfg)
}
Output:

Types

type Application

type Application struct {
	TransactionManager TransactionManager
	NRApplication
	Config Config
}

func NewApp

func NewApp(
	cfg config.ExtraConfig,
	nrAppFactory NewRelicAppFactoryFunc,
	manager TransactionManager,
) (*Application, error)

NewApp creates a new Application that wraps the newrelic application

type Config

type Config struct {
	InstrumentationRate int `json:"rate"`
}

Config struct for NewRelic Krakend

func ConfigGetter

func ConfigGetter(cfg config.ExtraConfig) (Config, error)

ConfigGetter gets config for NewRelic

type NRApplication

type NRApplication interface {
	StartTransaction(name string, opts ...newrelic.TraceOption) *newrelic.Transaction
	RecordCustomEvent(eventType string, params map[string]interface{})
	RecordCustomMetric(name string, value float64)
	RecordLog(logEvent newrelic.LogData)
	WaitForConnection(timeout time.Duration) error
	Shutdown(timeout time.Duration)
}

type NewRelicAppFactoryFunc

type NewRelicAppFactoryFunc func() (NRApplication, error)

type StatusCodeSetter

type StatusCodeSetter interface {
	SetStatusCode(code int)
}

type Transaction

type Transaction interface {
	End()
	SetName(name string)
	SetWebRequestHTTP(r *http.Request)
	SetWebRequest(r newrelic.WebRequest)
	SetWebResponse(w http.ResponseWriter) http.ResponseWriter
	StartSegmentNow() newrelic.SegmentStartTime
	StartSegment(name string) *newrelic.Segment
	InsertDistributedTraceHeaders(hdrs http.Header)
	NewGoroutine() *newrelic.Transaction
	GetTraceMetadata() newrelic.TraceMetadata
	GetLinkingMetadata() newrelic.LinkingMetadata
}

type TransactionEndStatusCodeSetter

type TransactionEndStatusCodeSetter interface {
	TransactionEnder
	StatusCodeSetter
}

type TransactionEnder

type TransactionEnder interface {
	End()
}

type TransactionManager

type TransactionManager interface {
	TransactionFromContext(ctx context.Context) Transaction
	StartExternalSegment(txn Transaction, request *http.Request) TransactionEndStatusCodeSetter
}

Jump to

Keyboard shortcuts

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