newrelic

package
v3.32.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0, Apache-2.0 Imports: 45 Imported by: 651

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.ConfigCodeLevelMetricsEnabled(false),
		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"
	// AttributeCodeFunction contains the Code Level Metrics function name.
	AttributeCodeFunction = "code.function"
	// AttributeCodeNamespace contains the Code Level Metrics namespace name.
	AttributeCodeNamespace = "code.namespace"
	// AttributeCodeFilepath contains the Code Level Metrics source file path name.
	AttributeCodeFilepath = "code.filepath"
	// AttributeCodeLineno contains the Code Level Metrics source file line number name.
	AttributeCodeLineno = "code.lineno"
	// AttributeErrorGroupName contains the error group name set by the user defined callback function.
	AttributeErrorGroupName = "error.group.name"
	// AttributeUserID tracks the user a transaction and its child events are impacting
	AttributeUserID = "enduser.id"
	// AttributeLLM tracks LLM transactions
	AttributeLLM = "llm"
)

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"
	// The headers of the message without CAT keys/values
	AttributeMessageHeaders = "message.headers"
)

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 (
	// MaxLogLength is the maximum number of bytes the log message is allowed to be
	MaxLogLength = 32768
)
View Source
const (
	// The error class for panics
	PanicErrorClass = panicErrorKlass
)
View Source
const (
	// Version is the full string version of this Go Agent.
	Version = "3.32.0"
)

Variables

View Source
var (
	// ErrNilLogBuffer is a type of error that occurs when the New Relic log decorator is passed a nil object when it was
	// expecting a valid, non nil pointer to a log bytes.Buffer object.
	ErrNilLogBuffer = fmt.Errorf("%s: the EnrichLog() function must not be passed a nil byte buffer", logDecorationErrorHeader)

	// ErrNoApplication is a type of error that occurs when the New Relic log decorator is passed a nil New Relic Application
	// when it was expecting a valid, non nil pointer to a New Relic application.
	ErrNoApplication = fmt.Errorf("%s: a non nil application or transaction must be provided to enrich a log", logDecorationErrorHeader)
)

Functions

func DistributedTraceHeadersFromJSON added in v3.14.0

func DistributedTraceHeadersFromJSON(jsondata string) (hdrs http.Header, err error)

DistributedTraceHeadersFromJSON takes a set of distributed trace headers as a JSON-encoded string and emits a http.Header value suitable for passing on to the txn.AcceptDistributedTraceHeaders() function.

This is a convenience function provided for cases where you receive the trace header data already as a JSON string and want to avoid manually converting that to an http.Header. It helps facilitate handling of headers passed to your Go application from components written in other languages which may natively handle these header values as JSON strings.

For example, given the input string

`{"traceparent": "frob", "tracestate": "blorfl", "newrelic": "xyzzy"}`

This will emit an http.Header value with headers "traceparent", "tracestate", and "newrelic". Specifically:

http.Header{
  "Traceparent": {"frob"},
  "Tracestate": {"blorfl"},
  "Newrelic": {"xyzzy"},
}

The JSON string must be a single object whose values may be strings or arrays of strings. These are translated directly to http headers with singleton or multiple values. In the case of multiple string values, these are translated to a multi-value HTTP header. For example:

`{"traceparent": "12345", "colors": ["red", "green", "blue"]}`

which produces

http.Header{
  "Traceparent": {"12345"},
  "Colors": {"red", "green", "blue"},
}

(Note that the HTTP headers are capitalized.)

func EnrichLog added in v3.18.0

func EnrichLog(buf *bytes.Buffer, opts EnricherOption) error

EnrichLog appends newrelic linking metadata to a log stored in a byte buffer. This should only be used by plugins built for frameworks.

func GetSecurityAgentInterface added in v3.23.0

func GetSecurityAgentInterface() securityAgent

GetSecurityAgentInterface returns the securityAgent value which provides the working interface to the installed security agent (or to a no-op interface if none were installed).

Packages which need to make calls to secureAgent's methods may obtain the secureAgent value by calling this function. This avoids exposing the variable itself, so it's not writable externally and also sets up for the future if this ends up not being a global variable later.

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 IsSecurityAgentPresent added in v3.23.0

func IsSecurityAgentPresent() bool

IsSecurityAgentPresent returns true if there's an actual security agent hooked in to the Go APM agent, whether or not it's enabled or operating in any particular mode. It returns false only if the hook-in interface for those functions is a No-Op will null functionality.

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", "https://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, options ...TraceOption) (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.

WrapHandle accepts zero or more TraceOption functions to allow additional options to be manually added to the transaction trace generated, in the same fashion as StartTransaction does. For example, this can be used to control code level metrics generated for this transaction.

func WrapHandleFunc

func WrapHandleFunc(app *Application, pattern string, handler func(http.ResponseWriter, *http.Request), options ...TraceOption) (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.

WrapHandleFunc accepts zero or more TraceOption functions to allow additional options to be manually added to the transaction trace generated, in the same fashion as StartTransaction does. For example, this can be used to control code level metrics generated for this transaction.

func WrapListen added in v3.23.0

func WrapListen(endpoint string) string

WrapListen wraps an HTTP endpoint reference passed to functions like http.ListenAndServe, which causes security scanning to be done for that incoming endpoint when vulnerability scanning is enabled. It returns the endpoint string, so you can replace a call like

http.ListenAndServe(":8000", nil)

with

http.ListenAndServe(newrelic.WrapListen(":8000"), 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) Config added in v3.23.0

func (app *Application) Config() (Config, bool)

Config returns a copy of the application's configuration data in case that information is needed (but since it is a copy, this function cannot be used to alter the application's configuration).

If the Config data could be copied from the application successfully, a boolean true value is returned as the second return value. If it is false, then the Config data returned is the standard default configuration. This usually occurs if the Application is not yet fully initialized.

func (*Application) HasLLMTokenCountCallback added in v3.31.0

func (app *Application) HasLLMTokenCountCallback() bool

HasLLMTokenCountCallback returns true if there is currently a registered callback function or false otherwise.

func (*Application) InvokeLLMTokenCountCallback added in v3.31.0

func (app *Application) InvokeLLMTokenCountCallback(model, content string) (int, bool)

InvokeLLMTokenCountCallback invokes the function registered previously as the callback function to compute token counts to report for LLM transactions, if any. If there is no current callback funtion, this simply returns a zero count and a false boolean value. Otherwise, it returns the value returned by the callback and a true value.

Although there's no harm in calling this method to invoke your callback function, there is no need (or particular benefit) of doing so. This is called as needed internally by the AI Monitoring integrations.

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) RecordLLMFeedbackEvent added in v3.31.0

