github.com/newrelic/go-agent@v3.26.0+incompatible/_integrations/nrnats/nrnats.go (about) 1 // Copyright 2020 New Relic Corporation. All rights reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 4 package nrnats 5 6 import ( 7 "strings" 8 9 nats "github.com/nats-io/nats.go" 10 newrelic "github.com/newrelic/go-agent" 11 "github.com/newrelic/go-agent/internal" 12 "github.com/newrelic/go-agent/internal/integrationsupport" 13 ) 14 15 // StartPublishSegment creates and starts a `newrelic.MessageProducerSegment` 16 // (https://godoc.org/github.com/newrelic/go-agent#MessageProducerSegment) for NATS 17 // publishers. Call this function before calling any method that publishes or 18 // responds to a NATS message. Call `End()` 19 // (https://godoc.org/github.com/newrelic/go-agent#MessageProducerSegment.End) on the 20 // returned newrelic.MessageProducerSegment when the publish is complete. The 21 // `newrelic.Transaction` and `nats.Conn` parameters are required. The subject 22 // parameter is the subject of the publish call and is used in metric and span 23 // names. 24 func StartPublishSegment(txn newrelic.Transaction, nc *nats.Conn, subject string) *newrelic.MessageProducerSegment { 25 if nil == txn { 26 return nil 27 } 28 if nil == nc { 29 return nil 30 } 31 return &newrelic.MessageProducerSegment{ 32 StartTime: newrelic.StartSegmentNow(txn), 33 Library: "NATS", 34 DestinationType: newrelic.MessageTopic, 35 DestinationName: subject, 36 DestinationTemporary: strings.HasPrefix(subject, "_INBOX"), 37 } 38 } 39 40 // SubWrapper can be used to wrap the function for nats.Subscribe (https://godoc.org/github.com/nats-io/go-nats#Conn.Subscribe 41 // or https://godoc.org/github.com/nats-io/go-nats#EncodedConn.Subscribe) 42 // and nats.QueueSubscribe (https://godoc.org/github.com/nats-io/go-nats#Conn.QueueSubscribe or 43 // https://godoc.org/github.com/nats-io/go-nats#EncodedConn.QueueSubscribe) 44 // If the `newrelic.Application` parameter is non-nil, it will create a `newrelic.Transaction` and end the transaction 45 // when the passed function is complete. 46 func SubWrapper(app newrelic.Application, f func(msg *nats.Msg)) func(msg *nats.Msg) { 47 if app == nil { 48 return f 49 } 50 return func(msg *nats.Msg) { 51 namer := internal.MessageMetricKey{ 52 Library: "NATS", 53 DestinationType: string(newrelic.MessageTopic), 54 DestinationName: msg.Subject, 55 Consumer: true, 56 } 57 txn := app.StartTransaction(namer.Name(), nil, nil) 58 defer txn.End() 59 60 integrationsupport.AddAgentAttribute(txn, internal.AttributeMessageRoutingKey, msg.Sub.Subject, nil) 61 integrationsupport.AddAgentAttribute(txn, internal.AttributeMessageQueueName, msg.Sub.Queue, nil) 62 integrationsupport.AddAgentAttribute(txn, internal.AttributeMessageReplyTo, msg.Reply, nil) 63 64 f(msg) 65 } 66 }