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

     1  package zlog
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"go.uber.org/zap/zaptest"
     9  )
    10  
    11  func TestRadixTree(t *testing.T) {
    12  	root := &radixNode{}
    13  	root.insert("some.module_2.pkg_1", InfoLevel)
    14  	root.insert("some.module_2.pkg_2", DebugLevel)
    15  	root.insert("zlog.filtertest", WarnLevel)
    16  	root.insert("some.module_1", ErrorLevel)
    17  	root.insert("some.module_1.pkg_1", WarnLevel)
    18  
    19  	assert.Equal(t, `some.module_1=error
    20  some.module_1.pkg_1=warn
    21  some.module_2.pkg_1=info
    22  some.module_2.pkg_2=debug
    23  zlog.filtertest=warn`, strings.TrimSpace(root.dumpTree("")))
    24  
    25  	testcases := []struct {
    26  		Name  string
    27  		Level Level
    28  		Found bool
    29  	}{
    30  		{"some.module_1", ErrorLevel, true},
    31  		{"some.module_1.pkg_0", ErrorLevel, true},
    32  		{"some.module_1.pkg_1", WarnLevel, true},
    33  		{"some.module_2", InfoLevel, false},
    34  		{"some.module_2.pkg_0", InfoLevel, false},
    35  		{"some.module_2.pkg_1", InfoLevel, true},
    36  		{"some.module_2.pkg_2", DebugLevel, true},
    37  	}
    38  	for _, tc := range testcases {
    39  		level, found := root.search(tc.Name)
    40  		assert.Equalf(t, tc.Level, level, "name= %v", tc.Name)
    41  		assert.Equal(t, tc.Found, found, "name= %v", tc.Name)
    42  	}
    43  }
    44  
    45  func TestPerLoggerLevels(t *testing.T) {
    46  	buf := &zaptest.Buffer{}
    47  	filters := []string{
    48  		"zlog.testfilters=trace",
    49  		"some.pkg2=error",
    50  	}
    51  	logger, _, err := NewWithOutput(&Config{Development: true, Level: "info", PerLoggerLevels: filters}, buf)
    52  	assert.Nil(t, err)
    53  
    54  	lg1 := logger.Named("zlog")
    55  	lg1.Debug("zlog debug message 1") // no
    56  	lg1.Info("zlog info message 2")   // yes
    57  
    58  	lg1 = lg1.Named("testfilters")
    59  	lg1.Debug("zlog debug message 3") // yes
    60  	lg1.Info("zlog info message 4")   // yes
    61  	TRACE(lg1, "zlog TRACE message")  // yes
    62  
    63  	lg2 := logger.Named("some.pkg2")
    64  	lg2.Info("zlog info message 5")   // no
    65  	lg2.Warn("zlog warn message 6")   // no
    66  	lg2.Error("zlog error message 7") // yes
    67  
    68  	got := buf.String()
    69  	assert.NotContains(t, got, "zlog debug message 1")
    70  	assert.Contains(t, got, "zlog info message 2")
    71  	assert.Contains(t, got, "zlog debug message 3")
    72  	assert.Contains(t, got, "zlog info message 4")
    73  	assert.Contains(t, got, "zlog TRACE message")
    74  	assert.NotContains(t, got, "zlog info message 5")
    75  	assert.NotContains(t, got, "zlog warn message 6")
    76  	assert.Contains(t, got, "zlog error message 7")
    77  }