func (app *Application) RecordLLMFeedbackEvent(trace_id string, rating any, category string, message string, metadata map[string]interface{})

RecordLLMFeedbackEvent adds a LLM Feedback event. An error is logged if eventType or params is invalid.

func (*Application) RecordLog added in v3.17.0

func (app *Application) RecordLog(logEvent LogData)

RecordLog records the data from a single log line. This consumes a LogData object that should be configured with data taken from a logging framework.

Certian parts of this feature can be turned off based on your config settings. Record log is capable of recording log events, as well as log metrics depending on how your application is configured.

func (*Application) RegisterSecurityAgent added in v3.23.0

func (app *Application) RegisterSecurityAgent(s securityAgent)

func (*Application) SetLLMTokenCountCallback added in v3.31.0

func (app *Application) SetLLMTokenCountCallback(callbackFunction func(string, string) int)

SetLLMTokenCountCallback registers a callback function which will be used by the AI Montoring integration packages in cases where they are unable to determine the token counts directly. You may call SetLLMTokenCountCallback multiple times. If you do, each call registers a new callback function which replaces the previous one. Calling SetLLMTokenCountCallback(nil) removes the callback function entirely.

Your callback function will be passed two string parameters: model name and content. It must return a single integer value which is the number of tokens to report. If it returns a value less than or equal to zero, no token count report will be made (which includes the case where your callback function was unable to determine the token count).

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, opts ...TraceOption) *Transaction

StartTransaction begins a Transaction with the given name.

func (*Application) UpdateSecurityConfig added in v3.29.0

func (app *Application) UpdateSecurityConfig(s interface{})

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.

