...

Source file src/k8s.io/klog/v2/klogr_slog_test.go

Documentation: k8s.io/klog/v2

     1  //go:build go1.21
     2  // +build go1.21
     3  
     4  /*
     5  Copyright 2023 The Kubernetes Authors.
     6  
     7  Licensed under the Apache License, Version 2.0 (the "License");
     8  you may not use this file except in compliance with the License.
     9  You may obtain a copy of the License at
    10  
    11      http://www.apache.org/licenses/LICENSE-2.0
    12  
    13  Unless required by applicable law or agreed to in writing, software
    14  distributed under the License is distributed on an "AS IS" BASIS,
    15  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    16  See the License for the specific language governing permissions and
    17  limitations under the License.
    18  */
    19  
    20  package klog_test
    21  
    22  import (
    23  	"errors"
    24  	"flag"
    25  	"fmt"
    26  	"log/slog"
    27  	"os"
    28  	"time"
    29  
    30  	"github.com/go-logr/logr"
    31  
    32  	"k8s.io/klog/v2"
    33  	internal "k8s.io/klog/v2/internal/buffer"
    34  )
    35  
    36  var _ slog.LogValuer = coordinates{}
    37  
    38  type coordinates struct {
    39  	x, y int
    40  }
    41  
    42  func (c coordinates) LogValue() slog.Value {
    43  	return slog.GroupValue(slog.Attr{Key: "X", Value: slog.IntValue(c.x)}, slog.Attr{Key: "Y", Value: slog.IntValue(c.y)})
    44  }
    45  
    46  func ExampleBackground_Slog() {
    47  	// Temporarily reconfigure for output to stdout, with -v=4.
    48  	state := klog.CaptureState()
    49  	defer state.Restore()
    50  	var fs flag.FlagSet
    51  	klog.InitFlags(&fs)
    52  	if err := fs.Set("logtostderr", "false"); err != nil {
    53  		fmt.Println(err)
    54  	}
    55  	if err := fs.Set("alsologtostderr", "false"); err != nil {
    56  		fmt.Println(err)
    57  	}
    58  	if err := fs.Set("v", "4"); err != nil {
    59  		fmt.Println(err)
    60  	}
    61  	if err := fs.Set("one_output", "true"); err != nil {
    62  		fmt.Println(err)
    63  	}
    64  	if err := fs.Set("skip_headers", "false"); err != nil {
    65  		fmt.Println(err)
    66  	}
    67  	klog.SetOutput(os.Stdout)
    68  
    69  	// To get consistent output for each run.
    70  	ts, _ := time.Parse(time.RFC3339, "2000-12-24T12:30:40Z")
    71  	internal.Time = &ts
    72  	internal.Pid = 123
    73  
    74  	logrLogger := klog.Background()
    75  	slogHandler := logr.ToSlogHandler(logrLogger)
    76  	slogLogger := slog.New(slogHandler)
    77  
    78  	// Note that -vmodule does not work when using the slog API because
    79  	// stack unwinding during the Enabled check leads to the wrong source
    80  	// code.
    81  	slogLogger.Debug("A debug message")
    82  	slogLogger.Log(nil, slog.LevelDebug-1, "A debug message with even lower level, not printed.")
    83  	slogLogger.Info("An info message")
    84  	slogLogger.Warn("A warning")
    85  	slogLogger.Error("An error", "err", errors.New("fake error"))
    86  
    87  	// The slog API supports grouping, in contrast to the logr API.
    88  	slogLogger.WithGroup("top").With("int", 42, slog.Group("variables", "a", 1, "b", 2)).Info("Grouping",
    89  		"sub", slog.GroupValue(
    90  			slog.Attr{Key: "str", Value: slog.StringValue("abc")},
    91  			slog.Attr{Key: "bool", Value: slog.BoolValue(true)},
    92  			slog.Attr{Key: "bottom", Value: slog.GroupValue(slog.Attr{Key: "coordinates", Value: slog.AnyValue(coordinates{x: -1, y: -2})})},
    93  		),
    94  		"duration", slog.DurationValue(time.Second),
    95  		slog.Float64("pi", 3.12),
    96  		"e", 2.71,
    97  		"moreCoordinates", coordinates{x: 100, y: 200},
    98  	)
    99  
   100  	// slog special values are also supported when passed through the logr API.
   101  	// This works with the textlogger, but might not work with other implementations
   102  	// and thus isn't portable. Passing attributes (= key and value in a single
   103  	// parameter) is not supported.
   104  	logrLogger.Info("slog values",
   105  		"variables", slog.GroupValue(slog.Int("a", 1), slog.Int("b", 2)),
   106  		"duration", slog.DurationValue(time.Second),
   107  		"coordinates", coordinates{x: 100, y: 200},
   108  	)
   109  
   110  	// Output:
   111  	// I1224 12:30:40.000000     123 klogr_slog_test.go:81] "A debug message"
   112  	// I1224 12:30:40.000000     123 klogr_slog_test.go:83] "An info message"
   113  	// W1224 12:30:40.000000     123 klogr_slog_test.go:84] "A warning"
   114  	// E1224 12:30:40.000000     123 klogr_slog_test.go:85] "An error" err="fake error"
   115  	// I1224 12:30:40.000000     123 klogr_slog_test.go:88] "Grouping" top.sub={"str":"abc","bool":true,"bottom":{"coordinates":{"X":-1,"Y":-2}}} top.duration="1s" top.pi=3.12 top.e=2.71 top.moreCoordinates={"X":100,"Y":200}
   116  	// I1224 12:30:40.000000     123 klogr_slog_test.go:104] "slog values" variables={"a":1,"b":2} duration="1s" coordinates={"X":100,"Y":200}
   117  }
   118  

View as plain text