newrelic

package module
v3.21.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2023 License: Apache-2.0 Imports: 20 Imported by: 0

README

Community Plus header

New Relic Go Agent GoDoc Go Report Card

The New Relic Go Agent allows you to monitor your Go applications with New Relic. It helps you track transactions, outbound requests, database calls, and other parts of your Go application's behavior and provides a running overview of garbage collection, goroutine activity, and memory use.

Go is a compiled language, and doesn’t use a virtual machine. This means that setting up New Relic for your Golang app requires you to use our Go agent API and manually add New Relic methods to your source code. Our API provides exceptional flexibility and control over what gets instrumented.

Installation

Compatibility and Requirements

For the latest version of the agent, Go 1.17+ is required.

Linux, OS X, and Windows (Vista, Server 2008 and later) are supported.

Installing and using the Go agent

To install the agent, follow the instructions in our GETTING_STARTED document or our GUIDE.

We recommend instrumenting your Go code to get the maximum benefits from the New Relic Go agent. But we make it easy to get great data in couple of ways:

  • Even without adding instrumentation, just importing the agent and creating an application will provide useful runtime information about your number of goroutines, garbage collection statistics, and memory and CPU usage.
  • You can use our many INTEGRATION packages for out-of-the box support for many popular Go web frameworks and libraries. We continue to add integration packages based on your feedback. You can weigh in on potential integrations by opening an Issue here in our New Relic Go agent GitHub project.
Upgrading

If you have already been using version 2.X of the agent and are upgrading to version 3.0, see our MIGRATION guide for details.

Getting Started

v3/examples/server/main.go is an example that will appear as "Example App" in your New Relic applications list. To run it:

env NEW_RELIC_LICENSE_KEY=__YOUR_NEW_RELIC_LICENSE_KEY__LICENSE__ \
    go run v3/examples/server/main.go

Some endpoints exposed are http://localhost:8000/ and http://localhost:8000/notice_error

Usage

Integration Packages

The following integration packages extend the base newrelic package to support the following frameworks and libraries. Frameworks and databases which don't have an integration package may still be instrumented using the newrelic package primitives.

Service Frameworks
Project Integration Package
gin-gonic/gin v3/integrations/nrgin Instrument inbound requests through the Gin framework
gorilla/mux v3/integrations/nrgorilla Instrument inbound requests through the Gorilla framework
google.golang.org/grpc v3/integrations/nrgrpc Instrument gRPC servers and clients
labstack/echo v3/integrations/nrecho-v3 Instrument inbound requests through version 3 of the Echo framework
labstack/echo v3/integrations/nrecho-v4 Instrument inbound requests through version 4 of the Echo framework
julienschmidt/httprouter v3/integrations/nrhttprouter Instrument inbound requests through the HttpRouter framework
micro/go-micro v3/integrations/nrmicro Instrument servers, clients, publishers, and subscribers through the Micro framework
Datastores

More information about instrumenting databases without an integration package using newrelic package primitives can be found here.