Note that in most cases, it is not necesary nor recommended to call WaitForConnection() at all, particularly for any but the most trivial, short-lived processes. It is better to simply start the application and allow the instrumentation code to handle its connections on its own, which it will do as needed in the background (and will continue attempting to connect if it wasn't immediately successful, all while allowing your application to proceed with its primary function).

type ApplicationLogging added in v3.17.0

type ApplicationLogging struct {
	// If this is disabled, all sub-features are disabled;
	// if it is enabled, the individual sub-feature configurations take effect.
	// MAY accomplish this by not installing instrumentation, or by early-return/no-op as necessary for an agent.
	Enabled bool
	// Forwarding controls log forwarding to New Relic One
	Forwarding struct {
		// Toggles whether the agent gathers log records for sending to New Relic.
		Enabled bool
		// Number of log records to send per minute to New Relic.
		// Controls the overall memory consumption when using log forwarding.
		// SHOULD be sent as part of the harvest_limits on Connect.
		MaxSamplesStored int
	}
	Metrics struct {
		// Toggles whether the agent gathers the the user facing Logging/lines and Logging/lines/{SEVERITY}
		// Logging Metrics used in the Logs chart on the APM Summary page.
		Enabled bool
	}
	LocalDecorating struct {
		// Toggles whether the agent enriches local logs printed to console so they can be sent to new relic for ingestion
		Enabled bool
	}
}

ApplicationLogging contains settings which control the capture and sending of log event data

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 BodyBuffer added in v3.28.0

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

func (*BodyBuffer) Len added in v3.28.0

func (b *BodyBuffer) Len() int

func (*BodyBuffer) String added in v3.28.0

func (b *BodyBuffer) String() (string, bool)

func (*BodyBuffer) Write added in v3.28.0

func (b *BodyBuffer) Write(p []byte) (int, error)

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 CachedCodeLocation added in v3.18.2

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

CachedCodeLocation provides storage for the code location computed such that the discovery of the code location is only done once; thereafter the cached value is available for use.

This type includes methods with the same names as some of the basic code location reporting functions and TraceOptions. However, when called as methods of a CachedCodeLocation value instead of a stand-alone function, the operation will make use of the cache to prevent computing the same source location more than once.

A usable CachedCodeLocation value must be obtained via a call to NewCachedCodeLocation.

func NewCachedCodeLocation added in v3.18.2

func NewCachedCodeLocation() *CachedCodeLocation

NewCachedCodeLocation returns a pointer to a newly-created CachedCodeLocation value, suitable for use with the methods defined for that type.

func (*CachedCodeLocation) Err added in v3.18.2

func (c *CachedCodeLocation) Err() error

Err returns the error condition encountered when trying to determine the code location being cached, if any.

func (*CachedCodeLocation) FunctionLocation added in v3.18.2

func (c *CachedCodeLocation) FunctionLocation(functions ...interface{}) (*CodeLocation, error)

FunctionLocation works identically to the stand-alone FunctionLocation function, in that it determines the souce code location of the named function, returning a pointer to a CodeLocation value which represents that location, or an error value if it was unable to find a valid code location for the provided value. However, unlike the stand-alone function, this stores the result in the CachedCodeLocation receiver; thus, subsequent invocations of FunctionLocation for the same receiver will result in immediately repeating the value (or error, if applicable) obtained from the first invocation.

This is thread-safe and is intended to allow the same code to run in multiple concurrent goroutines without needlessly recalculating the location of the function value.

func (*CachedCodeLocation) IsValid added in v3.18.2

func (c *CachedCodeLocation) IsValid() bool

IsValid returns true if the cache value was correctly initialized (as by, for example, NewCachedCodeLocation), and therefore can be used to cache code location values. Otherwise it cannot be used.

func (*CachedCodeLocation) ThisCodeLocation added in v3.18.2

func (c *CachedCodeLocation) ThisCodeLocation(skiplevels ...int) *CodeLocation

ThisCodeLocation works identically to the stand-alone ThisCodeLocation function, in that it determines the souce code location from whence it was called, returning a pointer to a CodeLocation value which represents that location. However, unlike the stand-alone function, this stores the result in the CachedCodeLocation receiver; thus, subsequent invocations of ThisCodeLocation for the same receiver will result in immediately repeating the value obtained from the first invocation.

This is thread-safe and is intended to allow the same code to run in multiple concurrent goroutines without needlessly recalculating the location of the caller.

func (*CachedCodeLocation) WithDefaultFunctionLocation added in v3.18.2

func (c *CachedCodeLocation) WithDefaultFunctionLocation(functions ...interface{}) TraceOption

WithDefaultFunctionLocation works like the standalone WithDefaultFunctionLocation function, except that it takes a CachedCodeLocation receiver which will be used to cache the source code location of the function value.

Thus, this will arrange for the given function to be reported in Code Level Metrics only if no other option that came before it gave an explicit location to use instead, but will also cache that answer in the provided CachedCodeLocation receiver variable, so that if called again with the same CachedCodeLocation variable, it will avoid the overhead of finding the function's location again, using instead the cached answer.

This is thread-safe and is intended to allow the same code to run in multiple concurrent goroutines without needlessly recalculating the location of the function value.

If an error is encountered when trying to evaluate the source code location of the provided function value, WithCachedDefaultFunctionLocation will not set anything for the reported code location, and the error will be available as a non-nil value in the Err member of the CachedCodeLocation variable. In this case, no additional attempts are guaranteed to be made on subsequent executions to determine the code location.

func (*CachedCodeLocation) WithFunctionLocation added in v3.18.2

func (c *CachedCodeLocation) WithFunctionLocation(functions ...interface{}) TraceOption

WithFunctionLocation works like the standalone function WithFunctionLocation, but it stores a copy of the function's location in its receiver the first time it is used. Subsequently that cached value will be used instead of computing the source code location every time.

This is thread-safe and is intended to allow the same code to run in multiple concurrent goroutines without needlessly recalculating the location of the function value.

func (*CachedCodeLocation) WithThisCodeLocation added in v3.18.2

func (c *CachedCodeLocation) WithThisCodeLocation() TraceOption

WithThisCodeLocation is equivalent to the standalone WithThisCodeLocation TraceOption, but uses the cached value in its receiver to ensure that the overhead of computing the code location is only performed the first time it is invoked for each instance of the receiver variable.

type CodeLevelMetricsScope added in v3.18.0

type CodeLevelMetricsScope uint32

CodeLevelMetricsScope is a bit-encoded value. Each such value describes a trace type for which code-level metrics are to be collected and reported.

const (
	TransactionCLM CodeLevelMetricsScope = 1 << iota
	AllCLM         CodeLevelMetricsScope = 0
)

These constants specify the types of telemetry data to which we will attach code level metric data.

Currently, this includes

TransactionCLM            any kind of transaction
AllCLM                    all kinds of telemetry data for which CLM is implemented (the default)

The zero value of CodeLevelMetricsScope means "all types" as a convenience so that new variables of this type provide the default expected behavior rather than, say, turning off all code level metrics as a 0 bit value would otherwise imply. Otherwise the numeric values of these constants are not to be relied upon and are subject to change. Only use the named constant identifiers in your code. We do not recommend saving the raw numeric value of these constants to use later.

func CodeLevelMetricsScopeLabelListToValue added in v3.18.2

func CodeLevelMetricsScopeLabelListToValue(labels string) (CodeLevelMetricsScope, bool)

CodeLevelMetricsScopeLabelListToValue is a convenience function which is like CodeLevelMetricsScopeLabeltoValue except that it takes a single string which contains comma-separated values instead of an already-broken-out set of individual label strings.

func CodeLevelMetricsScopeLabelToValue added in v3.18.2

func CodeLevelMetricsScopeLabelToValue(labels ...string) (CodeLevelMetricsScope, bool)

CodeLevelMetricsScopeLabelToValue accepts a number of string values representing the possible scope restrictions available for the agent, returning the CodeLevelMetricsScope value which represents the combination of all of the given labels. This value is suitable to be presented to ConfigCodeLevelMetricsScope.

It also returns a boolean flag; if true, it was able to understand all of the provided labels; otherwise, one or more of the values were not recognized and thus the returned CodeLevelMetricsScope value may be incomplete (although it will represent any valid label strings passed, if any).

Currently, this function recognizes the following labels:

for AllCLM: "all" (if this value appears anywhere in the list of strings, AllCLM will be returned)
for TransactionCLM: "transaction", "transactions", "txn"

func (CodeLevelMetricsScope) MarshalText added in v3.18.2

func (s CodeLevelMetricsScope) MarshalText() ([]byte, error)

MarshalText allows for a CodeLevelMetrics value to be encoded into JSON strings and other text encodings.

func (*CodeLevelMetricsScope) UnmarshalText added in v3.18.2

func (s *CodeLevelMetricsScope) UnmarshalText(b []byte) error

UnmarshalText allows for a CodeLevelMetricsScope value to be read from a JSON string (or other text encodings) whose value is a comma-separated list of scope labels.

type CodeLocation added in v3.18.0

type CodeLocation struct {
	// LineNo is the line number within the source file.
	LineNo int
	// Function is the function name (note that this may be auto-generated by Go
	// for function literals and the like). This is the fully-qualified name, which
	// includes the package name and other information to unambiguously identify
	// the function.
	Function string
	// FilePath is the absolute pathname on disk of the source file referred to.
	FilePath string
}

CodeLocation marks the location of a line of source code for later reference.

func FunctionLocation added in v3.18.0

func FunctionLocation(functions ...interface{}) (*CodeLocation, error)

FunctionLocation is like ThisCodeLocation, but takes as its parameter a function value. It will report the code-level metrics information for that function if that is possible to do. It returns an error if it was not possible to get a code location from the parameter passed to it.

If multiple functions are passed, each will be attempted until one is found for which we can successfully find a code location.

func ThisCodeLocation added in v3.18.0

func ThisCodeLocation(skipLevels ...int) *CodeLocation

ThisCodeLocation returns a CodeLocation value referring to the place in your code that it was invoked.

With no arguments (or if passed a 0 value), it returns the location of its own caller. However, you may adjust this by passing the number of function calls to skip. For example, ThisCodeLocation(1) will return the CodeLocation of the place the current function was called from (i.e., the caller of the caller of ThisCodeLocation).

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
		// MaxSamplesStored sets the desired maximum custom event samples stored
		MaxSamplesStored int
	}

	// 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
		// ExpectStatusCodes controls which http response codes should
		// impact your error metrics, apdex score and alerts. Expected errors will
		// be silently captured without impacting any of those. Note that setting an error
		// code as Ignored will prevent it from being collected, even if its expected.
		ExpectStatusCodes []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
		// ErrorGroupCallback is a user defined callback function that takes an error as an input
		// and returns a string that will be applied to an error to put it in an error group.
		//
		// If no error group is identified for a given error, this function should return an empty string.
		// If an ErrorGroupCallbeck is defined, it will be executed against every error the go agent notices that
		// is not ignored.
		//
		// example function:
		//
		// func ErrorGroupCallback(errorInfo newrelic.ErrorInfo) string {
		//		if errorInfo.Class == "403" && errorInfo.GetUserId() == "example user" {
		//			return "customer X payment issue"
		// 		}
		//
		//		// returning empty string causes default error grouping behavior
		//		return ""
		// }
		ErrorGroupCallback `json:"-"`
	}

	// 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
	}

	// AIMonitoring controls the behavior of AI monitoring features.
	AIMonitoring struct {
		Enabled bool
		// Indicates whether streams will be instrumented
		Streaming struct {
			Enabled bool
		}
		RecordContent struct {
			Enabled bool
		}
	}
	// 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
		// ReservoirLimit sets the desired maximum span event reservoir limit
		// for collecting span event data. The collector MAY override this value.
		ReservoirLimit int
	}

	// 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
		}
		RawQuery 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
		}
	}

	// Config Settings for Logs in Context features
	ApplicationLogging ApplicationLogging

	// 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

	// CodeLevelMetrics contains fields which control the collection and reporting
	// of source code context information associated with telemetry data.
	CodeLevelMetrics struct {
		// Enabling CodeLevelMetrics will include source code context information
		// as attributes. If this is disabled, no such metrics will be collected
		// or reported.
		Enabled bool
		// RedactPathPrefixes, if true, will redact a non-nil list of PathPrefixes
		// from the configuration data transmitted by the agent.
		RedactPathPrefixes bool
		// RedactIgnoredPrefixes, if true, will redact a non-nil list of IgnoredPrefixes
		// from the configuration data transmitted by the agent.
		RedactIgnoredPrefixes bool
		// Scope is a combination of CodeLevelMetricsScope values OR-ed together
		// to indicate which specific kinds of events will carry CodeLevelMetrics
		// data. This allows the agent to spend resources on discovering the source
		// code context data only where actually needed.
		Scope CodeLevelMetricsScope
		// PathPrefixes specifies a slice of filename patterns that describe the start of
		// the project area. Any text before any of these patterns is ignored. Thus, if
		// PathPrefixes is set to ["myproject/src", "otherproject/src"], then a function located in a file
		// called "/usr/local/src/myproject/src/foo.go" will be reported with the
		// pathname "myproject/src/foo.go". If this value is nil, the full path
		// will be reported (e.g., "/usr/local/src/myproject/src/foo.go").
		// The first string in the slice which is found in a file pathname will be the one
		// used to truncate that filename; if none of the strings in PathPrefixes are found
		// anywhere in a file's pathname, the full path will be reported.
		PathPrefixes []string
		// PathPrefix specifies the filename pattern that describes the start of
		// the project area. Any text before this pattern is ignored. Thus, if
		// PathPrefix is set to "myproject/src", then a function located in a file
		// called "/usr/local/src/myproject/src/foo.go" will be reported with the
		// pathname "myproject/src/foo.go". If this value is empty, the full path
		// will be reported (e.g., "/usr/local/src/myproject/src/foo.go").
		//
		// Deprecated: new code should use PathPrefixes instead (or better yet,
		// use the ConfigCodeLevelMetricsPathPrefix option, which accepts any number
		// of string parameters for backwards compatibility).
		PathPrefix string
		// IgnoredPrefix holds a single module path prefix to ignore when searching
		// to find the calling function to be reported.
		//
		// Deprecated: new code should use IgnoredPrefixes instead (or better yet,
		// use the ConfigCodeLevelMetricsIgnoredPrefix option, which accepts any number
		// of string parameters for backwards compatibility).
		IgnoredPrefix string
		// IgnoredPrefixes specifies a slice of initial patterns to look for in fully-qualified
		// function names to determine which functions to ignore while searching up
		// through the call stack to find the application function to associate
		// with telemetry data. The agent will look for the innermost caller whose name
		// does not begin with one of these prefixes. If empty, it will ignore functions whose
		// names look like they are internal to the agent itself.
		IgnoredPrefixes []string
	}

	// ModuleDependencyMetrics controls reporting of the packages used to build the instrumented
	// application, to help manage project dependencies.
	ModuleDependencyMetrics struct {
		// Enabled controls whether the module dependencies are collected and reported.
		Enabled bool
		// RedactIgnoredPrefixes, if true, redacts a non-nil list of IgnoredPrefixes from
		// the configuration data transmitted by the agent.
		RedactIgnoredPrefixes bool
		// IgnoredPrefixes is a list of module path prefixes. Any module whose import pathname
		// begins with one of these prefixes is excluded from the dependency reporting.
		// This list of ignored prefixes itself is not reported outside the agent.
		IgnoredPrefixes []string
	}
	// Security is used to post security configuration on UI.
	Security interface{} `json:"Security,omitempty"`
}

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 ConfigAIMonitoringEnabled added in v3.31.0

