New Relic Go Agent

repository·master·Indexed 21 days ago

https://github.com/newrelic/go-agent

Observability agent for Go applications (v3) that monitors transactions, database calls, and system runtime metrics such as goroutines and memory usage. It supports manual instrumentation via its API, basic runtime monitoring, and specialized integration packages for popular web frameworks and libraries. Includes tools for log integration via logWriter, nrzerolog, and zerologWriter to enable Logs in Context and distributed tracing.

Tokens
65.6K
Snippets
258
Records
298
Agent score
74%

What's inside newrelic-go-agent

  1. Overview of the New Relic Go Agent

    master

    The New Relic Go Agent is used to monitor Go applications by tracking transactions, outbound requests, database calls, and other application behaviors. It also provides runtime visibility into garbage collection, goroutine activity, and memory usage.

    Because Go is a compiled language without a virtual machine, instrumentation requires using the New Relic Go agent API to manually add methods to your source code. This provides high flexibility and control over what is instrumented. For a more automated setup, you can use the go-easy-instrumentation CLI tool to analyze your code and suggest instrumentation points.

  2. Use Logs in Context to link logs to APM traces

    master
    The logcontext integration package provides various logging plugins designed to inject necessary metadata (context) into your log messages. By using these plugins, you can enable 'Logs in Context' in the New Relic UI, which allows you to see direct links between your application logs and your APM (Application Performance Monitoring) traces.
  3. Use the New Relic Log Writer to integrate logs with New Relic

    master
    The logWriter library provides an io.Writer implementation that integrates New Relic Logs in Context features with the Go standard library logger. It automatically collects log metrics, forwards logs, and enriches them with New Relic metadata based on your application configuration. This is the recommended way to capture log data for New Relic in Go.
  4. Integrate Zerolog with New Relic Logs in Context

    master

    The zerologWriter library provides an io.Writer implementation that automatically integrates New Relic Logs in Context features with Zerolog. It collects log metrics, forwards logs, and enriches them with New Relic metadata based on your application configuration. This is the recommended way to capture log data when using Zerolog.

    // Create a new ZerologWriter instance
    // os.Stdout is the destination for the final log content
    // app is your pointer to the New Relic application
    writer := zerologWriter.New(os.Stdout, app)
  5. Understand datastore instance metric attributes

    master

    Datastore instance tests use a specific set of attributes to simulate database configurations and verify the generation of datastore instance metrics. When implementing or testing datastore integrations, you should be aware of which attributes are consistently provided and which are optional based on the database adapter's capabilities.

    NamePresentDescription
    system_hostnamealwaysthe hostname of the machine
    db_hostnamesometimesthe hostname reported by the database adapter
    productalwaysthe database product for this configuration
    portsometimesthe port reported by the database adapter
    unix_socketsometimesthe path to a unix domain socket reported by a database adapter
    database_pathsometimesthe path to a filesystem database
    expected_instance_metricalwaysthe instance metric expected to be generated from the given attributes
  6. Ways to instrument your Go application

    master

    There are three primary ways to get data into New Relic using this agent:

    1. Manual Instrumentation: Use the Go agent API to add specific methods to your source code for maximum control.
    2. Basic Runtime Monitoring: Even without manual instrumentation, simply importing the agent and creating an application instance will provide runtime information such as goroutine counts, garbage collection statistics, and memory/CPU usage.
    3. Integration Packages: Use the available INTEGRATION packages for out-of-the-box support for popular Go web frameworks and libraries.
  7. Understand the Utilization Test schema

    master

    Utilization tests verify that the Go agent gathers the correct information for pricing purposes. These tests validate the JSON generated by the agents by comparing input values against an expected_output_json.

    Each test case is represented as a JSON block containing specific fields that the agent is expected to calculate or detect from the environment.

  8. Use New Relic integration packages for frameworks and libraries

    master

    The New Relic Go Agent provides specialized integration packages that extend the core newrelic package to support specific frameworks, databases, and libraries. These packages automate instrumentation for inbound requests, outbound calls, and datastore operations.

    To use an integration, you must import both the core newrelic package and the specific integration package (e.g., v3/integrations/nrgin).

    // Example pattern for using an integration (based on nrgin documentation)
    import (
    	"github.com/newrelic/go-agent/v3/newrelic"
    	"github.com/newrelic/go-agent/v3/integrations/nrgin"
    	"github.com/gin-gonic/gin"
    )
  9. Understand Synthetics Test Verification

    master

    Synthetics tests verify that the Go agent correctly handles New Relic Synthetics requests. The testing lifecycle simulates a web transaction with the following flow:

    1. Request Initiation: A Synthetics HTTP request header is added to the incoming request.
    2. External Request: During the transaction, an external request is made.
    3. Completion: Upon transaction completion, a Transaction Trace and a Transaction Event are recorded.

    Tests validate that for valid requests, the correct attributes are added to the Trace and Event, and the proper request header is added to outbound external requests. For invalid requests, tests verify that these attributes and headers are not added.

  10. Understand the event_source_info test fixture structure

    master

    The event_source_info test fixture is used to verify that the New Relic Go Agent correctly detects event types (specifically in languages with dynamic typing) and accurately harvests AWS ARN values from Lambda invocation events.

    Each fixture is a JSON object containing three specific keys:

    • expected_type: The event type the agent is expected to identify (e.g., alb).
    • expected_arn: The AWS ARN value the agent should extract from the event.
    • event: The raw AWS Lambda invocation event object used for testing.

    The top-level key in the JSON object is a <type_key> used for organizational convenience during testing.

    {
      "<type_key>": {
        "expected_type": "alb",
        "expected_arn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a",
        "event": { ... }
      }
    }
  11. How tracing instrumentation works

    master

    The Go Agent provides both automatic and manual instrumentation for tracing:

    Automatic Instrumentation

    For Server Applications:

    • Using WrapHandle or WrapHandleFunc with http.ServeMux.
    • Using any of the Go Agent's built-in HTTP integrations.
    • Using other frameworks or http.Server if you manually call Transaction.SetWebRequest and Transaction.SetWebResponse after StartTransaction, and use the http.ResponseWriter returned by SetWebResponse instead of the original one.

    For Client Applications:

    • Using NewRoundTripper.
    • Calling StartExternalSegment and providing an http.Request.

    Manual Instrumentation

    If your service is not instrumented automatically, you must manually propagate headers:

    1. Calling Service: Use callingTxn.InsertDistributedTraceHeaders(h) to insert headers into the request.
    2. Called Service: Use calledTxn.AcceptDistributedTraceHeaders(newrelic.TransportOther, h) to accept the headers.
    // Calling service
    var h http.Headers
    callingTxn.InsertDistributedTraceHeaders(h)
    
    // Called service
    var h http.Headers
    calledTxn.AcceptDistributedTraceHeaders(newrelic.TransportOther, h)
  12. Update Transaction Names for HTTP Methods

    master

    In v3, transaction names created by WrapHandle, WrapHandleFunc, nrecho-v3, nrecho-v4, nrgorilla, and nrgin now automatically include the HTTP method.

    Example Change:

    • Old: WebTransaction/Go/users
    • New: WebTransaction/Go/GET /users

    Action Required: You may need to update your New Relic alerts and dashboards to reflect these new naming patterns.