github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/common/flogging/logging_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package flogging_test
    18  
    19  import (
    20  	"os"
    21  	"testing"
    22  
    23  	"github.com/hyperledger/fabric/common/flogging"
    24  	"github.com/op/go-logging"
    25  	"github.com/stretchr/testify/assert"
    26  )
    27  
    28  const logLevelCount = 6
    29  
    30  type testCase struct {
    31  	name           string
    32  	args           []string
    33  	expectedLevels []string
    34  	modules        []string
    35  	revert         bool
    36  	shouldErr      bool
    37  }
    38  
    39  func TestGetModuleLevelDefault(t *testing.T) {
    40  	assert.Equal(t, flogging.DefaultLevel(), flogging.GetModuleLevel("a"))
    41  }
    42  
    43  func TestSetModuleLevel(t *testing.T) {
    44  	defer flogging.Reset()
    45  
    46  	var tc []testCase
    47  
    48  	tc = append(tc,
    49  		testCase{"Valid", []string{"a", "warning"}, []string{"WARNING"}, []string{"a"}, false, false},
    50  		// Same as before
    51  		testCase{"Invalid", []string{"a", "foo"}, []string{flogging.DefaultLevel()}, []string{"a"}, false, false},
    52  		// Test setting the "error" module
    53  		testCase{"Error", []string{"error", "warning"}, []string{"WARNING"}, []string{"error"}, false, false},
    54  		// Tests with regular expressions
    55  		testCase{"RegexModuleWithSubmodule", []string{"foo", "warning"}, []string{"WARNING", "WARNING", flogging.DefaultLevel()},
    56  			[]string{"foo", "foo/bar", "baz"}, false, false},
    57  		// Set the level for modules that contain "foo" or "baz"
    58  		testCase{"RegexOr", []string{"foo|baz", "debug"}, []string{"DEBUG", "DEBUG", "DEBUG", flogging.DefaultLevel()},
    59  			[]string{"foo", "foo/bar", "baz", "random"}, false, false},
    60  		// Set the level for modules that end with "bar"
    61  		testCase{"RegexSuffix", []string{"bar$", "error"}, []string{"ERROR", flogging.DefaultLevel()},
    62  			[]string{"foo/bar", "bar/baz"}, false, false},
    63  		testCase{"RegexComplex", []string{"^[a-z]+\\/[a-z]+#.+$", "warning"}, []string{flogging.DefaultLevel(), flogging.DefaultLevel(), "WARNING", "WARNING", "WARNING"},
    64  			[]string{"gossip/util", "orderer/util", "gossip/gossip#0.0.0.0:7051", "gossip/conn#-1", "orderer/conn#0.0.0.0:7051"}, false, false},
    65  		testCase{"RegexInvalid", []string{"(", "warning"}, []string{flogging.DefaultLevel()},
    66  			[]string{"foo"}, false, true},
    67  		testCase{"RevertLevels", []string{"revertmodule1", "warning", "revertmodule2", "debug"}, []string{"WARNING", "DEBUG", "DEBUG"},
    68  			[]string{"revertmodule1", "revertmodule2", "revertmodule2/submodule"}, true, false},
    69  	)
    70  
    71  	assert := assert.New(t)
    72  
    73  	for i := 0; i < len(tc); i++ {
    74  		t.Run(tc[i].name, func(t *testing.T) {
    75  			for j := 0; j < len(tc[i].modules); j++ {
    76  				flogging.MustGetLogger(tc[i].modules[j])
    77  			}
    78  			if tc[i].revert {
    79  				flogging.SetPeerStartupModulesMap()
    80  			}
    81  			for k := 0; k < len(tc[i].args); k = k + 2 {
    82  				_, err := flogging.SetModuleLevel(tc[i].args[k], tc[i].args[k+1])
    83  				if tc[i].shouldErr {
    84  					assert.NotNil(err, "Should have returned an error")
    85  				}
    86  			}
    87  			for l := 0; l < len(tc[i].expectedLevels); l++ {
    88  				assert.Equal(tc[i].expectedLevels[l], flogging.GetModuleLevel(tc[i].modules[l]))
    89  			}
    90  			if tc[i].revert {
    91  				flogging.RevertToPeerStartupLevels()
    92  				for m := 0; m < len(tc[i].modules); m++ {
    93  					assert.Equal(flogging.GetPeerStartupLevel(tc[i].modules[m]), flogging.GetModuleLevel(tc[i].modules[m]))
    94  				}
    95  			}
    96  			flogging.Reset()
    97  		})
    98  	}
    99  }
   100  
   101  func TestInitFromSpec(t *testing.T) {
   102  	var tc []testCase
   103  
   104  	// GLOBAL
   105  
   106  	// all allowed log levels
   107  	for i := 0; i < logLevelCount; i++ {
   108  		level := logging.Level(i).String()
   109  		tc = append(tc, testCase{
   110  			name:           "Global" + level,
   111  			args:           []string{level},
   112  			expectedLevels: []string{level},
   113  			modules:        []string{""},
   114  		})
   115  	}
   116  	// NIL INPUT
   117  	tc = append(tc, testCase{
   118  		name:           "Global" + "NIL",
   119  		args:           []string{""},
   120  		expectedLevels: []string{flogging.DefaultLevel()},
   121  		modules:        []string{""},
   122  	})
   123  
   124  	// MODULES
   125  
   126  	tc = append(tc,
   127  		testCase{"SingleModuleLevel", []string{"a=info"}, []string{"INFO"}, []string{"a"}, false, false},
   128  		testCase{"MultipleModulesMultipleLevels", []string{"a=info:b=debug"}, []string{"INFO", "DEBUG"}, []string{"a", "b"}, false, false},
   129  		testCase{"MultipleModulesSameLevel", []string{"a,b=warning"}, []string{"WARNING", "WARNING"}, []string{"a", "b"}, false, false},
   130  	)
   131  
   132  	// MODULES + DEFAULT
   133  
   134  	tc = append(tc,
   135  		testCase{"GlobalDefaultAndSingleModuleLevel", []string{"info:a=warning"}, []string{"INFO", "WARNING"}, []string{"", "a"}, false, false},
   136  		testCase{"SingleModuleLevelAndGlobalDefaultAtEnd", []string{"a=warning:info"}, []string{"WARNING", "INFO"}, []string{"a", ""}, false, false},
   137  	)
   138  
   139  	// INVALID INPUT
   140  
   141  	tc = append(tc,
   142  		testCase{"InvalidLevel", []string{"foo"}, []string{flogging.DefaultLevel()}, []string{""}, false, false},
   143  		testCase{"InvalidLevelForSingleModule", []string{"a=foo"}, []string{flogging.DefaultLevel()}, []string{""}, false, false},
   144  		testCase{"EmptyModuleEqualsLevel", []string{"=warning"}, []string{flogging.DefaultLevel()}, []string{""}, false, false},
   145  		testCase{"InvalidModuleSyntax", []string{"a=b=c"}, []string{flogging.DefaultLevel()}, []string{""}, false, false},
   146  	)
   147  
   148  	assert := assert.New(t)
   149  
   150  	for i := 0; i < len(tc); i++ {
   151  		t.Run(tc[i].name, func(t *testing.T) {
   152  			defer flogging.Reset()
   153  			flogging.InitFromSpec(tc[i].args[0])
   154  			for j := 0; j < len(tc[i].expectedLevels); j++ {
   155  				assert.Equal(tc[i].expectedLevels[j], flogging.GetModuleLevel(tc[i].modules[j]))
   156  			}
   157  		})
   158  	}
   159  
   160  }
   161  
   162  func ExampleInitBackend() {
   163  	level, _ := logging.LogLevel(flogging.DefaultLevel())
   164  	// initializes logging backend for testing and sets time to 1970-01-01 00:00:00.000 UTC
   165  	logging.InitForTesting(level)
   166  
   167  	formatSpec := "%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x} %{message}"
   168  	flogging.InitBackend(flogging.SetFormat(formatSpec), os.Stdout)
   169  
   170  	logger := flogging.MustGetLogger("testModule")
   171  	logger.Info("test output")
   172  
   173  	// Output:
   174  	// 1970-01-01 00:00:00.000 UTC [testModule] ExampleInitBackend -> INFO 001 test output
   175  }