func ConfigAIMonitoringEnabled(enabled bool) ConfigOption

ConfigAIMonitoringEnabled enables or disables the collection of AI Monitoring event data.

func ConfigAIMonitoringRecordContentEnabled added in v3.31.0

func ConfigAIMonitoringRecordContentEnabled(enabled bool) ConfigOption

ConfigAIMonitoringRecordContentEnabled enables or disables the collection of the prompt and response data along with other AI event metadata.

func ConfigAIMonitoringStreamingEnabled added in v3.31.0

func ConfigAIMonitoringStreamingEnabled(enabled bool) ConfigOption

ConfigAIMonitoringStreamingEnabled turns on or off the collection of AI Monitoring streaming mode metrics.

func ConfigAppLogDecoratingEnabled added in v3.18.0

func ConfigAppLogDecoratingEnabled(enabled bool) ConfigOption

ConfigAppLogDecoratingEnabled enables or disables the local decoration of logs when using one of our logs in context plugins Defaults: enabled=false

func ConfigAppLogEnabled added in v3.17.0

func ConfigAppLogEnabled(enabled bool) ConfigOption

ConfigAppLogEnabled enables or disables all application logging features and data collection

func ConfigAppLogForwardingEnabled added in v3.17.0

func ConfigAppLogForwardingEnabled(enabled bool) ConfigOption

ConfigAppLogForwardingEnabled enables or disables the collection of logs from a user's application by the agent Defaults: enabled=false

func ConfigAppLogForwardingMaxSamplesStored added in v3.17.0

func ConfigAppLogForwardingMaxSamplesStored(maxSamplesStored int) ConfigOption

ConfigAppLogForwardingMaxSamplesStored allows users to set the maximium number of log events the agent is allowed to collect and store in a given harvest cycle.

func ConfigAppLogMetricsEnabled added in v3.17.0

func ConfigAppLogMetricsEnabled(enabled bool) ConfigOption

ConfigAppLogMetricsEnabled enables or disables the collection of metrics data for logs seen by an instrumented logging framework default: true

func ConfigAppName

func ConfigAppName(appName string) ConfigOption

ConfigAppName sets the application name.

func ConfigCodeLevelMetricsEnabled added in v3.18.0

func ConfigCodeLevelMetricsEnabled(enabled bool) ConfigOption

ConfigCodeLevelMetricsEnabled turns on or off the collection of code level metrics entirely.

func ConfigCodeLevelMetricsIgnoredPrefix deprecated added in v3.18.0

func ConfigCodeLevelMetricsIgnoredPrefix(prefix ...string) ConfigOption

