newrelic

package
v3.14.1 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2021 License: Apache-2.0, Apache-2.0 Imports: 45 Imported by: 0

Documentation

Overview

Package newrelic provides instrumentation for Go applications.

Additional documention available here:

https://github.com/newrelic/go-agent/blob/master/GETTING_STARTED.md

https://github.com/newrelic/go-agent/blob/master/GUIDE.md

Example
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func main() {
	// Create your application using your preferred app name, license key, and
	// any other configuration options.
	app, err := newrelic.NewApplication(
		newrelic.ConfigAppName("Example Application"),
		newrelic.ConfigLicense("__YOUR_NEW_RELIC_LICENSE_KEY__"),
		newrelic.ConfigDebugLogger(os.Stdout),
	)
	if nil != err {
		fmt.Println(err)
		os.Exit(1)
	}

	// Now you can use the Application to collect data!  Create transactions
	// to time inbound requests or background tasks. You can start and stop
	// transactions directly using Application.StartTransaction and
	// Transaction.End.
	func() {
		txn := app.StartTransaction("myTask")
		defer txn.End()

		// Do some work
		time.Sleep(time.Second)
	}()

	// WrapHandler and WrapHandleFunc make it easy to instrument inbound
	// web requests handled by the http standard library without calling
	// Application.StartTransaction.  Popular framework instrumentation
	// packages exist in the v3/integrations directory.
	http.HandleFunc(newrelic.WrapHandleFunc(app, "", func(w http.ResponseWriter, req *http.Request) {
		io.WriteString(w, "this is the index page")
	}))
	helloHandler := func(w http.ResponseWriter, req *http.Request) {
		// WrapHandler and WrapHandleFunc add the transaction to the
		// inbound request's context.  Access the transaction using
		// FromContext to add attributes, create segments, and notice.
		// errors.
		txn := newrelic.FromContext(req.Context())

		func() {
			// Segments help you understand where the time in your
			// transaction is being spent.  You can use them to time
			// functions or arbitrary blocks of code.
			defer txn.StartSegment("helperFunction").End()
		}()

		io.WriteString(w, "hello world")
	}
	http.HandleFunc(newrelic.WrapHandleFunc(app, "/hello", helloHandler))
	http.ListenAndServe(":8000", nil)
}
Output:

Index

Examples

Constants

View Source
const (
	// AttributeResponseCode is the response status code for a web request.
	AttributeResponseCode = "http.statusCode"
	// AttributeResponseCodeDeprecated is the response status code for a web
	// request, the same value as AttributeResponseCode. To completely exclude
	// this value from a destination, both AttributeResponseCode and
	// AttributeResponseCodeDeprecated must be specified.
	//
	// Deprecated: This attribute is currently deprecated and will be removed
	// in a later release.
	AttributeResponseCodeDeprecated = "httpResponseCode"
	// AttributeRequestMethod is the request's method.
	AttributeRequestMethod = "request.method"
	// AttributeRequestAccept is the request's "Accept" header.
	AttributeRequestAccept = "request.headers.accept"
	// AttributeRequestContentType is the request's "Content-Type" header.
	AttributeRequestContentType = "request.headers.contentType"
	// AttributeRequestContentLength is the request's "Content-Length" header.
	AttributeRequestContentLength = "request.headers.contentLength"
	// AttributeRequestHost is the request's "Host" header.
	AttributeRequestHost = "request.headers.host"
	// AttributeRequestURI is the request's URL without query parameters,
	// fragment, user, or password.
	AttributeRequestURI = "request.uri"
	// AttributeResponseContentType is the response "Content-Type" header.
	AttributeResponseContentType = "response.headers.contentType"
	// AttributeResponseContentLength is the response "Content-Length" header.
	AttributeResponseContentLength = "response.headers.contentLength"
	// AttributeHostDisplayName contains the value of Config.HostDisplayName.
	AttributeHostDisplayName = "host.displayName"
)

Attributes destined for Transaction Events, Errors, and Transaction Traces:

View Source
const (
	// AttributeRequestUserAgent is the request's "User-Agent" header.
	AttributeRequestUserAgent = "request.headers.userAgent"
	// AttributeRequestUserAgentDeprecated is the request's "User-Agent"
	// header, the same value as AttributeRequestUserAgent. To completely
	// exclude this value from a destination, both AttributeRequestUserAgent
	// and AttributeRequestUserAgentDeprecated must be specified.
	//
	// Deprecated: This attribute is currently deprecated and will be removed
	// in a later release.
	AttributeRequestUserAgentDeprecated = "request.headers.User-Agent"
	// AttributeRequestReferer is the request's "Referer" header.  Query
	// string parameters are removed.
	AttributeRequestReferer = "request.headers.referer"
)

Attributes destined for Errors and Transaction Traces:

View Source
const (
	AttributeAWSRequestID            = "aws.requestId"
	AttributeAWSLambdaARN            = "aws.lambda.arn"
	AttributeAWSLambdaColdStart      = "aws.lambda.coldStart"
	AttributeAWSLambdaEventSourceARN = "aws.lambda.eventSource.arn"
)

AWS Lambda specific attributes:

View Source
const (
	// The routing key of the consumed message.
	AttributeMessageRoutingKey = "message.routingKey"
	// The name of the queue the message was consumed from.
	AttributeMessageQueueName = "message.queueName"
	// The type of exchange used for the consumed message (direct, fanout,
	// topic, or headers).
	AttributeMessageExchangeType = "message.exchangeType"
	// The callback queue used in RPC configurations.
	AttributeMessageReplyTo = "message.replyTo"
	// The application-generated identifier used in RPC configurations.
	AttributeMessageCorrelationID = "message.correlationId"
)

Attributes for consumed message transactions:

When a message is consumed (for example from Kafka or RabbitMQ), supported instrumentation packages -- i.e. those found in the v3/integrations (https://godoc.org/github.com/newrelic/go-agent/v3/integrations) directory -- will add these attributes automatically. AttributeMessageExchangeType, AttributeMessageReplyTo, and AttributeMessageCorrelationID are disabled by default. To see these attributes added to all destinations, you must add include them in your config settings:

cfg.Attributes.Include = append(cfg.Attributes.Include,
	newrelic.AttributeMessageExchangeType,
	newrelic.AttributeMessageReplyTo,
	newrelic.AttributeMessageCorrelationID,
)

When not using a supported instrumentation package, you can add these attributes manually using the Transaction.AddAttribute (https://godoc.org/github.com/newrelic/go-agent/v3/newrelic#Transaction.AddAttribute) API. In this case, these attributes will be included on all destintations by default.

txn := app.StartTransaction("Message/RabbitMQ/Exchange/Named/MyExchange")
txn.AddAttribute(newrelic.AttributeMessageRoutingKey, "myRoutingKey")
txn.AddAttribute(newrelic.AttributeMessageQueueName, "myQueueName")
txn.AddAttribute(newrelic.AttributeMessageExchangeType, "myExchangeType")
txn.AddAttribute(newrelic.AttributeMessageReplyTo, "myReplyTo")
txn.AddAttribute(newrelic.AttributeMessageCorrelationID, "myCorrelationID")
// ... consume a message ...
txn.End()

It is recommended that at most one message is consumed per transaction.

View Source
const (
	SpanAttributeDBStatement             = "db.statement"
	SpanAttributeDBInstance              = "db.instance"
	SpanAttributeDBCollection            = "db.collection"
	SpanAttributePeerAddress             = "peer.address"
	SpanAttributePeerHostname            = "peer.hostname"
	SpanAttributeHTTPURL                 = "http.url"
	SpanAttributeHTTPMethod              = "http.method"
	SpanAttributeAWSOperation            = "aws.operation"
	SpanAttributeAWSRegion               = "aws.region"
	SpanAttributeErrorClass              = "error.class"
	SpanAttributeErrorMessage            = "error.message"
	SpanAttributeParentType              = "parent.type"
	SpanAttributeParentApp               = "parent.app"
	SpanAttributeParentAccount           = "parent.account"
	SpanAttributeParentTransportDuration = "parent.transportDuration"
	SpanAttributeParentTransportType     = "parent.transportType"

	// Deprecated: This attribute is a duplicate of AttributeResponseCode and
	// will be removed in a later release.
	SpanAttributeHTTPStatusCode = "http.statusCode"
	// Deprecated: This attribute is a duplicate of AttributeAWSRequestID and
	// will be removed in a later release.
	SpanAttributeAWSRequestID = "aws.requestId"
)

Attributes destined for Span Events. These attributes appear only on Span Events and are not available to transaction events, error events, or traced errors.

To disable the capture of one of these span event attributes, "db.statement" for example, modify your Config like this:

cfg.SpanEvents.Attributes.Exclude = append(cfg.SpanEvents.Attributes.Exclude,
	newrelic.SpanAttributeDBStatement)
View Source
const (
	// DistributedTraceNewRelicHeader is the header used by New Relic agents
	// for automatic trace payload instrumentation.
	DistributedTraceNewRelicHeader = "Newrelic"
	// DistributedTraceW3CTraceStateHeader is one of two headers used by W3C
	// trace context
	DistributedTraceW3CTraceStateHeader = "Tracestate"
	// DistributedTraceW3CTraceParentHeader is one of two headers used by W3C
	// trace context
	DistributedTraceW3CTraceParentHeader = "Traceparent"
)
View Source
const (
	// Version is the full string version of this Go Agent.
	Version = "3.13.0"
)

Variables

This section is empty.

Functions

func InstrumentSQLConnector

func InstrumentSQLConnector(connector driver.Connector, bld SQLDriverSegmentBuilder) driver.Connector

InstrumentSQLConnector wraps a driver.Connector, adding instrumentation for exec and query calls made with a transaction-containing context. Use this to instrument a database connector that is not supported by an existing integration package (nrmysql, nrpq, and nrsqlite3). See https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrmysql/nrmysql.go for example use.

func InstrumentSQLDriver

func InstrumentSQLDriver(d driver.Driver, bld SQLDriverSegmentBuilder) driver.Driver

InstrumentSQLDriver wraps a driver.Driver, adding instrumentation for exec and query calls made with a transaction-containing context. Use this to instrument a database driver that is not supported by an existing integration package (nrmysql, nrpq, and nrsqlite3). See https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrmysql/nrmysql.go for example use.

func NewContext

func NewContext(ctx context.Context, txn *Transaction) context.Context

NewContext returns a new context.Context that carries the provided transaction.

func NewRoundTripper

func NewRoundTripper(original http.RoundTripper) http.RoundTripper

NewRoundTripper creates an http.RoundTripper to instrument external requests and add distributed tracing headers. The http.RoundTripper returned creates an external segment before delegating to the original http.RoundTripper provided (or http.DefaultTransport if none is provided). The http.RoundTripper will look for a Transaction in the request's context (using FromContext).

Example
package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	client := &http.Client{}
	// The http.RoundTripper returned by NewRoundTripper instruments all
	// requests done by this client with external segments.
	client.Transport = newrelic.NewRoundTripper(client.Transport)

	request, _ := http.NewRequest("GET", "http://example.com", nil)

	// Be sure to add the current Transaction to each request's context so
	// the Transport has access to it.
	txn := currentTransaction()
	request = newrelic.RequestWithTransactionContext(request, txn)

	client.Do(request)
}
Output:

func NewStackTrace

func NewStackTrace() []uintptr

NewStackTrace generates a stack trace for the newrelic.Error struct's Stack field.

func RequestWithTransactionContext

func RequestWithTransactionContext(req *http.Request, txn *Transaction) *http.Request

RequestWithTransactionContext adds the Transaction to the request's context.

func WrapHandle

func WrapHandle(app *Application, pattern string, handler http.Handler) (string, http.Handler)

WrapHandle instruments http.Handler handlers with Transactions. To instrument this code:

http.Handle("/foo", myHandler)

Perform this replacement:

http.Handle(newrelic.WrapHandle(app, "/foo", myHandler))

WrapHandle adds the Transaction to the request's context. Access it using FromContext to add attributes, create segments, or notice errors:

func myHandler(rw ResponseWriter, req *Request) {
	txn := newrelic.FromContext(req.Context())
	txn.AddAttribute("customerLevel", "gold")
	io.WriteString(w, "users page")
}

The WrapHandle function is safe to call if app is nil.

func WrapHandleFunc

func WrapHandleFunc(app *Application, pattern string, handler func(http.ResponseWriter, *http.Request)) (string, func(http.ResponseWriter, *http.Request))

WrapHandleFunc instruments handler functions using Transactions. To instrument this code:

http.HandleFunc("/users", func(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "users page")
})

Perform this replacement:

http.HandleFunc(newrelic.WrapHandleFunc(app, "/users", func(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "users page")
}))

WrapHandleFunc adds the Transaction to the request's context. Access it using FromContext to add attributes, create segments, or notice errors:

http.HandleFunc(newrelic.WrapHandleFunc(app, "/users", func(w http.ResponseWriter, req *http.Request) {
	txn := newrelic.FromContext(req.Context())
	txn.AddAttribute("customerLevel", "gold")
	io.WriteString(w, "users page")
}))

The WrapHandleFunc function is safe to call if app is nil.

Types

type Application

type Application struct {
	Private interface{}
	// contains filtered or unexported fields
}

Application represents your application. All methods on Application are nil safe. Therefore, a nil Application pointer can be safely used as a mock.

func NewApplication

func NewApplication(opts ...ConfigOption) (*Application, error)

NewApplication creates an Application and spawns goroutines to manage the aggregation and harvesting of data. On success, a non-nil Application and a nil error are returned. On failure, a nil Application and a non-nil error are returned. All methods on an Application are nil safe. Therefore, a nil Application pointer can be safely used. Applications do not share global state, therefore it is safe to create multiple applications.

The ConfigOption arguments allow for configuration of the Application. They are applied in order from first to last, i.e. latter ConfigOptions may overwrite the Config fields already set.

Example (ConfigOptionOrder)
package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func main() {
	// In this case, the Application will be disabled because the disabling
	// ConfigOption is last.
	_, _ = newrelic.NewApplication(
		newrelic.ConfigEnabled(true),
		newrelic.ConfigEnabled(false),
	)
}
Output:

func (*Application) RecordCustomEvent

func (app *Application) RecordCustomEvent(eventType string, params map[string]interface{})

RecordCustomEvent adds a custom event.

eventType must consist of alphanumeric characters, underscores, and colons, and must contain fewer than 255 bytes.

Each value in the params map must be a number, string, or boolean. Keys must be less than 255 bytes. The params map may not contain more than 64 attributes. For more information, and a set of restricted keywords, see: https://docs.newrelic.com/docs/insights/new-relic-insights/adding-querying-data/inserting-custom-events-new-relic-apm-agents

An error is logged if eventType or params is invalid.

func (*Application) RecordCustomMetric

func (app *Application) RecordCustomMetric(name string, value float64)

RecordCustomMetric records a custom metric. The metric name you provide will be prefixed by "Custom/". Custom metrics are not currently supported in serverless mode.

See https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-metrics for more information on custom events.

func (*Application) Shutdown

func (app *Application) Shutdown(timeout time.Duration)

Shutdown flushes data to New Relic's servers and stops all agent-related goroutines managing this application. After Shutdown is called, the Application is disabled and will never collect data again. This method blocks until all final data is sent to New Relic or the timeout has elapsed. Increase the timeout and check debug logs if you aren't seeing data.

If Infinite Tracing is enabled, Shutdown will block until all queued span events have been sent to the Trace Observer or the timeout has been reached.

func (*Application) StartTransaction

func (app *Application) StartTransaction(name string) *Transaction

StartTransaction begins a Transaction with the given name.

func (*Application) WaitForConnection

func (app *Application) WaitForConnection(timeout time.Duration) error

WaitForConnection blocks until the application is connected, is incapable of being connected, or the timeout has been reached. This method is useful for short-lived processes since the application will not gather data until it is connected. nil is returned if the application is connected successfully.

If Infinite Tracing is enabled, WaitForConnection will block until a connection to the Trace Observer is made, a fatal error is reached, or the timeout is hit.

type AttributeDestinationConfig