Project Integration Package
lib/pq v3/integrations/nrpq Instrument PostgreSQL driver (pq driver for database/sql)
jackc/pgx v3/integrations/nrpgx Instrument PostgreSQL driver (pgx driver for database/sql)
jackc/pgx/v5 v3/integrations/nrpgx5 Instrument PostgreSQL driver (pgx/v5 driver for database/sql)
go-mssqldb v3/integrations/nrmssql Instrument MS SQL driver
go-sql-driver/mysql v3/integrations/nrmysql Instrument MySQL driver
elastic/go-elasticsearch v3/integrations/nrelasticsearch-v7 Instrument Elasticsearch datastore calls
database/sql Use a supported database driver or builtin instrumentation Instrument database calls with SQL
jmoiron/sqlx Use a supported database driver or builtin instrumentation Instrument database calls with SQLx
go-redis/redis v3/integrations/nrredis-v7 Instrument Redis 7 calls
go-redis/redis v3/integrations/nrredis-v8 Instrument Redis 8 calls
redis/go-redis v3/integrations/nrredis-v9 Instrument Redis 9 calls
mattn/go-sqlite3 v3/integrations/nrsqlite3 Instrument SQLite driver
snowflakedb/gosnowflake v3/integrations/nrsnowflake Instrument Snowflake driver
mongodb/mongo-go-driver v3/integrations/nrmongo Instrument MongoDB calls
Agent Logging
Project Integration Package
sirupsen/logrus v3/integrations/nrlogrus Send agent log messages to Logrus
mgutz/logxi v3/integrations/nrlogxi Send agent log messages to Logxi
uber-go/zap v3/integrations/nrzap Send agent log messages to Zap
Logs in Context
Project Integration Package
sirupsen/logrus v3/integrations/logcontext-v2/nrlogrus Send data collected from Logrus log messages to New Relic
log v3/integrations/logcontext-v2/logWriter Send data collected from the standard library logger log messages to New Relic
rs/zerolog v3/integrations/logcontext-v2/zerologWriter Send data collected from zerolog log messages to New Relic
AWS
Project Integration Package
aws/aws-sdk-go v3/integrations/nrawssdk-v1 Instrument outbound calls made using Go AWS SDK
aws/aws-sdk-go-v2 v3/integrations/nrawssdk-v2 Instrument outbound calls made using Go AWS SDK v2
aws/aws-lambda-go v3/integrations/nrlambda Instrument AWS Lambda applications
GraphQL
Project Integration Package
graph-gophers/graphql-go v3/integrations/nrgraphgophers Instrument inbound requests using graph-gophers/graphql-go
graphql-go/graphql v3/integrations/nrgraphqlgo Instrument inbound requests using graphql-go/graphql
Misc
Project Integration Package
pkg/errors v3/integrations/nrpkgerrors Wrap pkg/errors errors to improve stack traces and error class information
openzipkin/b3-propagation v3/integrations/nrb3 Add B3 headers to outgoing requests
nats-io/nats.go v3/integrations/nrnats Instrument publishers and subscribers using the NATS client
nats-io/stan.go v3/integrations/nrstan Instrument publishers and subscribers using the NATS streaming client

These integration packages must be imported along with the newrelic package, as shown in this nrgin example.

Alternatives

If you are already using another open source solution to gather telemetry data, you may find it easier to use one of our open source exporters to send this data to New Relic:

Support

Should you need assistance with New Relic products, you are in good hands with several support channels.

If the issue has been confirmed as a bug or is a Feature request, please file a Github issue.

Privacy

At New Relic we take your privacy and the security of your information seriously, and are committed to protecting your information. We must emphasize the importance of not sharing personal data in public forums, and ask all users to scrub logs and diagnostic information for sensitive information, whether personal, proprietary, or otherwise.

We define "Personal Data" as any information relating to an identified or identifiable individual, including, for example, your name, phone number, post code or zip code, Device ID, IP address and email address.

For more information, review New Relic’s General Data Privacy Notice.

Contribute

We encourage your contributions to improve the Go Agent! Keep in mind when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.

If you have any questions, or to execute our corporate CLA, required if your contribution is on behalf of a company, please drop us an email at opensource@newrelic.com.

A note about vulnerabilities

As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.

If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through HackerOne.

If you would like to contribute to this project, please review these guidelines.

To all contributors, we thank you! Without your contribution, this project would not be what it is today. We also host a community project page dedicated to the Go Agent.

License

The New Relic Go agent is licensed under the Apache 2.0 License.

Documentation

Overview

Package newrelic provides instrumentation for Go applications.

Deprecated: This package has been supplanted by version 3 here:

https://godoc.org/github.com/newrelic/go-agent/v3/newrelic

Example
// First create a Config.
cfg := NewConfig("Example Application", "__YOUR_NEW_RELIC_LICENSE_KEY__")

// Modify Config fields to control agent behavior.
cfg.Logger = NewDebugLogger(os.Stdout)

// Now use the Config the create an Application.
app, err := NewApplication(cfg)
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", nil, nil)
	defer txn.End()

	time.Sleep(time.Second)
}()