ConfigCodeLevelMetricsIgnoredPrefix alters the way the Code Level Metrics collection code searches for the right function to report for a given telemetry trace. It will find the innermost function whose name does NOT begin with any of the strings given here. By default (or if no paramters are given), it will ignore functions whose names imply that the function is part of the agent itself.

In agent version 3.18.0 (only), this took a single string parameter. It now takes a variable number of parameters, preserving the old call semantics for backward compatibility while allowing for multiple IgnoredPrefix values now.

Deprecated: New code should use ConfigCodeLevelmetricsIgnoredPrefixes instead, so the naming of this function is consistent with other related identifiers and the fact that multiple such prefixes are now used.

func ConfigCodeLevelMetricsIgnoredPrefixes added in v3.20.0

func ConfigCodeLevelMetricsIgnoredPrefixes(prefix ...string) ConfigOption

ConfigCodeLevelMetricsIgnoredPrefixes alters the way the Code Level Metrics collection code searches for the right function to report for a given telemetry trace. It will find the innermost function whose name does NOT begin with any of the strings given here. By default (or if no paramters are given), it will ignore functions whose names imply that the function is part of the agent itself.

func ConfigCodeLevelMetricsPathPrefix deprecated added in v3.18.0

func ConfigCodeLevelMetricsPathPrefix(prefix ...string) ConfigOption

ConfigCodeLevelMetricsPathPrefix specifies the filename pattern(s) that describe(s) the start of the project area(s). When reporting a source filename for Code Level Metrics, and any of the values in the path prefix list are found in the source filename, anything before that prefix is discarded from the file pathname. This will be based on the first value in the prefix list that is found in the pathname.

For example, if the path prefix list is set to ["myproject/src", "myproject/extra"], then a function located in a file called "/usr/local/src/myproject/src/foo.go" will be reported with the pathname "myproject/src/foo.go". If this value is empty or none of the prefix strings are found in a file's pathname, the full path will be reported (e.g., "/usr/local/src/myproject/src/foo.go").

In agent versions 3.18.0 and 3.18.1, this took a single string parameter. It now takes a variable number of parameters, preserving the old call semantics for backward compatibility while allowing for multiple PathPrefix values now.

Deprecated: New code should use ConfigCodeLevelMetricsPathPrefixes instead, so the naming of this function is consistent with other related identifiers and the fact that multiple such prefixes are now used.

func ConfigCodeLevelMetricsPathPrefixes added in v3.20.0

func ConfigCodeLevelMetricsPathPrefixes(prefix ...string) ConfigOption

ConfigCodeLevelMetricsPathPrefixes specifies the filename pattern(s) that describe(s) the start of the project area(s). When reporting a source filename for Code Level Metrics, and any of the values in the path prefix list are found in the source filename, anything before that prefix is discarded from the file pathname. This will be based on the first value in the prefix list that is found in the pathname.

For example, if the path prefix list is set to ["myproject/src", "myproject/extra"], then a function located in a file called "/usr/local/src/myproject/src/foo.go" will be reported with the pathname "myproject/src/foo.go". If this value is empty or none of the prefix strings are found in a file's pathname, the full path will be reported (e.g., "/usr/local/src/myproject/src/foo.go").

func ConfigCodeLevelMetricsRedactIgnoredPrefixes added in v3.20.0

func ConfigCodeLevelMetricsRedactIgnoredPrefixes(enabled bool) ConfigOption

ConfigCodeLevelMetricsRedactIgnoredPrefixes controls whether the names of ignored modules should be redacted from the agent configuration data reported and visible in the New Relic UI. Since one of the reasons these modules may be excluded is to preserve confidentiality of module or directory names, the default behavior (if this option is set to true) is to redact those names from the configuration data so that the only thing reported is that some list of unnamed modules were excluded from reporting. If this is set to false, then the names of the ignored modules will be listed in the configuration data, although those modules will still be ignored by Code Level Metrics.

func ConfigCodeLevelMetricsRedactPathPrefixes added in v3.20.0

func ConfigCodeLevelMetricsRedactPathPrefixes(enabled bool) ConfigOption

ConfigCodeLevelMetricsRedactPathPrefixes controls whether the names of source code parent directories should be redacted from the agent configuration data reported and visible in the New Relic UI. Since one of the reasons these path prefixes may be excluded is to preserve confidentiality of directory names, the default behavior (if this option is set to true) is to redact those names from the configuration data so that the only thing reported is that some list of unnamed path prefixes were removed from reported pathnames. If this is set to false, then the names of the removed path prefixes will be listed in the configuration data, although those strings will still be removed from pathnames reported by Code Level Metrics.

func ConfigCodeLevelMetricsScope added in v3.18.0

func ConfigCodeLevelMetricsScope(scope CodeLevelMetricsScope) ConfigOption

ConfigCodeLevelMetricsScope narrows the scope of where code level metrics are to be used. By default, if CodeLevelMetrics are enabled, they apply everywhere the agent currently supports them. To narrow this, supply a list of one or more CodeLevelMetricsScope values ORed together to ConfigCodeLevelMetricsScope.

Note that a zero value CodeLevelMetricsScope means to collect all supported telemetry data types. If you want to stop collecting any code level metrics, then disable collection via ConfigCodeLevelMetricsEnabled.

func ConfigCustomInsightsEventsEnabled added in v3.20.0

func ConfigCustomInsightsEventsEnabled(enabled bool) ConfigOption

ConfigCustomInsightsEventsEnabled enables or disables the collection of custom insight events.

func ConfigCustomInsightsEventsMaxSamplesStored added in v3.17.0

func ConfigCustomInsightsEventsMaxSamplesStored(limit int) ConfigOption

ConfigCustomInsightsEventsMaxSamplesStored alters the sample size allowing control of how many custom events are stored in an agent for a given harvest cycle. Alters the CustomInsightsEvents.MaxSamplesStored setting. Note: As of Jul 2022, the absolute maximum events that can be sent each minute is 100000.

func ConfigDatastoreRawQuery added in v3.23.1

func ConfigDatastoreRawQuery(enabled bool) ConfigOption

ConfigDatastoreRawQuery replaces a parameterized query in datastores with the full raw query

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 ConfigDistributedTracerReservoirLimit added in v3.16.0

func ConfigDistributedTracerReservoirLimit(limit int) ConfigOption

