github.com/newrelic/go-agent@v3.26.0+incompatible/_integrations/logcontext/nrlogrusplugin/example/main.go (about)

     1  // Copyright 2020 New Relic Corporation. All rights reserved.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package main
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"os"
    10  	"time"
    11  
    12  	newrelic "github.com/newrelic/go-agent"
    13  	"github.com/newrelic/go-agent/_integrations/logcontext/nrlogrusplugin"
    14  	"github.com/sirupsen/logrus"
    15  )
    16  
    17  func mustGetEnv(key string) string {
    18  	if val := os.Getenv(key); "" != val {
    19  		return val
    20  	}
    21  	panic(fmt.Sprintf("environment variable %s unset", key))
    22  }
    23  
    24  func doFunction2(txn newrelic.Transaction, e *logrus.Entry) {
    25  	defer newrelic.StartSegment(txn, "doFunction2").End()
    26  	e.Error("In doFunction2")
    27  }
    28  
    29  func doFunction1(txn newrelic.Transaction, e *logrus.Entry) {
    30  	defer newrelic.StartSegment(txn, "doFunction1").End()
    31  	e.Trace("In doFunction1")
    32  	doFunction2(txn, e)
    33  }
    34  
    35  func main() {
    36  	log := logrus.New()
    37  	// To enable New Relic log decoration, use the
    38  	// nrlogrusplugin.ContextFormatter{}
    39  	log.SetFormatter(nrlogrusplugin.ContextFormatter{})
    40  	log.SetLevel(logrus.TraceLevel)
    41  
    42  	log.Debug("Logger created")
    43  
    44  	cfg := newrelic.NewConfig("Logrus Log Decoration", mustGetEnv("NEW_RELIC_LICENSE_KEY"))
    45  	cfg.DistributedTracer.Enabled = true
    46  	cfg.CrossApplicationTracer.Enabled = false
    47  
    48  	app, err := newrelic.NewApplication(cfg)
    49  	if nil != err {
    50  		log.Panic("Failed to create application", err)
    51  	}
    52  
    53  	log.Debug("Application created, waiting for connection")
    54  
    55  	err = app.WaitForConnection(10 * time.Second)
    56  	if nil != err {
    57  		log.Panic("Failed to connect application", err)
    58  	}
    59  	log.Info("Application connected")
    60  	defer app.Shutdown(10 * time.Second)
    61  
    62  	log.Debug("Starting transaction now")
    63  	txn := app.StartTransaction("main", nil, nil)
    64  
    65  	// Add the transaction context to the logger. Only once this happens will
    66  	// the logs be properly decorated with all required fields.
    67  	e := log.WithContext(newrelic.NewContext(context.Background(), txn))
    68  
    69  	doFunction1(txn, e)
    70  
    71  	e.Info("Ending transaction")
    72  	txn.End()
    73  }