github.com/newrelic/newrelic-client-go@v1.1.0/pkg/events/example_batch_test.go (about)

     1  //go:build integration
     2  // +build integration
     3  
     4  package events
     5  
     6  import (
     7  	"context"
     8  	"log"
     9  	"os"
    10  	"strconv"
    11  
    12  	"github.com/newrelic/newrelic-client-go/pkg/config"
    13  )
    14  
    15  func Example_batch() {
    16  	// Initialize the client configuration.  An Insights insert key is required
    17  	// to communicate with the backend API.
    18  	cfg := config.New()
    19  	cfg.InsightsInsertKey = os.Getenv("NEW_RELIC_INSIGHTS_INSERT_KEY")
    20  
    21  	envAccountID := os.Getenv("NEW_RELIC_ACCOUNT_ID")
    22  	accountID, err := strconv.Atoi(envAccountID)
    23  	if err != nil {
    24  		log.Fatal("environment variable NEW_RELIC_ACCOUNT_ID required")
    25  	}
    26  
    27  	// Initialize the client.
    28  	client := New(cfg)
    29  
    30  	// Start batch mode
    31  	if err := client.BatchMode(context.Background(), accountID); err != nil {
    32  		log.Fatal("error starting batch mode:", err)
    33  	}
    34  
    35  	event := struct {
    36  		EventType string  `json:"eventType"`
    37  		Amount    float64 `json:"amount"`
    38  	}{
    39  		EventType: "Purchase",
    40  		Amount:    123.45,
    41  	}
    42  
    43  	// Queueu a custom event.
    44  	if err := client.EnqueueEvent(context.Background(), event); err != nil {
    45  		log.Fatal("error posting custom event:", err)
    46  	}
    47  
    48  	// Force flush events
    49  	if err := client.Flush(); err != nil {
    50  		log.Fatal("error flushing event queue:", err)
    51  	}
    52  }