ConfigDistributedTracerReservoirLimit alters the sample reservoir size (maximum number of span events to be collected) for distributed tracing instead of using the built-in default. Alters the DistributedTracer.ReservoirLimit 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_MODULE_DEPENDENCY_METRICS_ENABLED          		sets ModuleDependencyMetrics.Enabled
	NEW_RELIC_MODULE_DEPENDENCY_METRICS_IGNORED_PREFIXES 		sets ModuleDependencyMetrics.IgnoredPrefixes
	NEW_RELIC_MODULE_DEPENDENCY_METRICS_REDACT_IGNORED_PREFIXES sets ModuleDependencyMetrics.RedactIgnoredPrefixes to a boolean value
	NEW_RELIC_CODE_LEVEL_METRICS_ENABLED              			sets CodeLevelMetrics.Enabled
	NEW_RELIC_CODE_LEVEL_METRICS_SCOPE                			sets CodeLevelMetrics.Scope using a comma-separated list, e.g. "transaction"
	NEW_RELIC_CODE_LEVEL_METRICS_PATH_PREFIX          			sets CodeLevelMetrics.PathPrefixes using a comma-separated list
	NEW_RELIC_CODE_LEVEL_METRICS_REDACT_PATH_PREFIXES    		sets CodeLevelMetrics.RedactPathPrefixes to a boolean value
 	NEW_RELIC_CODE_LEVEL_METRICS_REDACT_IGNORED_PREFIXES 		sets CodeLevelMetrics.RedactIgnoredPrefixes to a boolean value
	NEW_RELIC_CODE_LEVEL_METRICS_IGNORED_PREFIX       			sets CodeLevelMetrics.IgnoredPrefixes 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
	NEW_RELIC_APPLICATION_LOGGING_ENABLED						sets ApplicationLogging.Enabled. Set to false to disable all application logging features.
 	NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED  			sets ApplicationLogging.LogForwarding.Enabled. Set to false to disable in agent log forwarding.
 	NEW_RELIC_APPLICATION_LOGGING_METRICS_ENABLED		  		sets ApplicationLogging.Metrics.Enabled. Set to false to disable the collection of application log metrics.
 	NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED      sets ApplicationLogging.LocalDecoration.Enabled. Set to true to enable local log decoration.
	NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED	sets ApplicationLogging.LogForwarding.Limit. Set to 0 to prevent captured logs from being forwarded.
	NEW_RELIC_AI_MONITORING_ENABLED								sets AIMonitoring.Enabled
	NEW_RELIC_AI_MONITORING_STREAMING_ENABLED					sets AIMonitoring.Streaming.Enabled
	NEW_RELIC_AI_MONITORING_RECORD_CONTENT_ENABLED				sets AIMonitoring.RecordContent.Enabled

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.

func ConfigModuleDependencyMetricsEnabled added in v3.20.0

func ConfigModuleDependencyMetricsEnabled(enabled bool) ConfigOption

ConfigModuleDependencyMetricsEnabled controls whether the agent collects and reports the list of modules compiled into the instrumented application.

func ConfigModuleDependencyMetricsIgnoredPrefixes added in v3.20.0

func ConfigModuleDependencyMetricsIgnoredPrefixes(prefix ...string) ConfigOption

ConfigModuleDependencyMetricsIgnoredPrefixes sets the list of module path prefix strings indicating which modules should be excluded from the dependency report.

func ConfigModuleDependencyMetricsRedactIgnoredPrefixes added in v3.20.0

func ConfigModuleDependencyMetricsRedactIgnoredPrefixes(enabled bool) ConfigOption

ConfigModuleDependencyMetricsRedactIgnoredPrefixes controls whether the names of ignored module path prefixes should be redacted from the agent configuration data reported and visible in the New Relic UI. Since one of the reasons these modules may be excluded is to preserve confidentiality of module or directory names, the default behavior (if this option is set to true) is to redact those names from the configuration data so that the only thing reported is that some list of unnamed modules were excluded from reporting. If this is set to false, then the names of the ignored modules will be listed in the configuration data, although those modules will still be ignored by Module Dependency Metrics.

func ConfigSetErrorGroupCallbackFunction added in v3.21.0

func ConfigSetErrorGroupCallbackFunction(callback ErrorGroupCallback) ConfigOption

ConfigSetErrorGroupCallbackFunction set a callback function of type ErrorGroupCallback that will be invoked against errors at harvest time. This function overrides the default grouping behavior of errors into a custom, user defined group when set. Setting this may have performance implications for your application depending on the contents of the callback function. Do not set this if you want the default error grouping behavior to be executed.

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
	// RawQuery stores the original raw query
	RawQuery 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
	// contains filtered or unexported fields
}

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.

func (*DatastoreSegment) GetSecureAgentEvent added in v3.23.0

func (ds *DatastoreSegment) GetSecureAgentEvent() any

GetSecureAgentEvent retrieves the secureAgentEvent previously stored by a SetSecureAgentEvent method.

func (*DatastoreSegment) SetSecureAgentEvent added in v3.23.0

func (ds *DatastoreSegment) SetSecureAgentEvent(event any)

SetSecureAgentEvent allows integration packages to set the secureAgentEvent for this datastore segment. That field is otherwise unexported and not available for other manipulation.

type EnricherOption added in v3.18.0

type EnricherOption func(*logEnricherConfig)

EnricherOption is a function that configures the enricher based on the source of data it receives.

func FromApp added in v3.18.0

func FromApp(app *Application) EnricherOption

FromApp configures the log enricher to build a linking payload from an application.

func FromTxn added in v3.18.0

func FromTxn(txn *Transaction) EnricherOption

FromTxn configures the log enricher to build a linking payload from a transaction.

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 ErrorGroupCallback added in v3.21.0

type ErrorGroupCallback func(ErrorInfo) string

ErrorGroupCallback is a user defined callback function that takes an error as an input and returns a string that will be applied to an error to put it in an error group.

If no error group is identified for a given error, this function should return an empty string.

If an ErrorGroupCallbeck is defined, it will be executed against every error the go agent notices that is not ignored.

type ErrorInfo added in v3.21.0

type ErrorInfo struct {

	// TransactionName is the formatted name of a transaction that is equivilent to how it appears in
	// the New Relic UI. For example, user defined transactions will be named `OtherTransaction/Go/yourTxnName`.
	TransactionName string

	// Error contains the raw error object that the agent collected.
	//
	// Not all errors collected by the system are collected as
	// error objects, like web/http errors and panics.
	// In these cases, Error will be nil, but details will be captured in
	// the Message and Class fields.
	Error error

	// Time Occured is the time.Time when the error was noticed by the go agent
	TimeOccured time.Time

	// Message will always be populated by a string message describing an error
	Message string

	// Class is a string containing the New Relic error class.
	//
	// If an error implements errorClasser, its value will be derived from that.
	// Otherwise, it will be derived from the way the error was
	// collected by the agent. For http errors, this will be the
	// error number. Panics will be the constant value `newrelic.PanicErrorClass`.
	// If no errorClass was defined, this will be reflect.TypeOf() the root
	// error object, which is commonly `*errors.errorString`.
	Class string

	// Expected is true if the error was expected by the go agent
	Expected bool
	// contains filtered or unexported fields
}