type AttributeDestinationConfig struct {
	// Enabled controls whether or not this destination will get any
	// attributes at all.  For example, to prevent any attributes from being
	// added to errors, set:
	//
	//	cfg.ErrorCollector.Attributes.Enabled = false
	//
	Enabled bool
	Include []string
	// Exclude allows you to prevent the capture of certain attributes.  For
	// example, to prevent the capture of the request URL attribute
	// "request.uri", set:
	//
	//	cfg.Attributes.Exclude = append(cfg.Attributes.Exclude, newrelic.AttributeRequestURI)
	//
	// The '*' character acts as a wildcard.  For example, to prevent the
	// capture of all request related attributes, set:
	//
	//	cfg.Attributes.Exclude = append(cfg.Attributes.Exclude, "request.*")
	//
	Exclude []string
}

AttributeDestinationConfig controls the attributes sent to each destination. For more information, see: https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/agent-attributes

type BrowserTimingHeader

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

BrowserTimingHeader encapsulates the JavaScript required to enable New Relic's Browser product.

Example
package main

import (
	"io"
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func getApp() *newrelic.Application {
	return nil
}

func main() {
	handler := func(w http.ResponseWriter, req *http.Request) {
		io.WriteString(w, "<html><head>")
		// The New Relic browser javascript should be placed as high in the
		// HTML as possible.  We suggest including it immediately after the
		// opening <head> tag and any <meta charset> tags.
		txn := newrelic.FromContext(req.Context())
		hdr := txn.BrowserTimingHeader()
		// BrowserTimingHeader() will always return a header whose methods can
		// be safely called.
		if js := hdr.WithTags(); js != nil {
			w.Write(js)
		}
		io.WriteString(w, "</head><body>browser header page</body></html>")
	}
	http.HandleFunc(newrelic.WrapHandleFunc(getApp(), "/browser", handler))
	http.ListenAndServe(":8000", nil)
}
Output:

func (*BrowserTimingHeader) WithTags

func (h *BrowserTimingHeader) WithTags() []byte

WithTags returns the browser timing JavaScript which includes the enclosing <script> and </script> tags. This method returns nil if the receiver is nil, the feature is disabled, the application is not yet connected, or an error occurs. The byte slice returned is in UTF-8 format.

func (*BrowserTimingHeader) WithoutTags

func (h *BrowserTimingHeader) WithoutTags() []byte

WithoutTags returns the browser timing JavaScript without any enclosing tags, which may then be embedded within any JavaScript code. This method returns nil if the receiver is nil, the feature is disabled, the application is not yet connected, or an error occurs. The byte slice returned is in UTF-8 format.

type Config

type Config struct {
	// AppName is used by New Relic to link data across servers.
	//
	// https://docs.newrelic.com/docs/apm/new-relic-apm/installation-configuration/naming-your-application
	AppName string

	// License is your New Relic license key.
	//
	// https://docs.newrelic.com/docs/accounts/install-new-relic/account-setup/license-key
	License string

	// Logger controls Go Agent logging.
	//
	// See https://github.com/newrelic/go-agent/blob/master/GUIDE.md#logging
	// for more examples and logging integrations.
	Logger Logger

	// Enabled controls whether the agent will communicate with the New Relic
	// servers and spawn goroutines.  Setting this to be false is useful in
	// testing and staging situations.
	Enabled bool

	// Labels are key value pairs used to roll up applications into specific
	// categories.
	//
	// https://docs.newrelic.com/docs/using-new-relic/user-interface-functions/organize-your-data/labels-categories-organize-apps-monitors
	Labels map[string]string

	// HighSecurity guarantees that certain agent settings can not be made
	// more permissive.  This setting must match the corresponding account
	// setting in the New Relic UI.
	//
	// https://docs.newrelic.com/docs/agents/manage-apm-agents/configuration/high-security-mode
	HighSecurity bool

	// SecurityPoliciesToken enables security policies if set to a non-empty
	// string.  Only set this if security policies have been enabled on your
	// account.  This cannot be used in conjunction with HighSecurity.
	//
	// https://docs.newrelic.com/docs/agents/manage-apm-agents/configuration/enable-configurable-security-policies
	SecurityPoliciesToken string

	// CustomInsightsEvents controls the behavior of
	// Application.RecordCustomEvent.
	//
	// https://docs.newrelic.com/docs/insights/new-relic-insights/adding-querying-data/inserting-custom-events-new-relic-apm-agents
	CustomInsightsEvents struct {
		// Enabled controls whether RecordCustomEvent will collect
		// custom analytics events.  High security mode overrides this
		// setting.
		Enabled bool
	}

	// TransactionEvents controls the behavior of transaction analytics
	// events.
	TransactionEvents struct {
		// Enabled controls whether transaction events are captured.
		Enabled bool
		// Attributes controls the attributes included with transaction
		// events.
		Attributes AttributeDestinationConfig
		// MaxSamplesStored allows you to limit the number of Transaction
		// Events stored/reported in a given 60-second period
		MaxSamplesStored int
	}

	// ErrorCollector controls the capture of errors.
	ErrorCollector struct {
		// Enabled controls whether errors are captured.  This setting
		// affects both traced errors and error analytics events.
		Enabled bool
		// CaptureEvents controls whether error analytics events are
		// captured.
		CaptureEvents bool
		// IgnoreStatusCodes controls which http response codes are
		// automatically turned into errors.  By default, response codes
		// greater than or equal to 400 or less than 100 -- with the exception
		// of 0, 5, and 404 -- are turned into errors.
		IgnoreStatusCodes []int
		// Attributes controls the attributes included with errors.
		Attributes AttributeDestinationConfig
		// RecordPanics controls whether or not a deferred
		// Transaction.End will attempt to recover panics, record them
		// as errors, and then re-panic them.  By default, this is
		// set to false.
		RecordPanics bool
	}

	// TransactionTracer controls the capture of transaction traces.
	TransactionTracer struct {
		// Enabled controls whether transaction traces are captured.
		Enabled bool
		// Threshold controls whether a transaction trace will be
		// considered for capture.  Of the traces exceeding the
		// threshold, the slowest trace every minute is captured.
		Threshold struct {
			// If IsApdexFailing is true then the trace threshold is
			// four times the apdex threshold.
			IsApdexFailing bool
			// If IsApdexFailing is false then this field is the
			// threshold, otherwise it is ignored.
			Duration time.Duration
		}
		// Attributes controls the attributes included with transaction
		// traces.
		Attributes AttributeDestinationConfig
		// Segments contains fields which control the behavior of
		// transaction trace segments.
		Segments struct {
			// StackTraceThreshold is the threshold at which
			// segments will be given a stack trace in the
			// transaction trace.  Lowering this setting will
			// increase overhead.
			StackTraceThreshold time.Duration
			// Threshold is the threshold at which segments will be
			// added to the trace.  Lowering this setting may
			// increase overhead.  Decrease this duration if your
			// transaction traces are missing segments.
			Threshold time.Duration
			// Attributes controls the attributes included with each
			// trace segment.
			Attributes AttributeDestinationConfig
		}
	}

	// BrowserMonitoring contains settings which control the behavior of
	// Transaction.BrowserTimingHeader.
	BrowserMonitoring struct {
		// Enabled controls whether or not the Browser monitoring feature is
		// enabled.
		Enabled bool
		// Attributes controls the attributes included with Browser monitoring.
		// BrowserMonitoring.Attributes.Enabled is false by default, to include
		// attributes in the Browser timing Javascript:
		//
		//	cfg.BrowserMonitoring.Attributes.Enabled = true
		Attributes AttributeDestinationConfig
	}

	// HostDisplayName gives this server a recognizable name in the New
	// Relic UI.  This is an optional setting.
	HostDisplayName string

	// Transport customizes communication with the New Relic servers.  This may
	// be used to configure a proxy.
	Transport http.RoundTripper

	// Utilization controls the detection and gathering of system
	// information.
	Utilization struct {
		// DetectAWS controls whether the Application attempts to detect
		// AWS.
		DetectAWS bool
		// DetectAzure controls whether the Application attempts to detect
		// Azure.
		DetectAzure bool
		// DetectPCF controls whether the Application attempts to detect
		// PCF.
		DetectPCF bool
		// DetectGCP controls whether the Application attempts to detect
		// GCP.
		DetectGCP bool
		// DetectDocker controls whether the Application attempts to
		// detect Docker.
		DetectDocker bool
		// DetectKubernetes controls whether the Application attempts to
		// detect Kubernetes.
		DetectKubernetes bool

		// These settings provide system information when custom values
		// are required.
		LogicalProcessors int
		TotalRAMMIB       int
		BillingHostname   string
	}

	// Heroku controls the behavior of Heroku specific features.
	Heroku struct {
		// UseDynoNames controls if Heroku dyno names are reported as the
		// hostname.  Default is true.
		UseDynoNames bool
		// DynoNamePrefixesToShorten allows you to shorten and combine some
		// Heroku dyno names into a single value.  Ordinarily the agent reports
		// dyno names with a trailing dot and process ID (for example,
		// worker.3). You can remove this trailing data by specifying the
		// prefixes you want to report without trailing data (for example,
		// worker.*).  Defaults to shortening "scheduler" and "run" dyno names.
		DynoNamePrefixesToShorten []string
	}

	// CrossApplicationTracer controls behavior relating to cross application
	// tracing (CAT).  In the case where CrossApplicationTracer and
	// DistributedTracer are both enabled, DistributedTracer takes precedence.
	//
	// https://docs.newrelic.com/docs/apm/transactions/cross-application-traces/introduction-cross-application-traces
	CrossApplicationTracer struct {
		Enabled bool
	}

	// DistributedTracer controls behavior relating to Distributed Tracing.  In
	// the case where CrossApplicationTracer and DistributedTracer are both
	// enabled, DistributedTracer takes precedence.
	//
	// https://docs.newrelic.com/docs/apm/distributed-tracing/getting-started/introduction-distributed-tracing
	DistributedTracer struct {
		Enabled bool
		// ExcludeNewRelicHeader allows you to choose whether to insert the New
		// Relic Distributed Tracing header on outbound requests, which by
		// default is emitted along with the W3C trace context headers.  Set
		// this value to true if you do not want to include the New Relic
		// distributed tracing header in your outbound requests.
		//
		// Disabling the New Relic header here does not prevent the agent from
		// accepting *inbound* New Relic headers.
		ExcludeNewRelicHeader bool
	}

	// SpanEvents controls behavior relating to Span Events.  Span Events
	// require that DistributedTracer is enabled.
	SpanEvents struct {
		Enabled bool
		// Attributes controls the attributes included on Spans.
		Attributes AttributeDestinationConfig
	}

	// InfiniteTracing controls behavior related to Infinite Tracing tail based
	// sampling.  InfiniteTracing requires that both DistributedTracer and
	// SpanEvents are enabled.
	//
	// https://docs.newrelic.com/docs/understand-dependencies/distributed-tracing/enable-configure/enable-distributed-tracing
	InfiniteTracing struct {
		// TraceObserver controls behavior of connecting to the Trace Observer.
		TraceObserver struct {
			// Host is the Trace Observer host to connect to and tells the
			// Application to enable Infinite Tracing support. When this field
			// is set to an empty string, which is the default, Infinite
			// Tracing support is disabled.
			Host string
			// Port is the Trace Observer port to connect to. The default is
			// 443.
			Port int
		}
		// SpanEvents controls the behavior of the span events sent to the
		// Trace Observer.
		SpanEvents struct {
			// QueueSize is the maximum number of span events that may be held
			// in memory as they wait to be serialized and sent to the Trace
			// Observer.  Default value is 10,000. Any span event created when
			// the QueueSize limit is reached will be discarded.
			QueueSize int
		}
	}

	// DatastoreTracer controls behavior relating to datastore segments.
	DatastoreTracer struct {
		// InstanceReporting controls whether the host and port are collected
		// for datastore segments.
		InstanceReporting struct {
			Enabled bool
		}
		// DatabaseNameReporting controls whether the database name is
		// collected for datastore segments.
		DatabaseNameReporting struct {
			Enabled bool
		}
		QueryParameters struct {
			Enabled bool
		}
		// SlowQuery controls the capture of slow query traces.  Slow
		// query traces show you instances of your slowest datastore
		// segments.
		SlowQuery struct {
			Enabled   bool
			Threshold time.Duration
		}
	}

	// Attributes controls which attributes are enabled and disabled globally.
	// This setting affects all attribute destinations: Transaction Events,
	// Error Events, Transaction Traces and segments, Traced Errors, Span
	// Events, and Browser timing header.
	Attributes AttributeDestinationConfig

	// RuntimeSampler controls the collection of runtime statistics like
	// CPU/Memory usage, goroutine count, and GC pauses.
	RuntimeSampler struct {
		// Enabled controls whether runtime statistics are captured.
		Enabled bool
	}

	// ServerlessMode contains fields which control behavior when running in
	// AWS Lambda.
	//
	// https://docs.newrelic.com/docs/serverless-function-monitoring/aws-lambda-monitoring/get-started/introduction-new-relic-monitoring-aws-lambda
	ServerlessMode struct {
		// Enabling ServerlessMode will print each transaction's data to
		// stdout.  No agent goroutines will be spawned in serverless mode, and
		// no data will be sent directly to the New Relic backend.
		// nrlambda.NewConfig sets Enabled to true.
		Enabled bool
		// ApdexThreshold sets the Apdex threshold when in ServerlessMode.  The
		// default is 500 milliseconds.  nrlambda.NewConfig populates this
		// field using the NEW_RELIC_APDEX_T environment variable.
		//
		// https://docs.newrelic.com/docs/apm/new-relic-apm/apdex/apdex-measure-user-satisfaction
		ApdexThreshold time.Duration
		// AccountID, TrustedAccountKey, and PrimaryAppID are used for
		// distributed tracing in ServerlessMode.  AccountID and
		// TrustedAccountKey must be populated for distributed tracing to be
		// enabled. nrlambda.NewConfig populates these fields using the
		// NEW_RELIC_ACCOUNT_ID, NEW_RELIC_TRUSTED_ACCOUNT_KEY, and
		// NEW_RELIC_PRIMARY_APPLICATION_ID environment variables.
		AccountID         string
		TrustedAccountKey string
		PrimaryAppID      string
	}

	// Host can be used to override the New Relic endpoint.
	Host string

	// Error may be populated by the ConfigOptions provided to NewApplication
	// to indicate that setup has failed.  NewApplication will return this
	// error if it is set.
	Error error
}

Config contains Application and Transaction behavior settings.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption configures the Config when provided to NewApplication.

Example (Custom)

While many ConfigOptions are provided for you, it is also possible to create your own. This is necessary if you have complex configuration needs.

package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func main() {
	_, _ = newrelic.NewApplication(
		newrelic.ConfigAppName("Example App"),
		newrelic.ConfigLicense("__YOUR_NEW_RELIC_LICENSE_KEY__"),
		func(cfg *newrelic.Config) {
			// Set specific Config fields inside a custom ConfigOption.
			cfg.Attributes.Enabled = false
			cfg.HighSecurity = true
		},
	)
}
Output:

Example (Errors)

Setting the Config.Error field will cause the NewApplication function to return an error.

package main

import (
	"errors"
	"fmt"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func main() {
	myError := errors.New("oops")

	_, err := newrelic.NewApplication(
		newrelic.ConfigAppName("Example App"),
		newrelic.ConfigLicense("__YOUR_NEW_RELIC_LICENSE_KEY__"),
		func(cfg *newrelic.Config) {
			cfg.Error = myError
		},
	)

	fmt.Printf("%t", err == myError)
}
Output:

true

func ConfigAppName

func ConfigAppName(appName string) ConfigOption

ConfigAppName sets the application name.

func ConfigDebugLogger

func ConfigDebugLogger(w io.Writer) ConfigOption

ConfigDebugLogger populates the config with a Logger at debug level.

func ConfigDistributedTracerEnabled

func ConfigDistributedTracerEnabled(enabled bool) ConfigOption

ConfigDistributedTracerEnabled populates the Config's DistributedTracer.Enabled setting.

func ConfigEnabled

func ConfigEnabled(enabled bool) ConfigOption

ConfigEnabled sets the whether or not the agent is enabled.

func ConfigFromEnvironment

func ConfigFromEnvironment() ConfigOption

ConfigFromEnvironment populates the config based on environment variables:

NEW_RELIC_APP_NAME                                sets AppName
NEW_RELIC_ATTRIBUTES_EXCLUDE                      sets Attributes.Exclude using a comma-separated list, eg. "request.headers.host,request.method"
NEW_RELIC_ATTRIBUTES_INCLUDE                      sets Attributes.Include using a comma-separated list
NEW_RELIC_DISTRIBUTED_TRACING_ENABLED             sets DistributedTracer.Enabled using strconv.ParseBool
NEW_RELIC_ENABLED                                 sets Enabled using strconv.ParseBool
NEW_RELIC_HIGH_SECURITY                           sets HighSecurity using strconv.ParseBool
NEW_RELIC_HOST                                    sets Host
NEW_RELIC_INFINITE_TRACING_SPAN_EVENTS_QUEUE_SIZE sets InfiniteTracing.SpanEvents.QueueSize using strconv.Atoi
NEW_RELIC_INFINITE_TRACING_TRACE_OBSERVER_PORT    sets InfiniteTracing.TraceObserver.Port using strconv.Atoi
NEW_RELIC_INFINITE_TRACING_TRACE_OBSERVER_HOST    sets InfiniteTracing.TraceObserver.Host
NEW_RELIC_LABELS                                  sets Labels using a semi-colon delimited string of colon-separated pairs, eg. "Server:One;DataCenter:Primary"
NEW_RELIC_LICENSE_KEY                             sets License
NEW_RELIC_LOG                                     sets Logger to log to either "stdout" or "stderr" (filenames are not supported)
NEW_RELIC_LOG_LEVEL                               controls the NEW_RELIC_LOG level, must be "debug" for debug, or empty for info
NEW_RELIC_PROCESS_HOST_DISPLAY_NAME               sets HostDisplayName
NEW_RELIC_SECURITY_POLICIES_TOKEN                 sets SecurityPoliciesToken
NEW_RELIC_UTILIZATION_BILLING_HOSTNAME            sets Utilization.BillingHostname
NEW_RELIC_UTILIZATION_LOGICAL_PROCESSORS          sets Utilization.LogicalProcessors using strconv.Atoi
NEW_RELIC_UTILIZATION_TOTAL_RAM_MIB               sets Utilization.TotalRAMMIB using strconv.Atoi

This function is strict and will assign Config.Error if any of the environment variables cannot be parsed.

Example

The order in which the ConfigOptions are added plays an important role when using ConfigFromEnvironment.

package main

import (
	"os"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func main() {
	os.Setenv("NEW_RELIC_ENABLED", "true")

	// Application is disabled.  Enabled is first set to true from
	// ConfigFromEnvironment then set to false from ConfigEnabled.
	_, _ = newrelic.NewApplication(
		newrelic.ConfigFromEnvironment(),
		newrelic.ConfigEnabled(false),
	)

	// Application is enabled.  Enabled is first set to false from
	// ConfigEnabled then set to true from ConfigFromEnvironment.
	_, _ = newrelic.NewApplication(
		newrelic.ConfigEnabled(false),
		newrelic.ConfigFromEnvironment(),
	)
}
Output:

func ConfigInfoLogger

func ConfigInfoLogger(w io.Writer) ConfigOption

ConfigInfoLogger populates the config with basic Logger at info level.

func ConfigLicense

func ConfigLicense(license string) ConfigOption

ConfigLicense sets the license.

func ConfigLogger

func ConfigLogger(l Logger) ConfigOption

ConfigLogger populates the Config's Logger.

type DatastoreProduct

type DatastoreProduct string

DatastoreProduct is used to identify your datastore type in New Relic. It is used in the DatastoreSegment Product field.

const (
	DatastoreCassandra     DatastoreProduct = "Cassandra"
	DatastoreCouchDB       DatastoreProduct = "CouchDB"
	DatastoreDerby         DatastoreProduct = "Derby"
	DatastoreDynamoDB      DatastoreProduct = "DynamoDB"
	DatastoreElasticsearch DatastoreProduct = "Elasticsearch"
	DatastoreFirebird      DatastoreProduct = "Firebird"
	DatastoreIBMDB2        DatastoreProduct = "IBMDB2"
	DatastoreInformix      DatastoreProduct = "Informix"
	DatastoreMemcached     DatastoreProduct = "Memcached"
	DatastoreMongoDB       DatastoreProduct = "MongoDB"
	DatastoreMSSQL         DatastoreProduct = "MSSQL"
	DatastoreMySQL         DatastoreProduct = "MySQL"
	DatastoreNeptune       DatastoreProduct = "Neptune"
	DatastoreOracle        DatastoreProduct = "Oracle"
	DatastorePostgres      DatastoreProduct = "Postgres"
	DatastoreRedis         DatastoreProduct = "Redis"
	DatastoreRiak          DatastoreProduct = "Riak"
	DatastoreSnowflake     DatastoreProduct = "Snowflake"
	DatastoreSolr          DatastoreProduct = "Solr"
	DatastoreSQLite        DatastoreProduct = "SQLite"
	DatastoreTarantool     DatastoreProduct = "Tarantool"
	DatastoreVoltDB        DatastoreProduct = "VoltDB"
	DatastoreAerospike     DatastoreProduct = "Aerospike"
)

Datastore names used across New Relic agents:

type DatastoreSegment

type DatastoreSegment struct {
	// StartTime should be assigned using Transaction.StartSegmentNow before
	// each datastore call is made.
	StartTime SegmentStartTime

	// Product, Collection, and Operation are highly recommended as they are
	// used for aggregate metrics:
	//
	// Product is the datastore type.  See the constants in
	// https://github.com/newrelic/go-agent/blob/master/datastore.go.  Product
	// is one of the fields primarily responsible for the grouping of Datastore
	// metrics.
	Product DatastoreProduct
	// Collection is the table or group being operated upon in the datastore,
	// e.g. "users_table".  This becomes the db.collection attribute on Span
	// events and Transaction Trace segments.  Collection is one of the fields
	// primarily responsible for the grouping of Datastore metrics.
	Collection string
	// Operation is the relevant action, e.g. "SELECT" or "GET".  Operation is
	// one of the fields primarily responsible for the grouping of Datastore
	// metrics.
	Operation string

	// The following fields are used for extra metrics and added to instance
	// data:
	//
	// ParameterizedQuery may be set to the query being performed.  It must
	// not contain any raw parameters, only placeholders.
	ParameterizedQuery string
	// QueryParameters may be used to provide query parameters.  Care should
	// be taken to only provide parameters which are not sensitive.
	// QueryParameters are ignored in high security mode. The keys must contain
	// fewer than than 255 bytes.  The values must be numbers, strings, or
	// booleans.
	QueryParameters map[string]interface{}
	// Host is the name of the server hosting the datastore.
	Host string
	// PortPathOrID can represent either the port, path, or id of the
	// datastore being connected to.
	PortPathOrID string
	// DatabaseName is name of database instance where the current query is
	// being executed.  This becomes the db.instance attribute on Span events
	// and Transaction Trace segments.
	DatabaseName string
}

DatastoreSegment is used to instrument calls to databases and object stores.

Example
package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	ds := &newrelic.DatastoreSegment{
		StartTime: txn.StartSegmentNow(),
		// Product, Collection, and Operation are the primary metric
		// aggregation fields which we encourage you to populate.
		Product:    newrelic.DatastoreMySQL,
		Collection: "users_table",
		Operation:  "SELECT",
	}
	// your database call here
	ds.End()
}
Output:

func (*DatastoreSegment) AddAttribute

func (s *DatastoreSegment) AddAttribute(key string, val interface{})

AddAttribute adds a key value pair to the current DatastoreSegment.

The key must contain fewer than than 255 bytes. The value must be a number, string, or boolean.

func (*DatastoreSegment) End

func (s *DatastoreSegment) End()

End finishes the datastore segment.

type Error

type Error struct {
	// Message is the error message which will be returned by the Error()
	// method.
	Message string
	// Class indicates how the error may be aggregated.
	Class string
	// Attributes are attached to traced errors and error events for
	// additional context.  These attributes are validated just like those
	// added to Transaction.AddAttribute.
	Attributes map[string]interface{}
	// Stack is the stack trace.  Assign this field using NewStackTrace,
	// or leave it nil to indicate that Transaction.NoticeError should
	// generate one.
	Stack []uintptr
}

Error is an error designed for use with Transaction.NoticeError. It allows direct control over the recorded error's message, class, stacktrace, and attributes.

Example
package main

import (
	"fmt"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	username := "gopher"
	e := fmt.Errorf("error unable to login user %s", username)
	// txn.NoticeError(newrelic.Error{...}) instead of txn.NoticeError(e)
	// allows more control over error fields.  Class is how errors are
	// aggregated and Attributes are added to the error event and error
	// trace.
	txn.NoticeError(newrelic.Error{
		Message: e.Error(),
		Class:   "LoginError",
		Attributes: map[string]interface{}{
			"username": username,
		},
	})
}
Output:

func (Error) Error

func (e Error) Error() string

func (Error) ErrorAttributes

func (e Error) ErrorAttributes() map[string]interface{}

ErrorAttributes returns the error's extra attributes.

func (Error) ErrorClass

func (e Error) ErrorClass() string

ErrorClass returns the error's class.

func (Error) StackTrace

func (e Error) StackTrace() []uintptr

StackTrace returns the error's stack.

type ExternalSegment

type ExternalSegment struct {
	StartTime SegmentStartTime
	Request   *http.Request
	Response  *http.Response

	// URL is an optional field which can be populated in lieu of Request if
	// you don't have an http.Request.  Either URL or Request must be
	// populated.  If both are populated then Request information takes
	// priority.  URL is parsed using url.Parse so it must include the
	// protocol scheme (eg. "http://").
	URL string
	// Host is an optional field that is automatically populated from the
	// Request or URL.  It is used for external metrics, transaction trace
	// segment names, and span event names.  Use this field to override the
	// host in the URL or Request.  This field does not override the host in
	// the "http.url" attribute.
	Host string
	// Procedure is an optional field that can be set to the remote
	// procedure being called.  If set, this value will be used in metrics,
	// transaction trace segment names, and span event names.  If unset, the
	// request's http method is used.
	Procedure string
	// Library is an optional field that defaults to "http".  It is used for
	// external metrics and the "component" span attribute.  It should be
	// the framework making the external call.
	Library string
	// contains filtered or unexported fields
}

ExternalSegment instruments external calls. StartExternalSegment is the recommended way to create ExternalSegments.

Example
package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	client := &http.Client{}
	request, _ := http.NewRequest("GET", "http://www.example.com", nil)
	segment := newrelic.StartExternalSegment(txn, request)
	response, _ := client.Do(request)
	segment.Response = response
	segment.End()
}
Output:

Example (Url)

StartExternalSegment is the recommend way of creating ExternalSegments. If you don't have access to an http.Request, however, you may create an ExternalSegment and control the URL manually.

package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	segment := newrelic.ExternalSegment{
		StartTime: txn.StartSegmentNow(),
		// URL is parsed using url.Parse so it must include the protocol
		// scheme (eg. "http://").  The host of the URL is used to
		// create metrics.  Change the host to alter aggregation.
		URL: "http://www.example.com",
	}
	http.Get("http://www.example.com")
	segment.End()
}
Output:

func StartExternalSegment

func StartExternalSegment(txn *Transaction, request *http.Request) *ExternalSegment

StartExternalSegment starts the instrumentation of an external call and adds distributed tracing headers to the request. If the Transaction parameter is nil then StartExternalSegment will look for a Transaction in the request's context using FromContext.

Using the same http.Client for all of your external requests? Check out NewRoundTripper: You may not need to use StartExternalSegment at all!

Example
package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	client := &http.Client{}
	request, _ := http.NewRequest("GET", "http://www.example.com", nil)
	segment := newrelic.StartExternalSegment(txn, request)
	response, _ := client.Do(request)
	segment.Response = response
	segment.End()
}
Output:

Example (Context)
package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	request, _ := http.NewRequest("GET", "http://www.example.com", nil)

	// If the transaction is added to the request's context then it does not
	// need to be provided as a parameter to StartExternalSegment.
	request = newrelic.RequestWithTransactionContext(request, txn)
	segment := newrelic.StartExternalSegment(nil, request)

	client := &http.Client{}
	response, _ := client.Do(request)
	segment.Response = response
	segment.End()
}
Output:

func (*ExternalSegment) AddAttribute

func (s *ExternalSegment) AddAttribute(key string, val interface{})

AddAttribute adds a key value pair to the current ExternalSegment.

