...

Source file src/k8s.io/component-base/logs/example/example.go

Documentation: k8s.io/component-base/logs/example

     1  /*
     2  Copyright 2023 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 example shows how a library uses contextual logging.
    18  package example
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"os"
    25  	"time"
    26  
    27  	"k8s.io/klog/v2"
    28  )
    29  
    30  func init() {
    31  	// Intentionally broken: logging is not initialized yet.
    32  	klog.TODO().Info("Oops, I shouldn't be logging yet!")
    33  }
    34  
    35  func Run(ctx context.Context) {
    36  	fmt.Println("This is normal output via stdout.")
    37  	fmt.Fprintln(os.Stderr, "This is other output via stderr.")
    38  	klog.Infof("Log using Infof, key: %s", "value")
    39  	klog.InfoS("Log using InfoS", "key", "value")
    40  	err := errors.New("fail")
    41  	klog.Errorf("Log using Errorf, err: %v", err)
    42  	klog.ErrorS(err, "Log using ErrorS")
    43  	klog.V(1).Info("Log less important message")
    44  
    45  	// This is the fallback that can be used if neither logger nor context
    46  	// are available... but it's better to pass some kind of parameter.
    47  	klog.TODO().Info("Now the default logger is set, but using the one from the context is still better.")
    48  
    49  	logger := klog.FromContext(ctx)
    50  	logger.V(5).Info("Log less important message at V=5 through context")
    51  
    52  	// This intentionally uses the same key/value multiple times. Only the
    53  	// second example could be detected via static code analysis.
    54  	klog.LoggerWithValues(klog.LoggerWithName(logger, "myname"), "duration", time.Hour).Info("runtime", "duration", time.Minute)
    55  	logger.Info("another runtime", "duration", time.Hour, "duration", time.Minute)
    56  }
    57  

View as plain text