ErrorInfo contains info for user defined callbacks that are relevant to an error. All fields are either safe to access copies of internal agent data, or protected from direct access with methods and can not manipulate or distort any agent data.

func (*ErrorInfo) GetErrorAttribute added in v3.21.0

func (e *ErrorInfo) GetErrorAttribute(attribute string) (interface{}, bool)

GetErrorAttribute safely looks up an error attribute by string key. The value of the attribute will be returned as an interface{}, and a bool indicating whether the key was found in the attribute map. If no matching key was found, the return will be (nil, false).

func (*ErrorInfo) GetHttpResponseCode added in v3.21.0

func (e *ErrorInfo) GetHttpResponseCode() string

GetHttpResponseCode will return the HTTP response code that resulted from the web request made in the parent transaction of this error. If no web request occured, then an empty string will be returned.

func (*ErrorInfo) GetRequestMethod added in v3.21.0

func (e *ErrorInfo) GetRequestMethod() string

GetRequestMethod will return the HTTP method used to make a web request if one occured during the parent transaction of this error. If no web request occured, then an empty string will be returned.

func (*ErrorInfo) GetRequestURI added in v3.21.0

func (e *ErrorInfo) GetRequestURI() string

GetRequestURI returns the URI of the http request made during the parent transaction of this error. If no web request occured, this will return an empty string.

func (*ErrorInfo) GetStackTraceFrames added in v3.21.0

func (e *ErrorInfo) GetStackTraceFrames() []StacktraceFrame

GetStackTraceFrames returns a slice of StacktraceFrame objects containing up to 100 lines of stack trace data gathered from the Go runtime. Calling this function may be expensive since it allocates and populates a new slice with stack trace data, and should be called only when needed.

func (*ErrorInfo) GetTransactionUserAttribute added in v3.21.0

func (e *ErrorInfo) GetTransactionUserAttribute(attribute string) (interface{}, bool)

GetTransactionUserAttribute safely looks up a user attribute by string key from the parent transaction of an error. This function will return the attribute vaue as an interface{}, and a bool indicating whether the key was found in the attribute map. If the key was not found, then the return will be (nil, false).

func (*ErrorInfo) GetUserID added in v3.21.0

func (e *ErrorInfo) GetUserID() string

GetUserID will return the User ID set for the parent transaction of this error. It will return empty string if none was set.

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", "https://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", "https://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", "https://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) GetOutboundHeaders added in v3.28.0

func (s *ExternalSegment) GetOutboundHeaders() http.Header

func (*ExternalSegment) GetSecureAgentEvent added in v3.28.0

func (s *ExternalSegment) GetSecureAgentEvent() any

GetSecureAgentEvent retrieves the secureAgentEvent previously stored by a SetSecureAgentEvent method.

func (*ExternalSegment) SetSecureAgentEvent added in v3.28.0

func (s *ExternalSegment) SetSecureAgentEvent(event any)

SetSecureAgentEvent allows integration packages to set the secureAgentEvent for this external segment. That field is otherwise unexported and not available for other manipulation.

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", "https://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 LogData added in v3.17.0

type LogData struct {
	Timestamp int64  // Optional: Unix Millisecond Timestamp; A timestamp will be generated if unset
	Severity  string // Optional: Severity of log being consumed
	Message   string // Optional: Message of log being consumed; Maximum size: 32768 Bytes.
}

LogData contains data fields that are needed to generate log events.

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 StacktraceFrame added in v3.21.0

type StacktraceFrame struct {
	Name string
	File string
	Line int64
}

func (StacktraceFrame) WriteJSON added in v3.21.0

func (f StacktraceFrame) WriteJSON(buf *bytes.Buffer)

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 TraceOption added in v3.18.0

type TraceOption func(*traceOptSet)

TraceOption values provide optional parameters to transactions.