The key must contain fewer than than 255 bytes. The value must be a number, string, or boolean.

func (*ExternalSegment) End

func (s *ExternalSegment) End()

End finishes the external segment.

func (*ExternalSegment) SetStatusCode

func (s *ExternalSegment) SetStatusCode(code int)

SetStatusCode sets the status code for the response of this ExternalSegment. This status code will be included as an attribute on Span Events. If status code is not set using this method, then the status code found on the ExternalSegment.Response will be used.

Use this method when you are creating ExternalSegment manually using either StartExternalSegment or the ExternalSegment struct directly. Status code is set automatically when using NewRoundTripper.

Example

Use ExternalSegment.SetStatusCode when you do not have access to an http.Response and still want to record the response status code.

package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func doSendRequest(*http.Request) int { return 418 }

func main() {
	txn := currentTransaction()
	request, _ := http.NewRequest("GET", "http://www.example.com", nil)
	segment := newrelic.StartExternalSegment(txn, request)
	statusCode := doSendRequest(request)
	segment.SetStatusCode(statusCode)
	segment.End()
}
Output:

type LinkingMetadata

type LinkingMetadata struct {
	// TraceID identifies the entire distributed trace.  This field is empty
	// if distributed tracing is disabled.
	TraceID string
	// SpanID identifies the currently active segment.  This field is empty
	// if distributed tracing is disabled or the transaction is not sampled.
	SpanID string
	// EntityName is the Application name as set on the Config.  If multiple
	// application names are specified in the Config, only the first is
	// returned.
	EntityName string
	// EntityType is the type of this entity and is always the string
	// "SERVICE".
	EntityType string
	// EntityGUID is the unique identifier for this entity.
	EntityGUID string
	// Hostname is the hostname this entity is running on.
	Hostname string
}