// WrapHandler and WrapHandleFunc make it easy to instrument inbound web
// requests handled by the http standard library without calling
// StartTransaction.  Popular framework instrumentation packages exist
// in the _integrations directory.
http.HandleFunc(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 := 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 StartSegment(txn, "helperFunction").End()
	}()

	io.WriteString(w, "hello world")
}
http.HandleFunc(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 = "httpResponseCode"
	// AttributeRequestMethod is the request's method.
	AttributeRequestMethod = "request.method"
	// AttributeRequestAccept is the request's "Accept" header.
	AttributeRequestAccept = "request.headers.accept"
	// AttributeRequestContentType is the request's "Content-Type" header.
	AttributeRequestContentType = "request.headers.contentType"
	// AttributeRequestContentLength is the request's "Content-Length" header.
	AttributeRequestContentLength = "request.headers.contentLength"
	// AttributeRequestHost is the request's "Host" header.
	AttributeRequestHost = "request.headers.host"
	// AttributeRequestURI is the request's URL without query parameters,
	// fragment, user, or password.
	AttributeRequestURI = "request.uri"
	// AttributeResponseContentType is the response "Content-Type" header.
	AttributeResponseContentType = "response.headers.contentType"
	// AttributeResponseContentLength is the response "Content-Length" header.
	AttributeResponseContentLength = "response.headers.contentLength"
	// AttributeHostDisplayName contains the value of Config.HostDisplayName.
	AttributeHostDisplayName = "host.displayName"
)

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

View Source
const (
	// AttributeRequestUserAgent is the request's "User-Agent" header.
	AttributeRequestUserAgent = "request.headers.User-Agent"
	// AttributeRequestReferer is the request's "Referer" header.  Query
	// string parameters are removed.
	AttributeRequestReferer = "request.headers.referer"
)

Attributes destined for Errors and Transaction Traces:

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

AWS Lambda specific attributes:

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

Attributes for consumed message transactions:

