github.com/jxskiss/gopkg@v0.17.3/zlog/trace_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  	"go.uber.org/zap/zaptest"
    10  )
    11  
    12  func TestTrace(t *testing.T) {
    13  	buf := &zaptest.Buffer{}
    14  	l, p, _ := NewWithOutput(&Config{Level: "trace", Format: "logfmt"}, buf)
    15  	defer ReplaceGlobals(l, p)()
    16  
    17  	Trace("trace message", zap.String("k1", "v1"))
    18  
    19  	got := buf.String()
    20  	assert.Contains(t, got, "level=trace")
    21  	assert.Contains(t, got, "k1=v1")
    22  	assert.Contains(t, got, "caller=zlog/trace_test.go:17")
    23  	assert.Contains(t, got, `msg="[TRACE] trace message"`)
    24  }
    25  
    26  func TestTracef(t *testing.T) {
    27  	buf := &zaptest.Buffer{}
    28  	l, p, _ := NewWithOutput(&Config{Level: "trace", Format: "logfmt"}, buf)
    29  	defer ReplaceGlobals(l, p)()
    30  
    31  	Tracef("trace message, %v, %v", 123, 456)
    32  
    33  	got := buf.String()
    34  	assert.Contains(t, got, "level=trace")
    35  	assert.Contains(t, got, "caller=zlog/trace_test.go:31")
    36  	assert.Contains(t, got, `msg="[TRACE] trace message, 123, 456"`)
    37  }
    38  
    39  func TestTRACE(t *testing.T) {
    40  	defer ReplaceGlobals(mustNewGlobalLogger(&Config{Level: "trace", Development: true}))()
    41  
    42  	TRACE()
    43  	TRACE(context.Background())
    44  	TRACE(L())
    45  	TRACE(S())
    46  
    47  	TRACE("a", "b", "c", 1, 2, 3)
    48  	TRACE(context.Background(), "a", "b", "c", 1, 2, 3)
    49  	TRACE(L(), "a", "b", "c", 1, 2, 3)
    50  	TRACE(S(), "a", "b", "c", 1, 2, 3)
    51  
    52  	TRACE("a=%v, b=%v, c=%v", 1, 2, 3)
    53  	TRACE(context.Background(), "a=%v, b=%v, c=%v", 1, 2, 3)
    54  	TRACE(L(), "a=%v, b=%v, c=%v", 1, 2, 3)
    55  	TRACE(S(), "a=%v, b=%v, c=%v", 1, 2, 3)
    56  }
    57  
    58  func TestTRACESkip(t *testing.T) {
    59  	buf := &zaptest.Buffer{}
    60  	l, p, _ := NewWithOutput(&Config{Level: "trace"}, buf)
    61  	defer ReplaceGlobals(l, p)()
    62  
    63  	TRACE()
    64  	TRACESkip(0)
    65  	wrappedTRACE() // this line outputs two messages
    66  
    67  	lines := buf.Lines()
    68  	assert.Len(t, lines, 4)
    69  	for _, line := range lines {
    70  		t.Log(line)
    71  		assert.Contains(t, line, `"level":"trace"`)
    72  		assert.Contains(t, line, "========")
    73  		assert.Contains(t, line, TracePrefix)
    74  		assert.Contains(t, line, "zlog.TestTRACESkip")
    75  		assert.Regexp(t, `zlog/trace_test\.go:6[3-5]`, line)
    76  	}
    77  }
    78  
    79  func wrappedTRACE(args ...interface{}) {
    80  
    81  	var wrappedLevel2 = func(args ...interface{}) {
    82  		TRACESkip(2, args...)
    83  		return
    84  	}
    85  
    86  	TRACESkip(1, args...)
    87  	wrappedLevel2(args...)
    88  }