LinkingMetadata is returned by Transaction.GetLinkingMetadata. It contains identifiers needed to link data to a trace or entity.

type Logger

type Logger interface {
	Error(msg string, context map[string]interface{})
	Warn(msg string, context map[string]interface{})
	Info(msg string, context map[string]interface{})
	Debug(msg string, context map[string]interface{})
	DebugEnabled() bool
}

Logger is the interface that is used for logging in the Go Agent. Assign the Config.Logger field to the Logger you wish to use. Loggers must be safe for use in multiple goroutines. Two Logger implementations are included: NewLogger, which logs at info level, and NewDebugLogger which logs at debug level. logrus, logxi, and zap are supported by the integration packages https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrlogrus, https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrlogxi, and https://godoc.org/github.com/newrelic/go-agent/v3/integrations/nrzap respectively.

func NewDebugLogger deprecated

func NewDebugLogger(w io.Writer) Logger

NewDebugLogger creates a basic Logger at debug level.

Deprecated: NewDebugLogger is deprecated and will be removed in a future release. Use the ConfigDebugLogger ConfigOption instead.

func NewLogger deprecated

func NewLogger(w io.Writer) Logger

NewLogger creates a basic Logger at info level.

Deprecated: NewLogger is deprecated and will be removed in a future release. Use the ConfigInfoLogger ConfigOption instead.

type MessageDestinationType

type MessageDestinationType string

MessageDestinationType is used for the MessageSegment.DestinationType field.

const (
	MessageQueue    MessageDestinationType = "Queue"
	MessageTopic    MessageDestinationType = "Topic"
	MessageExchange MessageDestinationType = "Exchange"
)

These message destination type constants are used in for the MessageSegment.DestinationType field.

type MessageProducerSegment

type MessageProducerSegment struct {
	StartTime SegmentStartTime

	// Library is the name of the library instrumented.  eg. "RabbitMQ",
	// "JMS"
	Library string

	// DestinationType is the destination type.
	DestinationType MessageDestinationType

	// DestinationName is the name of your queue or topic.  eg. "UsersQueue".
	DestinationName string

	// DestinationTemporary must be set to true if destination is temporary
	// to improve metric grouping.
	DestinationTemporary bool
}

