github.com/jxskiss/gopkg@v0.17.3/zlog/builder_test.go (about)

     1  package zlog
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"go.uber.org/zap"
     9  )
    10  
    11  func TestB(t *testing.T) {
    12  
    13  	demoCtxFunc := func(ctx context.Context, args CtxArgs) (result CtxResult) {
    14  		if v1 := ctx.Value("k1"); v1 != nil {
    15  			result.Fields = append(result.Fields, zap.String("k1", v1.(string)))
    16  		}
    17  		if v2 := ctx.Value("k2"); v2 != nil {
    18  			result.Fields = append(result.Fields, zap.Int("k2", v2.(int)))
    19  		}
    20  		return result
    21  	}
    22  	defer testHelperReplaceGlobalsToStdout(demoCtxFunc)()
    23  
    24  	builder1 := B(context.Background())
    25  	assert.Equal(t, baseBuilder, builder1)
    26  
    27  	ctx2 := WithBuilder(context.Background(),
    28  		builder1.With(zap.Int64("some1", 1), zap.String("some2", "value")))
    29  	builder2 := B(ctx2)
    30  	assert.NotEqual(t, builder2, builder1)
    31  	assert.Len(t, builder2.fields, 2)
    32  
    33  	ctx3 := WithBuilder(context.Background(), builder2)
    34  	builder3 := B(ctx3)
    35  	assert.Equal(t, builder2, builder3)
    36  
    37  	ctx4 := context.WithValue(context.Background(), "k1", "v1")
    38  	ctx4 = context.WithValue(ctx4, "k2", 123)
    39  	builder4 := B(ctx4)
    40  	assert.Len(t, builder4.fields, 2)
    41  }
    42  
    43  func BenchmarkZapLoggerWith(b *testing.B) {
    44  	b.ReportAllocs()
    45  	for i := 0; i < b.N; i++ {
    46  		method, _, _, _ := getCaller(0)
    47  		_ = L().With(
    48  			zap.String("method", method),
    49  			zap.Int64("some1", 1),
    50  			zap.String("some2", "value"),
    51  			zap.String("some3", "value"),
    52  		)
    53  	}
    54  }
    55  
    56  func BenchmarkWithMethod(b *testing.B) {
    57  	b.ReportAllocs()
    58  	for i := 0; i < b.N; i++ {
    59  		_ = WithMethod(
    60  			zap.Int64("some1", 1),
    61  			zap.String("some2", "value"),
    62  			zap.String("some3", "value"),
    63  		)
    64  	}
    65  }
    66  
    67  func BenchmarkBuilder(b *testing.B) {
    68  	b.ReportAllocs()
    69  	for i := 0; i < b.N; i++ {
    70  		_ = B(context.TODO()).Method().With(
    71  			zap.Int64("some1", 1),
    72  			zap.String("some2", "value"),
    73  			zap.String("some3", "value"),
    74  		).Build()
    75  	}
    76  }