Get detailed performance insights for your Go applications by installing the New Relic Go agent. This guide walks you through a complete installation with examples for common Go application patterns.
Before you begin
Create a New Relic account - If you don't have one already, create a New Relic account. It's free, forever.
Check compatibility - Ensure you have:
- Go 1.19 or higher
- Linux, macOS, or Windows
- A supported web framework or library
Get your license key - You'll need your during installation.
Installation steps
Install the Go agent
Add the New Relic Go agent to your project:
$go get github.com/newrelic/go-agent/v3/newrelicSugerencia
Using Go modules? The agent works seamlessly with Go modules. If you're using an older Go version, you may need to add the agent to your vendor folder.
Import the agent
Add the import to your Go application:
import "github.com/newrelic/go-agent/v3/newrelic"Initialize the agent
Create an application instance in your main function:
func main() { app, err := newrelic.NewApplication( newrelic.ConfigAppName("My Go Application"), newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), ) if err != nil { log.Fatal("Failed to create New Relic application:", err) }
// Wait for the application to connect if err := app.WaitForCompletion(5 * time.Second); err != nil { log.Println("Warning: New Relic application did not connect:", err) }
// Your application code here}Importante
Security best practice: Always use environment variables for your license key instead of hardcoding it in your source code.
Instrument your web handlers
For HTTP applications, wrap your handlers to monitor web transactions:
// Method 1: Wrap individual handlershttp.HandleFunc(newrelic.WrapHandleFunc(app, "/", indexHandler))http.HandleFunc(newrelic.WrapHandleFunc(app, "/users", usersHandler))http.HandleFunc(newrelic.WrapHandleFunc(app, "/api/data", apiHandler))
// Method 2: Wrap your entire mux (recommended for many routes)mux := http.NewServeMux()mux.HandleFunc("/", indexHandler)mux.HandleFunc("/users", usersHandler)mux.HandleFunc("/api/data", apiHandler)
http.ListenAndServe(":8080", newrelic.WrapListen(app, mux))Add basic error handling
Capture errors in your handlers:
func usersHandler(w http.ResponseWriter, r *http.Request) { // Get transaction from request context txn := newrelic.FromContext(r.Context())
user, err := getUserFromDatabase(r.URL.Query().Get("id")) if err != nil { // Report error to New Relic txn.NoticeError(err) http.Error(w, "User not found", http.StatusNotFound) return }
// Add custom attributes txn.AddAttribute("user.id", user.ID) txn.AddAttribute("user.tier", user.Tier)
// Return user data json.NewEncoder(w).Encode(user)}Deploy and verify
Set your environment variable:
bash$export NEW_RELIC_LICENSE_KEY="your-license-key-here"Compile and run your application:
bash$go build -o myapp$./myappGenerate some traffic by visiting your application URLs
Check New Relic within 2-3 minutes at one.newrelic.com
Installation examples
Simple HTTP server
package main
import ( "fmt" "log" "net/http" "os" "time"
"github.com/newrelic/go-agent/v3/newrelic")
func main() { // Initialize New Relic app, err := newrelic.NewApplication( newrelic.ConfigAppName("Simple Go Server"), newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), ) if err != nil { log.Fatal(err) }
// Simple handler http.HandleFunc(newrelic.WrapHandleFunc(app, "/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }))
log.Println("Server starting on :8080") log.Fatal(http.ListenAndServe(":8080", nil))}Gin framework integration
package main
import ( "os"
"github.com/gin-gonic/gin" "github.com/newrelic/go-agent/v3/integrations/nrgin" "github.com/newrelic/go-agent/v3/newrelic")
func main() { // Initialize New Relic app, _ := newrelic.NewApplication( newrelic.ConfigAppName("Gin Application"), newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")), )
// Set up Gin with New Relic middleware r := gin.Default() r.Use(nrgin.Middleware(app))
r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello, World!"}) })
r.Run(":8080")}Background job monitoring
func processBackgroundJob(app *newrelic.Application, jobData JobData) { // Create a background transaction txn := app.StartTransaction("background-job") defer txn.End()
// Add job context txn.AddAttribute("job.id", jobData.ID) txn.AddAttribute("job.type", jobData.Type)
// Process job with error handling if err := processJob(jobData); err != nil { txn.NoticeError(err) log.Printf("Job %s failed: %v", jobData.ID, err) return }
log.Printf("Job %s completed successfully", jobData.ID)}What happens next?
After completing the basic installation, you'll immediately see:
- APM dashboard with response times, throughput, and error rates for your HTTP endpoints
- Transaction traces showing the slowest web requests
- Basic error tracking for errors reported via
txn.NoticeError()
To unlock additional monitoring capabilities, you'll need to add more instrumentation:
- Database monitoring - Requires database segment instrumentation
- External service tracking - Requires external segment instrumentation
- Custom metrics and events - Requires custom instrumentation
Troubleshooting
If you don't see data after installation:
- Check your application logs for New Relic connection messages
- Verify your license key is correct and not expired
- Ensure network connectivity to New Relic (ports 80/443)
- Review the troubleshooting guide for detailed help
Sugerencia
Enable debug logging to see what the agent is doing:
config := newrelic.NewConfig("My App", os.Getenv("NEW_RELIC_LICENSE_KEY"))config.Logger = newrelic.NewDebugLogger(os.Stdout)app, _ := newrelic.NewApplication(config)Next steps
Now that you have basic monitoring set up, you can enhance your observability through configuration and instrumentation:
- Configuration controls how the agent behaves globally across your entire application
- Instrumentation adds monitoring code to specific operations you want to track
Configure the agent
Use agent configuration to control global behavior and achieve:
- Enable distributed tracing - Trace requests across multiple services
- Control logging - Set debug levels and log destinations
- Set performance thresholds - Configure when queries are considered "slow"
- Enable security features - Turn on high-security mode
Add instrumentation
Use detailed instrumentation to monitor specific operations and achieve:
- Monitor database queries - Track SQL performance and slow queries
- Track external API calls - Monitor third-party service calls
- Monitor background jobs - Track non-web transactions
- Create custom metrics - Monitor business-specific KPIs
Advanced features and monitoring
- Explore advanced features like browser monitoring and custom events
- Set up alerts for key performance metrics
Sugerencia
Keep your agent updated: Regularly update to the latest version to get new features, performance improvements, and security patches.