...

Source file src/k8s.io/klog/v2/ktesting/example_test.go

Documentation: k8s.io/klog/v2/ktesting

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     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 ktesting_test
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"time"
    23  
    24  	"k8s.io/klog/v2/ktesting"
    25  )
    26  
    27  func ExampleUnderlier() {
    28  	logger := ktesting.NewLogger(ktesting.NopTL{},
    29  		ktesting.NewConfig(
    30  			ktesting.Verbosity(4),
    31  			ktesting.BufferLogs(true),
    32  			ktesting.AnyToString(func(value interface{}) string {
    33  				return fmt.Sprintf("### %+v ###", value)
    34  			}),
    35  		),
    36  	)
    37  
    38  	logger.Error(errors.New("failure"), "I failed", "what", "something", "data", struct{ Field int }{Field: 1})
    39  	logger.WithValues("request", 42).WithValues("anotherValue", "fish").Info("hello world")
    40  	logger.WithValues("request", 42, "anotherValue", "fish").Info("hello world 2", "yetAnotherValue", "thanks")
    41  	logger.WithName("example").Info("with name")
    42  	logger.V(4).Info("higher verbosity")
    43  	logger.V(5).Info("Not captured because of ktesting.Verbosity(4) above. Normally it would be captured because default verbosity is 5.")
    44  
    45  	testingLogger, ok := logger.GetSink().(ktesting.Underlier)
    46  	if !ok {
    47  		panic("Should have had a ktesting LogSink!?")
    48  	}
    49  
    50  	t := testingLogger.GetUnderlying()
    51  	t.Log("This goes to /dev/null...")
    52  
    53  	buffer := testingLogger.GetBuffer()
    54  	fmt.Printf("%s\n", buffer.String())
    55  
    56  	log := buffer.Data()
    57  	for i, entry := range log {
    58  		if i > 0 &&
    59  			entry.Timestamp.Sub(log[i-1].Timestamp).Nanoseconds() < 0 {
    60  			fmt.Printf("Unexpected timestamp order: #%d %s > #%d %s", i-1, log[i-1].Timestamp, i, entry.Timestamp)
    61  		}
    62  		// Strip varying time stamp before dumping the struct.
    63  		entry.Timestamp = time.Time{}
    64  		fmt.Printf("log entry #%d: %+v\n", i, entry)
    65  	}
    66  
    67  	// Output:
    68  	// ERROR I failed err="failure" what="something" data=### {Field:1} ###
    69  	// INFO hello world request=### 42 ### anotherValue="fish"
    70  	// INFO hello world 2 request=### 42 ### anotherValue="fish" yetAnotherValue="thanks"
    71  	// INFO example: with name
    72  	// INFO higher verbosity
    73  	//
    74  	// log entry #0: {Timestamp:0001-01-01 00:00:00 +0000 UTC Type:ERROR Prefix: Message:I failed Verbosity:0 Err:failure WithKVList:[] ParameterKVList:[what something data {Field:1}]}
    75  	// log entry #1: {Timestamp:0001-01-01 00:00:00 +0000 UTC Type:INFO Prefix: Message:hello world Verbosity:0 Err:<nil> WithKVList:[request 42 anotherValue fish] ParameterKVList:[]}
    76  	// log entry #2: {Timestamp:0001-01-01 00:00:00 +0000 UTC Type:INFO Prefix: Message:hello world 2 Verbosity:0 Err:<nil> WithKVList:[request 42 anotherValue fish] ParameterKVList:[yetAnotherValue thanks]}
    77  	// log entry #3: {Timestamp:0001-01-01 00:00:00 +0000 UTC Type:INFO Prefix:example Message:with name Verbosity:0 Err:<nil> WithKVList:[] ParameterKVList:[]}
    78  	// log entry #4: {Timestamp:0001-01-01 00:00:00 +0000 UTC Type:INFO Prefix: Message:higher verbosity Verbosity:4 Err:<nil> WithKVList:[] ParameterKVList:[]}
    79  }
    80  
    81  func ExampleNewLogger() {
    82  	var buffer ktesting.BufferTL
    83  	logger := ktesting.NewLogger(&buffer, ktesting.NewConfig())
    84  
    85  	logger.Error(errors.New("failure"), "I failed", "what", "something", "data", struct{ Field int }{Field: 1})
    86  	logger.V(5).Info("Logged at level 5.")
    87  	logger.V(6).Info("Not logged at level 6.")
    88  
    89  	testingLogger, ok := logger.GetSink().(ktesting.Underlier)
    90  	if !ok {
    91  		panic("Should have had a ktesting LogSink!?")
    92  	}
    93  	fmt.Printf(">> %s <<\n", testingLogger.GetBuffer().String())       // Should be empty.
    94  	fmt.Print(headerRe.ReplaceAllString(buffer.String(), "${1}...] ")) // Should not be empty.
    95  
    96  	// Output:
    97  	// >>  <<
    98  	// E...] I failed err="failure" what="something" data={"Field":1}
    99  	// I...] Logged at level 5.
   100  }
   101  
   102  func ExampleConfig_Verbosity() {
   103  	var buffer ktesting.BufferTL
   104  	config := ktesting.NewConfig(ktesting.Verbosity(1))
   105  	logger := ktesting.NewLogger(&buffer, config)
   106  
   107  	logger.Info("initial verbosity", "v", config.Verbosity().String())
   108  	logger.V(2).Info("now you don't see me")
   109  	if err := config.Verbosity().Set("2"); err != nil {
   110  		logger.Error(err, "setting verbosity to 2")
   111  	}
   112  	logger.V(2).Info("now you see me")
   113  	if err := config.Verbosity().Set("1"); err != nil {
   114  		logger.Error(err, "setting verbosity to 1")
   115  	}
   116  	logger.V(2).Info("now I'm gone again")
   117  
   118  	fmt.Print(headerRe.ReplaceAllString(buffer.String(), "${1}...] "))
   119  
   120  	// Output:
   121  	// I...] initial verbosity v="1"
   122  	// I...] now you see me
   123  }
   124  

View as plain text