File: examples_test.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (396 lines) | stat: -rw-r--r-- 12,573 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package newrelic_test

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"time"

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

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

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

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

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

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

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

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

var txn *newrelic.Transaction

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

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

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

	client.Do(request)
}

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

func ExampleBrowserTimingHeader() {
	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)
}

func ExampleDatastoreSegment() {
	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()
}

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

func ExampleError() {
	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,
		},
	})
}

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

// 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.
func ExampleExternalSegment_url() {
	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()
}

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

func ExampleStartExternalSegment_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 = newrelic.RequestWithTransactionContext(request, txn)
	segment := newrelic.StartExternalSegment(nil, request)

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

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

// Use ExternalSegment.SetStatusCode when you do not have access to an
// http.Response and still want to record the response status code.
func ExampleExternalSegment_SetStatusCode() {
	txn := currentTransaction()
	request, _ := http.NewRequest("GET", "http://www.example.com", nil)
	segment := newrelic.StartExternalSegment(txn, request)
	statusCode := doSendRequest(request)
	segment.SetStatusCode(statusCode)
	segment.End()
}

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

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

// 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.
func ExampleTransaction_SetWebRequestHTTP_nil() {
	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)
}

// 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.
func ExampleTransaction_SetWebResponse() {
	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)
	})
}

// The order in which the ConfigOptions are added plays an important role when
// using ConfigFromEnvironment.
func ExampleConfigFromEnvironment() {
	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(),
	)
}

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

// While many ConfigOptions are provided for you, it is also possible to create
// your own.  This is necessary if you have complex configuration needs.
func ExampleConfigOption_custom() {
	_, _ = 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
		},
	)
}

// Setting the Config.Error field will cause the NewApplication function to
// return an error.
func ExampleConfigOption_errors() {
	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 ExampleTransaction_StartSegmentNow() {
	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()
}

// Passing a new Transaction reference directly to another goroutine.
func ExampleTransaction_NewGoroutine() {
	go func(txn *newrelic.Transaction) {
		defer txn.StartSegment("async").End()
		// Do some work
		time.Sleep(100 * time.Millisecond)
	}(txn.NewGoroutine())
}

// Passing a new Transaction reference on a channel to another goroutine.
func ExampleTransaction_NewGoroutine_channel() {
	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()
}

// 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.
func ExampleTransaction_NewGoroutine_insideGoroutines() {
	// 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)
}