MessageProducerSegment instruments calls to add messages to a queueing system.

Example
package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	seg := &newrelic.MessageProducerSegment{
		StartTime:       txn.StartSegmentNow(),
		Library:         "RabbitMQ",
		DestinationType: newrelic.MessageExchange,
		DestinationName: "myExchange",
	}
	// add message to queue here
	seg.End()
}
Output:

func (*MessageProducerSegment) AddAttribute

func (s *MessageProducerSegment) AddAttribute(key string, val interface{})

AddAttribute adds a key value pair to the current MessageProducerSegment.

The key must contain fewer than than 255 bytes. The value must be a number, string, or boolean.

func (*MessageProducerSegment) End

func (s *MessageProducerSegment) End()

End finishes the message segment.

type SQLDriverSegmentBuilder

type SQLDriverSegmentBuilder struct {
	BaseSegment DatastoreSegment
	ParseQuery  func(segment *DatastoreSegment, query string)
	ParseDSN    func(segment *DatastoreSegment, dataSourceName string)
}

SQLDriverSegmentBuilder populates DatastoreSegments for sql.Driver instrumentation. Use this to instrument a database that is not supported by an existing integration package (nrmysql, nrpq, and nrsqlite3). See https://github.com/newrelic/go-agent/blob/master/v3/integrations/nrmysql/nrmysql.go for example use.

type Segment

type Segment struct {
	StartTime SegmentStartTime
	Name      string
}

Segment is used to instrument functions, methods, and blocks of code. The easiest way use Segment is the Transaction.StartSegment method.

func StartSegment deprecated

func StartSegment(txn *Transaction, name string) *Segment

StartSegment instruments segments.

Deprecated: StartSegment is deprecated and will be removed in a future release. Use Transaction.StartSegment instead.

func (*Segment) AddAttribute

func (s *Segment) AddAttribute(key string, val interface{})

AddAttribute adds a key value pair to the current segment.

The key must contain fewer than than 255 bytes. The value must be a number, string, or boolean.

func (*Segment) End

func (s *Segment) End()

End finishes the segment.

type SegmentStartTime

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

SegmentStartTime is created by Transaction.StartSegmentNow and marks the beginning of a segment. A segment with a zero-valued SegmentStartTime may safely be ended.

func StartSegmentNow deprecated

func StartSegmentNow(txn *Transaction) SegmentStartTime

StartSegmentNow starts timing a segment.

Deprecated: StartSegmentNow is deprecated and will be removed in a future release. Use Transaction.StartSegmentNow instead.

type TraceMetadata

type TraceMetadata struct {
	// TraceID identifies the entire distributed trace.  This field is empty
	// if distributed tracing is disabled.
	TraceID string
	// SpanID identifies the currently active segment.  This field is empty
	// if distributed tracing is disabled or the transaction is not sampled.
	SpanID string
}

TraceMetadata is returned by Transaction.GetTraceMetadata. It contains distributed tracing identifiers.

type Transaction

type Transaction struct {
	Private interface{}
	// contains filtered or unexported fields
}

Transaction instruments one logical unit of work: either an inbound web request or background task. Start a new Transaction with the Application.StartTransaction method.

All methods on Transaction are nil safe. Therefore, a nil Transaction pointer can be safely used as a mock.

func FromContext

func FromContext(ctx context.Context) *Transaction

FromContext returns the Transaction from the context if present, and nil otherwise.

func (*Transaction) AcceptDistributedTraceHeaders

func (txn *Transaction) AcceptDistributedTraceHeaders(t TransportType, hdrs http.Header)

AcceptDistributedTraceHeaders links transactions by accepting distributed trace headers from another transaction.

Transaction.SetWebRequest and Transaction.SetWebRequestHTTP both call this method automatically with the request headers. Therefore, this method does not need to be used for typical HTTP transactions.

AcceptDistributedTraceHeaders should be used as early in the transaction as possible. It may not be called after a call to Transaction.InsertDistributedTraceHeaders.

AcceptDistributedTraceHeaders first looks for the presence of W3C trace context headers. Only when those are not found will it look for the New Relic distributed tracing header.

func (*Transaction) AddAttribute

func (txn *Transaction) AddAttribute(key string, value interface{})

AddAttribute adds a key value pair to the transaction event, errors, and traces.

The key must contain fewer than than 255 bytes. The value must be a number, string, or boolean.

For more information, see: https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-metrics/collect-custom-attributes

func (*Transaction) Application

func (txn *Transaction) Application() *Application

Application returns the Application which started the transaction.

func (*Transaction) BrowserTimingHeader

func (txn *Transaction) BrowserTimingHeader() *BrowserTimingHeader

BrowserTimingHeader generates the JavaScript required to enable New Relic's Browser product. This code should be placed into your pages as close to the top of the <head> element as possible, but after any position-sensitive <meta> tags (for example, X-UA-Compatible or charset information).

This function freezes the transaction name: any calls to SetName() after BrowserTimingHeader() will be ignored.

The *BrowserTimingHeader return value will be nil if browser monitoring is disabled, the application is not connected, or an error occurred. It is safe to call the pointer's methods if it is nil.

func (*Transaction) End

func (txn *Transaction) End()

End finishes the Transaction. After that, subsequent calls to End or other Transaction methods have no effect. All segments and instrumentation must be completed before End is called.

func (*Transaction) GetLinkingMetadata

func (txn *Transaction) GetLinkingMetadata() LinkingMetadata

GetLinkingMetadata returns the fields needed to link data to a trace or entity.

func (*Transaction) GetTraceMetadata

func (txn *Transaction) GetTraceMetadata() TraceMetadata

GetTraceMetadata returns distributed tracing identifiers. Empty string identifiers are returned if the transaction has finished.

func (*Transaction) Ignore

func (txn *Transaction) Ignore()

Ignore prevents this transaction's data from being recorded.

func (*Transaction) InsertDistributedTraceHeaders

func (txn *Transaction) InsertDistributedTraceHeaders(hdrs http.Header)

InsertDistributedTraceHeaders adds the Distributed Trace headers used to link transactions. InsertDistributedTraceHeaders should be called every time an outbound call is made since the payload contains a timestamp.

When the Distributed Tracer is enabled, InsertDistributedTraceHeaders will always insert W3C trace context headers. It also by default inserts the New Relic distributed tracing header, but can be configured based on the Config.DistributedTracer.ExcludeNewRelicHeader option.

StartExternalSegment calls InsertDistributedTraceHeaders, so you don't need to use it for outbound HTTP calls: Just use StartExternalSegment!

func (*Transaction) IsSampled

func (txn *Transaction) IsSampled() bool

IsSampled indicates if the Transaction is sampled. A sampled Transaction records a span event for each segment. Distributed tracing must be enabled for transactions to be sampled. False is returned if the Transaction has finished.

func (*Transaction) NewGoroutine

func (txn *Transaction) NewGoroutine() *Transaction

NewGoroutine allows you to use the Transaction in multiple goroutines.

Each goroutine must have its own Transaction reference returned by NewGoroutine. You must call NewGoroutine to get a new Transaction reference every time you wish to pass the Transaction to another goroutine. It does not matter if you call this before or after the other goroutine has started.

All Transaction methods can be used in any Transaction reference. The Transaction will end when End() is called in any goroutine. Note that any segments that end after the transaction ends will not be reported.

Example

Passing a new Transaction reference directly to another goroutine.

package main

import (
	"time"

	"github.com/newrelic/go-agent/v3/newrelic"
)

var txn *newrelic.Transaction

func main() {
	go func(txn *newrelic.Transaction) {
		defer txn.StartSegment("async").End()
		// Do some work
		time.Sleep(100 * time.Millisecond)
	}(txn.NewGoroutine())
}
Output:

Example (Channel)

Passing a new Transaction reference on a channel to another goroutine.

package main

import (
	"time"

	"github.com/newrelic/go-agent/v3/newrelic"
)

var txn *newrelic.Transaction

func main() {
	ch := make(chan *newrelic.Transaction)
	go func() {
		txn := <-ch
		defer txn.StartSegment("async").End()
		// Do some work
		time.Sleep(100 * time.Millisecond)
	}()
	ch <- txn.NewGoroutine()
}
Output:

Example (InsideGoroutines)

Sometimes it is not possible to call txn.NewGoroutine() before the goroutine has started. In this case, it is okay to call the method from inside the newly started goroutine.

package main

import (
	"context"
	"time"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	// async will always be called using `go async(ctx)`
	async := func(ctx context.Context) {
		txn := newrelic.FromContext(ctx)
		txn = txn.NewGoroutine()
		defer txn.StartSegment("async").End()

		// Do some work
		time.Sleep(100 * time.Millisecond)
	}
	ctx := newrelic.NewContext(context.Background(), currentTransaction())
	go async(ctx)
}
Output:

func (*Transaction) NoticeError

func (txn *Transaction) NoticeError(err error)

NoticeError records an error. The Transaction saves the first five errors. For more control over the recorded error fields, see the newrelic.Error type.

In certain situations, using this method may result in an error being recorded twice. Errors are automatically recorded when Transaction.WriteHeader receives a status code at or above 400 or strictly below 100 that is not in the IgnoreStatusCodes configuration list. This method is unaffected by the IgnoreStatusCodes configuration list.

NoticeError examines whether the error implements the following optional methods:

// StackTrace records a stack trace
StackTrace() []uintptr

// ErrorClass sets the error's class
ErrorClass() string

// ErrorAttributes sets the errors attributes
ErrorAttributes() map[string]interface{}

The newrelic.Error type, which implements these methods, is the recommended way to directly control the recorded error's message, class, stacktrace, and attributes.

func (*Transaction) SetName

func (txn *Transaction) SetName(name string)

SetName names the transaction. Use a limited set of unique names to ensure that Transactions are grouped usefully.

func (*Transaction) SetWebRequest

func (txn *Transaction) SetWebRequest(r WebRequest)

SetWebRequest marks the transaction as a web transaction. SetWebRequest additionally collects details on request attributes, url, and method if these fields are set. If headers are present, the agent will look for distributed tracing headers using Transaction.AcceptDistributedTraceHeaders. Use Transaction.SetWebRequestHTTP if you have a *http.Request.

Example
package main

import (
	"net/http"
	"net/url"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func getApp() *newrelic.Application {
	return nil
}

func main() {
	app := getApp()
	txn := app.StartTransaction("My-Transaction")
	txn.SetWebRequest(newrelic.WebRequest{
		Header:    http.Header{},
		URL:       &url.URL{Path: "path"},
		Method:    "GET",
		Transport: newrelic.TransportHTTP,
	})
}
Output:

func (*Transaction) SetWebRequestHTTP

func (txn *Transaction) SetWebRequestHTTP(r *http.Request)

SetWebRequestHTTP marks the transaction as a web transaction. If the request is non-nil, SetWebRequestHTTP will additionally collect details on request attributes, url, and method. If headers are present, the agent will look for distributed tracing headers using Transaction.AcceptDistributedTraceHeaders.

Example
package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func getApp() *newrelic.Application {
	return nil
}

func main() {
	app := getApp()
	inboundRequest, _ := http.NewRequest("GET", "http://example.com", nil)
	txn := app.StartTransaction("My-Transaction")
	// Mark transaction as a web transaction, record attributes based on the
	// inbound request, and read any available distributed tracing headers.
	txn.SetWebRequestHTTP(inboundRequest)
}
Output:

Example (Nil)

Sometimes there is no inbound request, but you may still wish to set a Transaction as a web request. Passing nil to Transaction.SetWebRequestHTTP allows you to do just this.

package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func getApp() *newrelic.Application {
	return nil
}

func main() {
	app := getApp()
	txn := app.StartTransaction("My-Transaction")
	// Mark transaction as a web transaction, but do not record attributes
	// based on an inbound request or read distributed tracing headers.
	txn.SetWebRequestHTTP(nil)
}
Output:

func (*Transaction) SetWebResponse

func (txn *Transaction) SetWebResponse(w http.ResponseWriter) http.ResponseWriter

SetWebResponse allows the Transaction to instrument response code and response headers. Use the return value of this method in place of the input parameter http.ResponseWriter in your instrumentation.

The returned http.ResponseWriter is safe to use even if the Transaction receiver is nil or has already been ended.

The returned http.ResponseWriter implements the combination of http.CloseNotifier, http.Flusher, http.Hijacker, and io.ReaderFrom implemented by the input http.ResponseWriter.

This method is used by WrapHandle, WrapHandleFunc, and most integration package middlewares. Therefore, you probably want to use this only if you are writing your own instrumentation middleware.

Example

This example (modified from the WrapHandle instrumentation) demonstrates how you can replace an http.ResponseWriter in order to capture response headers and notice errors based on status code.

Note that this is just an example and that WrapHandle and WrapHandleFunc perform this instrumentation for you.

package main

import (
	"net/http"

	"github.com/newrelic/go-agent/v3/newrelic"
)

func getApp() *newrelic.Application {
	return nil
}

func main() {
	app := getApp()
	handler := http.FileServer(http.Dir("/tmp"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Begin a Transaction.
		txn := app.StartTransaction("index")
		defer txn.End()

		// Set the transaction as a web request, gather attributes based on the
		// request, and read incoming distributed trace headers.
		txn.SetWebRequestHTTP(r)

		// Prepare to capture attributes, errors, and headers from the
		// response.
		w = txn.SetWebResponse(w)

		// Add the Transaction to the http.Request's Context.
		r = newrelic.RequestWithTransactionContext(r, txn)

		// The http.ResponseWriter passed to ServeHTTP has been replaced with
		// the new instrumented http.ResponseWriter.
		handler.ServeHTTP(w, r)
	})
}
Output:

func (*Transaction) StartSegment

func (txn *Transaction) StartSegment(name string) *Segment

StartSegment makes it easy to instrument segments. To time a function, do the following:

func timeMe(txn newrelic.Transaction) {
	defer txn.StartSegment("timeMe").End()
	// ... function code here ...
}

To time a block of code, do the following:

segment := txn.StartSegment("myBlock")
// ... code you want to time here ...
segment.End()

func (*Transaction) StartSegmentNow

func (txn *Transaction) StartSegmentNow() SegmentStartTime

StartSegmentNow starts timing a segment. The SegmentStartTime returned can be used as the StartTime field in Segment, DatastoreSegment, or ExternalSegment. The returned SegmentStartTime is safe to use even when the Transaction receiver is nil. In this case, the segment will have no effect.

Example
package main

import (
	"github.com/newrelic/go-agent/v3/newrelic"
)

func currentTransaction() *newrelic.Transaction {
	return nil
}

func main() {
	txn := currentTransaction()
	seg := &newrelic.MessageProducerSegment{
		// The value returned from Transaction.StartSegmentNow is used for the
		// StartTime field on any segment.
		StartTime:       txn.StartSegmentNow(),
		Library:         "RabbitMQ",
		DestinationType: newrelic.MessageExchange,
		DestinationName: "myExchange",
	}
	// add message to queue here
	seg.End()
}
Output:

type TransportType

type TransportType string

TransportType is used in Transaction.AcceptDistributedTraceHeaders to represent the type of connection that the trace payload was transported over.

const (
	TransportUnknown TransportType = "Unknown"
	TransportHTTP    TransportType = "HTTP"
	TransportHTTPS   TransportType = "HTTPS"
	TransportKafka   TransportType = "Kafka"
	TransportJMS     TransportType = "JMS"
	TransportIronMQ  TransportType = "IronMQ"
	TransportAMQP    TransportType = "AMQP"
	TransportQueue   TransportType = "Queue"
	TransportOther   TransportType = "Other"
)

TransportType names used across New Relic agents:

type WebRequest

type WebRequest struct {
	// Header may be nil if you don't have any headers or don't want to
	// transform them to http.Header format.
	Header http.Header
	// URL may be nil if you don't have a URL or don't want to transform
	// it to *url.URL.
	URL *url.URL
	// Method is the request's method.
	Method string
	// If a distributed tracing header is found in the WebRequest.Header,
	// this TransportType will be used in the distributed tracing metrics.
	Transport TransportType
	// This is the value of the `Host` header. Go does not add it to the
	// http.Header object and so must be passed separately.
	Host string
}

WebRequest is used to provide request information to Transaction.SetWebRequest.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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