github.com/songzhibin97/gkit@v1.2.13/log/helper_test.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"io/ioutil"
     6  	"os"
     7  	"testing"
     8  )
     9  
    10  func TestHelper(t *testing.T) {
    11  	logger := With(DefaultLogger, "ts", DefaultTimestamp, "caller", DefaultCaller)
    12  	log := NewHelper(logger)
    13  
    14  	log.Log(LevelError, "msg", "test debug")
    15  	log.Debug("test debug")
    16  	log.Debugf("test %s", "debug")
    17  	log.Debugw("log", "test debug")
    18  }
    19  
    20  func TestHelperLevel(t *testing.T) {
    21  	log := NewHelper(DefaultLogger)
    22  	log.Debug("debug", "v")
    23  	log.Debugf("%s,%s", "debugf", "v")
    24  	log.Info("Info", "v")
    25  	log.Infof("%s,%s", "infof", "v")
    26  	log.Warn("Warn", "v")
    27  	log.Warnf("%s,%s", "warnf", "v")
    28  	log.Error("Error", "v")
    29  	log.Errorf("%s,%s", "errorf", "v")
    30  }
    31  
    32  func BenchmarkHelperPrint(b *testing.B) {
    33  	log := NewHelper(NewStdLogger(ioutil.Discard))
    34  	for i := 0; i < b.N; i++ {
    35  		log.Debug("test")
    36  	}
    37  }
    38  
    39  func BenchmarkHelperPrintf(b *testing.B) {
    40  	log := NewHelper(NewStdLogger(ioutil.Discard))
    41  	for i := 0; i < b.N; i++ {
    42  		log.Debugf("%s", "test")
    43  	}
    44  }
    45  
    46  func BenchmarkHelperPrintw(b *testing.B) {
    47  	log := NewHelper(NewStdLogger(ioutil.Discard))
    48  	for i := 0; i < b.N; i++ {
    49  		log.Debugw("key", "value")
    50  	}
    51  }
    52  
    53  func TestContext(t *testing.T) {
    54  	logger := With(NewStdLogger(os.Stdout),
    55  		"trace", Trace(),
    56  	)
    57  	log := NewHelper(logger)
    58  	ctx := context.WithValue(context.Background(), "trace_id", "2233")
    59  	log.WithContext(ctx).Info("got trace!")
    60  }
    61  
    62  func Trace() Valuer {
    63  	return func(ctx context.Context) interface{} {
    64  		s := ctx.Value("trace_id").(string)
    65  		return s
    66  	}
    67  }