When a message is consumed (for example from Kafka or RabbitMQ), supported instrumentation packages -- i.e. those found in the _integrations (https://godoc.org/github.com/newrelic/go-agent/_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,
	AttributeMessageExchangeType, AttributeMessageReplyTo,
	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#Transaction) API. In this case, these attributes will be included on all destintations by default.

txn := app.StartTransaction("Message/RabbitMQ/Exchange/Named/MyExchange", nil, nil)
txn.AddAttribute(AttributeMessageRoutingKey, "myRoutingKey")
txn.AddAttribute(AttributeMessageQueueName, "myQueueName")
txn.AddAttribute(AttributeMessageExchangeType, "myExchangeType")
txn.AddAttribute(AttributeMessageReplyTo, "myReplyTo")
txn.AddAttribute(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"
	SpanAttributeAWSRequestID = "aws.requestId"
	SpanAttributeAWSRegion    = "aws.region"
)

Attributes destined for Span Events:

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 (
	// DistributedTracePayloadHeader is the header used by New Relic agents
	// for automatic trace payload instrumentation.
	DistributedTracePayloadHeader = "Newrelic"
)
View Source
const (

	// Version is the full string version of this Go Agent.
	Version = major + "." + minor + "." + patch
)

Variables

View Source
var (
	TransportUnknown = TransportType{/* contains filtered or unexported fields */}
	TransportHTTP    = TransportType{/* contains filtered or unexported fields */}
	TransportHTTPS   = TransportType{/* contains filtered or unexported fields */}
	TransportKafka   = TransportType{/* contains filtered or unexported fields */}
	TransportJMS     = TransportType{/* contains filtered or unexported fields */}
	TransportIronMQ  = TransportType{/* contains filtered or unexported fields */}
	TransportAMQP    = TransportType{/* contains filtered or unexported fields */}
	TransportQueue   = TransportType{/* contains filtered or unexported fields */}
	TransportOther   = TransportType{/* contains filtered or unexported fields */}
)

TransportType names used across New Relic agents:

Functions

func InstrumentSQLConnector

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

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

func NewContext

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

NewContext returns a new Context that carries the provided transaction.

func NewRoundTripper

func NewRoundTripper(txn Transaction, original http.RoundTripper) http.RoundTripper

NewRoundTripper creates an http.RoundTripper to instrument external requests and add distributed tracing headers. The RoundTripper returned creates an external segment before delegating to the original RoundTripper provided (or http.DefaultTransport if none is provided). If the Transaction parameter is nil then the RoundTripper will look for a Transaction in the request's context (using FromContext). Using a nil Transaction is STRONGLY recommended because it allows the same RoundTripper (and client) to be reused for multiple transactions.

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

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

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

client.Do(request)
Output:

func NewStackTrace

func NewStackTrace() []uintptr

NewStackTrace generates a stack trace which can be assigned to the Error struct's Stack field or returned by an error that implements the ErrorClasser interface.

func RequestWithTransactionContext

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

RequestWithTransactionContext adds the transaction to the request's context.

func WrapHandle

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

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

http.Handle("/foo", myHandler)

Perform this replacement:

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

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

func myHandler(rw ResponseWriter, req *Request) {
	if txn := newrelic.FromContext(req.Context()); nil != txn {
		txn.AddAttribute("customerLevel", "gold")
	}
}

This function is safe to call if app is nil.

func WrapHandleFunc

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

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

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

Perform this replacement:

http.HandleFunc(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(WrapHandleFunc(app, "/users", func(w http.ResponseWriter, req *http.Request) {
	if txn := newrelic.FromContext(req.Context()); nil != txn {
		txn.AddAttribute("customerLevel", "gold")
	}
	io.WriteString(w, "users page")
}))

This function is safe to call if app is nil.

Types

type Application

type Application interface {
	// StartTransaction begins a Transaction.
	// * Transaction.NewGoroutine() must be used to pass the Transaction
	//   between goroutines.
	// * This method never returns nil.
	// * The Transaction is considered a web transaction if an http.Request
	//   is provided.
	// * The transaction returned implements the http.ResponseWriter
	//   interface.  Provide your ResponseWriter as a parameter and
	//   then use the Transaction in its place to instrument the response
	//   code and response headers.
	StartTransaction(name string, w http.ResponseWriter, r *http.Request) Transaction

	// 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 returned if event type or params is invalid.
	RecordCustomEvent(eventType string, params map[string]interface{}) error

	// RecordCustomMetric records a custom metric.  The metric name you
	// provide will be prefixed by "Custom/".  Custom metrics are not
	// currently supported in serverless mode.
	//
	// https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-metrics
	RecordCustomMetric(name string, value float64) 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.
	WaitForConnection(timeout time.Duration) error

	// 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.
	Shutdown(timeout time.Duration)
}

Application represents your application.

func NewApplication

func NewApplication(c Config) (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. Applications do not share global state, therefore it is safe to create multiple applications.

type AttributeDestinationConfig

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

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

type BrowserTimingHeader

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

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

Example
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.
	if txn := FromContext(req.Context()); nil != txn {
		hdr, err := txn.BrowserTimingHeader()
		if nil != err {
			log.Printf("unable to create browser timing header: %v", err)
		}
		// 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(WrapHandleFunc(getApp(), "/browser", handler))
http.ListenAndServe(":8000", nil)
Output:

func (*BrowserTimingHeader) WithTags

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

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

func (*BrowserTimingHeader) WithoutTags

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

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

type Config

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

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

	// Logger controls go-agent logging.  For info level logging to stdout:
	//
	//	cfg.Logger = newrelic.NewLogger(os.Stdout)
	//
	// For debug level logging to stdout:
	//
	//	cfg.Logger = newrelic.NewDebugLogger(os.Stdout)
	//
	// See https://github.com/newrelic/go-agent/blob/master/GUIDE.md#logging
	// for more examples and logging integrations.
	Logger Logger

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

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

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

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

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

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

	// ErrorCollector controls the capture of errors.
	ErrorCollector struct {
		// Enabled controls whether errors are captured.  This setting
		// affects both traced errors and error analytics events.
		Enabled bool
		// CaptureEvents controls whether error analytics events are
		// captured.
		CaptureEvents bool
		// IgnoreStatusCodes controls which http response codes are
		// automatically turned into errors.  By default, response codes
		// greater than or equal to 400, with the exception of 404, are
		// turned into errors.
		IgnoreStatusCodes []int
		// Attributes controls the attributes included with errors.
		Attributes AttributeDestinationConfig
	}

	// 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
		}
		// SegmentThreshold 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.
		SegmentThreshold time.Duration
		// 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
		// Attributes controls the attributes included with transaction
		// traces.
		Attributes AttributeDestinationConfig
		// Segments.Attributes controls the attributes included with
		// each trace segment.
		Segments struct {
			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
	}

	// CrossApplicationTracer controls behaviour relating to cross application
	// tracing (CAT), available since Go Agent v0.11.  The
	// CrossApplicationTracer and the DistributedTracer cannot be
	// simultaneously enabled.
	//
	// https://docs.newrelic.com/docs/apm/transactions/cross-application-traces/introduction-cross-application-traces
	CrossApplicationTracer struct {
		Enabled bool
	}

	// DistributedTracer controls behaviour relating to Distributed Tracing,
	// available since Go Agent v2.1. The DistributedTracer and the
	// CrossApplicationTracer cannot be simultaneously enabled.
	//
	// https://docs.newrelic.com/docs/apm/distributed-tracing/getting-started/introduction-distributed-tracing
	DistributedTracer struct {
		Enabled bool
	}

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

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

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

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

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

Config contains Application and Transaction behavior settings. Use NewConfig to create a Config with proper defaults.

func NewConfig

func NewConfig(appname, license string) Config

NewConfig creates a Config populated with default settings and the given appname and license.

func (Config) MaxTxnEvents

func (c Config) MaxTxnEvents() int

MaxTxnEvents returns the configured maximum number of Transaction Events if it has been configured and is less than the default maximum; otherwise it returns the default max.

func (Config) Validate

func (c Config) Validate() error

Validate checks the config for improper fields. If the config is invalid, newrelic.NewApplication returns an error.

type DatastoreProduct

type DatastoreProduct string

DatastoreProduct is used to identify your datastore type in New Relic. It is used in the DatastoreSegment Product field. See https://github.com/newrelic/go-agent/blob/master/datastore.go for the full list of available DatastoreProducts.

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

Datastore names used across New Relic agents:

type DatastoreSegment

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

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

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

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

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

func (*DatastoreSegment) End

func (s *DatastoreSegment) End() error

End finishes the datastore segment.

type DistributedTracePayload

type DistributedTracePayload interface {
	// HTTPSafe serializes the payload into a string containing http safe
	// characters.
	HTTPSafe() string
	// Text serializes the payload into a string.  The format is slightly
	// more compact than HTTPSafe.
	Text() string
}

DistributedTracePayload traces requests between applications or processes. DistributedTracePayloads are automatically added to HTTP requests by StartExternalSegment, so you only need to use this if you are tracing through a message queue or another non-HTTP communication library. The DistributedTracePayload may be marshalled in one of two formats: HTTPSafe or Text. All New Relic agents can accept payloads in either format.

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 that implements ErrorClasser, ErrorAttributer, and StackTracer. Use it with Transaction.NoticeError to directly control error message, class, stacktrace, and attributes.

Example
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(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 implements the ErrorAttributes interface.

func (Error) ErrorClass

func (e Error) ErrorClass() string

ErrorClass implements the ErrorClasser interface.

func (Error) StackTrace

func (e Error) StackTrace() []uintptr

StackTrace implements the StackTracer interface.

type ErrorAttributer

type ErrorAttributer interface {
	ErrorAttributes() map[string]interface{}
}

ErrorAttributer can be implemented by errors to provide extra context when using Transaction.NoticeError.

type ErrorClasser

type ErrorClasser interface {
	ErrorClass() string
}

ErrorClasser can be implemented by errors to provide a custom class when using Transaction.NoticeError.

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
}

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

Example
txn := currentTransaction()
client := &http.Client{}
request, _ := http.NewRequest("GET", "http://www.example.com", nil)
segment := 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.

txn := currentTransaction()
segment := ExternalSegment{
	StartTime: StartSegmentNow(txn),
	// 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
txn := currentTransaction()
client := &http.Client{}
request, _ := http.NewRequest("GET", "http://www.example.com", nil)
segment := StartExternalSegment(txn, request)
response, _ := client.Do(request)
segment.Response = response
segment.End()
Output:

Example (Context)
txn := currentTransaction()
request, _ := http.NewRequest("GET", "http://www.example.com", nil)

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

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

func (*ExternalSegment) End

func (s *ExternalSegment) End() error

End finishes the external segment.

func (*ExternalSegment) OutboundHeaders

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

OutboundHeaders returns the headers that should be attached to the external request.

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 newrelic.Config.  If
	// multiple application names are specified, 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 link data to a trace or entity.

type Logger

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

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

func NewDebugLogger

func NewDebugLogger(w io.Writer) Logger

NewDebugLogger creates a basic Logger at debug level.

func NewLogger

func NewLogger(w io.Writer) Logger

NewLogger creates a basic Logger at info level.

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
txn := currentTransaction()
seg := &MessageProducerSegment{
	StartTime:       StartSegmentNow(txn),
	Library:         "RabbitMQ",
	DestinationType: MessageExchange,
	DestinationName: "myExchange",
}
// add message to queue here
seg.End()
Output:

func (*MessageProducerSegment) End

func (s *MessageProducerSegment) End() error

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/_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 StartSegment function.

func StartSegment

func StartSegment(txn Transaction, name string) *Segment

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

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

To time a block of code, do the following:

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

func (*Segment) End

func (s *Segment) End() error

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

func StartSegmentNow(txn Transaction) SegmentStartTime

StartSegmentNow starts timing a segment. This function is recommended over Transaction.StartSegmentNow() because it is nil safe.

type StackTracer

type StackTracer interface {
	StackTrace() []uintptr
}

StackTracer can be implemented by errors to provide a stack trace when using Transaction.NoticeError.

type TraceMetadata

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

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

type Transaction

type Transaction interface {
	// The transaction's http.ResponseWriter methods delegate to the
	// http.ResponseWriter provided as a parameter to
	// Application.StartTransaction or Transaction.SetWebResponse.  This
	// allows instrumentation of the response code and response headers.
	// These methods may be called safely if the transaction does not have a
	// http.ResponseWriter.
	http.ResponseWriter

	// 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.
	End() error

	// Ignore prevents this transaction's data from being recorded.
	Ignore() error

	// SetName names the transaction.  Use a limited set of unique names to
	// ensure that Transactions are grouped usefully.
	SetName(name string) 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 above
	// 400 or below 100 that is not in the IgnoreStatusCodes configuration
	// list.  This method is unaffected by the IgnoreStatusCodes
	// configuration list.
	NoticeError(err error) error

	// 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
	AddAttribute(key string, value interface{}) error

	// SetWebRequest marks the transaction as a web transaction.  If
	// WebRequest is non-nil, SetWebRequest will additionally collect
	// details on request attributes, url, and method.  If headers are
	// present, the agent will look for a distributed tracing header.  Use
	// NewWebRequest to transform a *http.Request into a WebRequest.
	SetWebRequest(WebRequest) error

	// SetWebResponse sets transaction's http.ResponseWriter.  After calling
	// this method, the transaction may be used in place of the
	// ResponseWriter to intercept the response code.  This method is useful
	// when the ResponseWriter is not available at the beginning of the
	// transaction (if so, it can be given as a parameter to
	// Application.StartTransaction).  This method will return a reference
	// to the transaction which implements the combination of
	// http.CloseNotifier, http.Flusher, http.Hijacker, and io.ReaderFrom
	// implemented by the ResponseWriter.
	SetWebResponse(http.ResponseWriter) Transaction

	// StartSegmentNow starts timing a segment.  The SegmentStartTime
	// returned can be used as the StartTime field in Segment,
	// DatastoreSegment, or ExternalSegment.  We recommend using the
	// StartSegmentNow function instead of this method since it checks if
	// the Transaction is nil.
	StartSegmentNow() SegmentStartTime

	// CreateDistributedTracePayload creates a payload used to link
	// transactions.  CreateDistributedTracePayload should be called every
	// time an outbound call is made since the payload contains a timestamp.
	//
	// StartExternalSegment calls CreateDistributedTracePayload, so you
	// don't need to use it for outbound HTTP calls: Just use
	// StartExternalSegment!
	//
	// This method never returns nil.  If the application is disabled or not
	// yet connected then this method returns a shim implementation whose
	// methods return empty strings.
	CreateDistributedTracePayload() DistributedTracePayload

	// AcceptDistributedTracePayload links transactions by accepting a
	// distributed trace payload from another transaction.
	//
	// Application.StartTransaction calls this method automatically if a
	// payload is present in the request headers.  Therefore, this method
	// does not need to be used for typical HTTP transactions.
	//
	// AcceptDistributedTracePayload should be used as early in the
	// transaction as possible.  It may not be called after a call to
	// CreateDistributedTracePayload.
	//
	// The payload parameter may be a DistributedTracePayload, a string, or
	// a []byte.
	AcceptDistributedTracePayload(t TransportType, payload interface{}) error

	// Application returns the Application which started the transaction.
	Application() Application

	// 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.
	BrowserTimingHeader() (*BrowserTimingHeader, error)

	// 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.
	//
	// Example passing a new Transaction reference directly to another
	// goroutine:
	//
	//	go func(txn newrelic.Transaction) {
	//		defer newrelic.StartSegment(txn, "async").End()
	//		time.Sleep(100 * time.Millisecond)
	//	}(txn.NewGoroutine())
	//
	// Example passing a new Transaction reference on a channel to another
	// goroutine:
	//
	//	ch := make(chan newrelic.Transaction)
	//	go func() {
	//		txn := <-ch
	//		defer newrelic.StartSegment(txn, "async").End()
	//		time.Sleep(100 * time.Millisecond)
	//	}()
	//	ch <- txn.NewGoroutine()
	//
	NewGoroutine() Transaction

	// GetTraceMetadata returns distributed tracing identifiers.  Empty
	// string identifiers are returned if the transaction has finished.
	GetTraceMetadata() TraceMetadata

	// GetLinkingMetadata returns the fields needed to link data to a trace or
	// entity.
	GetLinkingMetadata() LinkingMetadata

	// 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.
	IsSampled() bool
}

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

func FromContext

func FromContext(ctx context.Context) Transaction

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

type TransportType

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

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

type WebRequest

type WebRequest interface {
	// Header may return nil if you don't have any headers or don't want to
	// transform them to http.Header format.
	Header() http.Header
	// URL may return nil if you don't have a URL or don't want to transform
	// it to *url.URL.
	URL() *url.URL
	Method() string
	// If a distributed tracing header is found in the headers returned by
	// Header(), this TransportType will be used in the distributed tracing
	// metrics.
	Transport() TransportType
}

WebRequest may be implemented to provide request information to Transaction.SetWebRequest.

func NewStaticWebRequest

func NewStaticWebRequest(hdrs http.Header, url *url.URL, method string, transport TransportType) WebRequest

NewStaticWebRequest takes the minimum necessary information and creates a static WebRequest out of it

Example
app := getApp()
webReq := NewStaticWebRequest(http.Header{}, &url.URL{Path: "path"}, "GET", TransportHTTP)
txn := app.StartTransaction("My-Transaction", nil, nil)
txn.SetWebRequest(webReq)
Output:

func NewWebRequest

func NewWebRequest(request *http.Request) WebRequest

NewWebRequest turns a *http.Request into a WebRequest for input into Transaction.SetWebRequest.

Directories

Path Synopsis
_integrations
logcontext/nrlogrusplugin
Package nrlogrusplugin decorates logs for sending to the New Relic backend.
Package nrlogrusplugin decorates logs for sending to the New Relic backend.
nrawssdk/v1
Package nrawssdk instruments https://github.com/aws/aws-sdk-go requests.
Package nrawssdk instruments https://github.com/aws/aws-sdk-go requests.
nrawssdk/v2
Package nrawssdk instruments https://github.com/aws/aws-sdk-go-v2 requests.
Package nrawssdk instruments https://github.com/aws/aws-sdk-go-v2 requests.
nrb3
Package nrb3 supports adding B3 headers to outgoing requests.
Package nrb3 supports adding B3 headers to outgoing requests.
nrecho
Package nrecho instruments https://github.com/labstack/echo applications.
Package nrecho instruments https://github.com/labstack/echo applications.
nrgin/v1
Package nrgin instruments https://github.com/gin-gonic/gin applications.
Package nrgin instruments https://github.com/gin-gonic/gin applications.
nrgorilla/v1
Package nrgorilla instruments https://github.com/gorilla/mux applications.
Package nrgorilla instruments https://github.com/gorilla/mux applications.
nrgrpc
Package nrgrpc instruments https://github.com/grpc/grpc-go.
Package nrgrpc instruments https://github.com/grpc/grpc-go.
nrhttprouter
Package nrhttprouter instruments https://github.com/julienschmidt/httprouter applications.
Package nrhttprouter instruments https://github.com/julienschmidt/httprouter applications.
nrlambda
Package nrlambda adds support for AWS Lambda.
Package nrlambda adds support for AWS Lambda.
nrlogrus
Package nrlogrus sends go-agent log messages to https://github.com/sirupsen/logrus.
Package nrlogrus sends go-agent log messages to https://github.com/sirupsen/logrus.
nrlogxi/v1
Package nrlogxi supports https://github.com/mgutz/logxi.
Package nrlogxi supports https://github.com/mgutz/logxi.
nrmicro
Package nrmicro instruments https://github.com/micro/go-micro.
Package nrmicro instruments https://github.com/micro/go-micro.
nrmongo
Package nrmongo instruments https://github.com/mongodb/mongo-go-driver
Package nrmongo instruments https://github.com/mongodb/mongo-go-driver
nrmysql
Package nrmysql instruments https://github.com/go-sql-driver/mysql.
Package nrmysql instruments https://github.com/go-sql-driver/mysql.
nrnats
Package nrnats instruments https://github.com/nats-io/nats.go.
Package nrnats instruments https://github.com/nats-io/nats.go.
nrpkgerrors
Package nrpkgerrors introduces support for https://github.com/pkg/errors.
Package nrpkgerrors introduces support for https://github.com/pkg/errors.
nrpq
Package nrpq instruments https://github.com/lib/pq.
Package nrpq instruments https://github.com/lib/pq.
nrpq/example/sqlx
An application that illustrates how to instrument jmoiron/sqlx with DatastoreSegments
An application that illustrates how to instrument jmoiron/sqlx with DatastoreSegments
nrsqlite3
Package nrsqlite3 instruments https://github.com/mattn/go-sqlite3.
Package nrsqlite3 instruments https://github.com/mattn/go-sqlite3.
nrstan
Package nrstan instruments https://github.com/nats-io/stan.go.
Package nrstan instruments https://github.com/nats-io/stan.go.
nrzap
Package nrzap supports https://github.com/uber-go/zap
Package nrzap supports https://github.com/uber-go/zap
examples
client-round-tripper
An application that illustrates Distributed Tracing or Cross Application Tracing when using NewRoundTripper.
An application that illustrates Distributed Tracing or Cross Application Tracing when using NewRoundTripper.
custom-instrumentation
An application that illustrates Distributed Tracing with custom instrumentation.
An application that illustrates Distributed Tracing with custom instrumentation.
server-http
An application that illustrates Distributed Tracing or Cross Application Tracing when using http.Server or similar frameworks.
An application that illustrates Distributed Tracing or Cross Application Tracing when using http.Server or similar frameworks.
cat
Package cat provides functionality related to the wire format of CAT headers.
Package cat provides functionality related to the wire format of CAT headers.
integrationsupport
Package integrationsupport exists to expose functionality to integration packages without adding noise to the public API.
Package integrationsupport exists to expose functionality to integration packages without adding noise to the public API.
jsonx
Package jsonx extends the encoding/json package to encode JSON incrementally and without requiring reflection.
Package jsonx extends the encoding/json package to encode JSON incrementally and without requiring reflection.
stacktracetest
Package stacktracetest helps test stack trace behavior.
Package stacktracetest helps test stack trace behavior.
utilization
Package utilization implements the Utilization spec, available at https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md
Package utilization implements the Utilization spec, available at https://source.datanerd.us/agents/agent-specs/blob/master/Utilization.md

Jump to

Keyboard shortcuts

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