github.com/newrelic/newrelic-client-go@v1.1.0/pkg/logs/example_log_batch_test.go (about)

     1  //go:build integration
     2  // +build integration
     3  
     4  package logs
     5  
     6  import (
     7  	"context"
     8  	"log"
     9  	"os"
    10  	"time"
    11  
    12  	"github.com/newrelic/newrelic-client-go/pkg/config"
    13  )
    14  
    15  const (
    16  	BatchTimeoutSeconds = 5
    17  )
    18  
    19  //func TestExample_log_batch(t *testing.T) {
    20  func Example_basic() {
    21  	// Initialize the client configuration.  A New Relic License Key is required to communicate with the backend API.
    22  	cfg := config.New()
    23  	cfg.LicenseKey = os.Getenv("NEW_RELIC_LICENSE_KEY")
    24  	cfg.LogLevel = "trace"
    25  	cfg.Compression = config.Compression.None
    26  
    27  	// Initialize the client.
    28  	client := New(cfg)
    29  	client.batchTimeout = BatchTimeoutSeconds * time.Second
    30  
    31  	logEntries := []struct {
    32  		Message string `json:"message"`
    33  		LogType string `json:"logType"`
    34  	}{
    35  		{
    36  			Message: "INFO: From example_log_batch_test.go message 1",
    37  			LogType: "Teapot",
    38  		},
    39  		{
    40  			Message: "INFO: From example_log_batch_test.go message 2",
    41  			LogType: "Teapot",
    42  		}}
    43  
    44  	// Start batch mode, 12345 is a placeholder to pass PR compilation
    45  	if err := client.BatchMode(context.Background(), 12345); err != nil {
    46  		log.Fatal("error starting batch mode: ", err)
    47  	}
    48  
    49  	// Queue log entries.
    50  	for _, e := range logEntries {
    51  		if err := client.EnqueueLogEntry(context.Background(), e); err != nil {
    52  			log.Fatal("error queuing log entry: ", err)
    53  		}
    54  	}
    55  
    56  	// Hack to stop the test from ending BEFORE the queue flushes
    57  	time.Sleep((BatchTimeoutSeconds * 2) * time.Second)
    58  	// Force flush
    59  	if err := client.Flush(); err != nil {
    60  		log.Fatal("error flushing log queue: ", err)
    61  	}
    62  }