(Currently it's only implemented for transactions, but the name TraceOption is intentionally generic in case we apply these to other kinds of traces in the future.)

func AddCodeLevelMetricsTraceOptions added in v3.28.0

func AddCodeLevelMetricsTraceOptions(app *Application, options []TraceOption, cache *CachedCodeLocation, cachedLocations ...interface{}) []TraceOption

AddCodeLevelMetricsTraceOptions adds trace options to an existing slice of TraceOption objects depending on how code level metrics is configured in your application. Please call cache:=newrelic.NewCachedCodeLocation() before calling this function, and pass the cache to us in order to allow you to optimize the performance and accuracy of this function.

func WithCodeLevelMetrics added in v3.18.2

func WithCodeLevelMetrics() TraceOption

WithCodeLevelMetrics includes this trace in code level metrics even if it would otherwise not be (for example, if it would be out of the configured scope setting). This will never cause code level metrics to be reported if CLM were explicitly disabled (e.g. by CLM being globally off or if WithoutCodeLevelMetrics is present in the options for this trace).

func WithCodeLocation deprecated added in v3.18.0

func WithCodeLocation(loc *CodeLocation) TraceOption

WithCodeLocation adds an explicit CodeLocation value to report for the Code Level Metrics attached to a trace. This is probably a value previously obtained by calling ThisCodeLocation().

Deprecated: This function requires the caller to do the work up-front to calculate the code location, which may be a waste of effort if code level metrics happens to be disabled. Instead, use the WithCodeLocationCallback function.

func WithCodeLocationCallback added in v3.29.0

func WithCodeLocationCallback(locf func() *CodeLocation) TraceOption

WithCodeLocationCallback adds a callback function which the agent will call if it needs to report the code location with an explicit value provided by the caller. This will only be called if code level metrics is enabled, saving unnecessary work if those metrics are not enabled.

If the callback function value passed here is nil, then no callback function will be used (same as if this function were never called). If the callback function itself returns nil instead of a pointer to a CodeLocation, then it is assumed the callback function was not able to determine the code location, and the CLM reporting code's normal method for determining the code location is used instead.

func WithDefaultFunctionLocation added in v3.18.2

func WithDefaultFunctionLocation(functions ...interface{}) TraceOption

WithDefaultFunctionLocation is like WithFunctionLocation but will only evaluate the location of the function if nothing that came before it set a code location first. This is useful, for example, if you want to provide a default code location value to be used but not pay the overhead of resolving that location until it's clear that you will need to. This should appear at the end of a TraceOption list (or at least after any other options that want to specify the code location).

func WithFunctionLocation added in v3.18.0

func WithFunctionLocation(functions ...interface{}) TraceOption

WithFunctionLocation is like WithThisCodeLocation, but uses the function value(s) passed as the location to report. Unlike FunctionLocation, this does not report errors explicitly. If it is unable to use the value passed to find a code location, it will do nothing.

func WithIgnoredPrefix deprecated added in v3.18.0

func WithIgnoredPrefix(prefix ...string) TraceOption

WithIgnoredPrefix indicates that the code location reported for Code Level Metrics should be the first function in the call stack that does not begin with the given string (or any of the given strings if more than one are given). This string is matched against the entire fully-qualified function name, which includes the name of the package the function comes from. By default, the Go Agent tries to take the first function on the call stack that doesn't seem to be internal to the agent itself, but you can control this behavior using this option.

If all functions in the call stack begin with this prefix, the outermost one will be used anyway, since we didn't find anything better on the way to the bottom of the stack.

If no prefix strings are passed here, the configured defaults will be used.

Deprecated: New code should use WithIgnoredPrefixes instead.

func WithIgnoredPrefixes added in v3.20.1

func WithIgnoredPrefixes(prefix ...string) TraceOption

WithIgnoredPrefixes indicates that the code location reported for Code Level Metrics should be the first function in the call stack that does not begin with the given string (or any of the given strings if more than one are given). This string is matched against the entire fully-qualified function name, which includes the name of the package the function comes from. By default, the Go Agent tries to take the first function on the call stack that doesn't seem to be internal to the agent itself, but you can control this behavior using this option.

If all functions in the call stack begin with this prefix, the outermost one will be used anyway, since we didn't find anything better on the way to the bottom of the stack.

If no prefix strings are passed here, the configured defaults will be used.

func WithPathPrefix deprecated added in v3.18.2

func WithPathPrefix(prefix ...string) TraceOption

WithPathPrefix overrides the list of source code path prefixes used to trim source file pathnames, providing a new set of one or more path prefixes to use for this trace only. If no strings are given, the configured defaults will be used.

Deprecated: New code should use WithPathPrefixes instead.

func WithPathPrefixes added in v3.20.1

func WithPathPrefixes(prefix ...string) TraceOption

WithPathPrefixes overrides the list of source code path prefixes used to trim source file pathnames, providing a new set of one or more path prefixes to use for this trace only. If no strings are given, the configured defaults will be used.

func WithThisCodeLocation added in v3.18.0

func WithThisCodeLocation() TraceOption

WithThisCodeLocation is equivalent to calling WithCodeLocation, referring to the point in the code where the WithThisCodeLocation call is being made. This can be helpful, for example, when the actual code invocation which starts a transaction or other kind of trace is originating from a framework or other centralized location, but you want to report this point in your application for the Code Level Metrics associated with this trace.

func WithoutCodeLevelMetrics added in v3.18.0

func WithoutCodeLevelMetrics() TraceOption

WithoutCodeLevelMetrics suppresses the collection and reporting of Code Level Metrics for this trace. This helps avoid the overhead of collecting that information if it's not needed for certain traces.

type Transaction

type Transaction struct {
	Private any
	// 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) AcceptDistributedTraceHeadersFromJSON added in v3.14.0

func (txn *Transaction) AcceptDistributedTraceHeadersFromJSON(t TransportType, jsondata string) error

AcceptDistributedTraceHeadersFromJSON works just like AcceptDistributedTraceHeaders(), except that it takes the header data as a JSON string à la DistributedTraceHeadersFromJSON(). Additionally (unlike AcceptDistributedTraceHeaders()) it returns an error if it was unable to successfully convert the JSON string to http headers. There is no guarantee that the header data found in JSON is correct beyond conforming to the expected types and syntax.

func (*Transaction) AddAttribute

func (txn *Transaction) AddAttribute(key string, value any)

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) ExpectLogEvents added in v3.18.0

func (txn *Transaction) ExpectLogEvents(t internal.Validator, want []internal.WantLog)

ExpectLogEvents from transactions dumps all the log events from a transaction into the test harvest then checks that the contents of the logs harvest matches the list of WantLogs.

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) Name added in v3.24.0

func (txn *Transaction) Name() string

Name returns the name currently set for the transaction, as, e.g. by a call to SetName. If unable to do so (such as due to a nil transaction pointer), the empty string is returned.

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]any

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) NoticeExpectedError added in v3.20.2

func (txn *Transaction) NoticeExpectedError(err error)

NoticeExpectedError records an error that was expected to occur. Errors recoreded with this method will not trigger any error alerts or count towards your error metrics. 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.

NoticeExpectedError 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]any

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) RecordLog added in v3.17.0

func (txn *Transaction) RecordLog(log LogData)

RecordLog records the data from a single log line. This consumes a LogData object that should be configured with data taken from a logging framework.

Certian parts of this feature can be turned off based on your config settings. Record log is capable of recording log events, as well as log metrics depending on how your application is configured.

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) SetOption added in v3.18.0

func (txn *Transaction) SetOption(options ...TraceOption)

SetOption allows the setting of some transaction TraceOption parameters after the transaction has already been started, such as specifying a new source code location for code-level metrics.

The set of options should be the complete set you wish to have in effect, just as if you were calling StartTransaction now with the same set of options.

func (*Transaction) SetUserID added in v3.21.0

func (txn *Transaction) SetUserID(userID string)

SetUserID is used to track the user that a transaction, and all data that is recorded as a subset of that transaction, belong to or interact with. This will propogate an attribute containing this information to all events that are a child of this transaction, like errors and spans.

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", "https://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

	// The following fields are needed for the secure agent's vulnerability
	// detection features.
	Body          *BodyBuffer
	ServerName    string
	Type          string
	RemoteAddress string
}

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

func (WebRequest) GetBody added in v3.23.0

func (webrequest WebRequest) GetBody() []byte

func (WebRequest) GetHeader added in v3.23.0

func (webrequest WebRequest) GetHeader() http.Header

func (WebRequest) GetHost added in v3.23.0

func (webrequest WebRequest) GetHost() string

func (WebRequest) GetMethod added in v3.23.0

func (webrequest WebRequest) GetMethod() string

func (WebRequest) GetRemoteAddress added in v3.23.0

func (webrequest WebRequest) GetRemoteAddress() string

func (WebRequest) GetServerName added in v3.23.0

func (webrequest WebRequest) GetServerName() string

func (WebRequest) GetTransport added in v3.23.0

func (webrequest WebRequest) GetTransport() string

func (WebRequest) GetURL added in v3.23.0

func (webrequest WebRequest) GetURL() *url.URL

func (WebRequest) IsDataTruncated added in v3.28.0

func (webrequest WebRequest) IsDataTruncated() bool

func (WebRequest) Type1 added in v3.23.0

func (webrequest WebRequest) Type1() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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