...

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

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

     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 main
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"os"
    24  	"strings"
    25  
    26  	"k8s.io/apimachinery/pkg/util/runtime"
    27  	"k8s.io/component-base/featuregate"
    28  	"k8s.io/component-base/logs"
    29  	logsapi "k8s.io/component-base/logs/api/v1"
    30  	"k8s.io/component-base/logs/example"
    31  	"k8s.io/klog/v2"
    32  
    33  	_ "k8s.io/component-base/logs/json/register"
    34  )
    35  
    36  func main() {
    37  	// Set up command line, including a feature gate parameter and logging options.
    38  	featureGate := featuregate.NewFeatureGate()
    39  	runtime.Must(logsapi.AddFeatureGates(featureGate))
    40  	flag.Var(featureGate, "feature-gate",
    41  		"A set of key=value pairs that describe feature gates for alpha/experimental features. "+
    42  			"Options are:\n"+strings.Join(featureGate.KnownFeatures(), "\n"))
    43  	c := logsapi.NewLoggingConfiguration()
    44  	logsapi.AddGoFlags(c, flag.CommandLine)
    45  
    46  	// Parse flags and apply the result. logs.InitLogs disables contextual
    47  	// logging while it is still alpha. The feature gate parameter must be
    48  	// used to enable it explicitly.
    49  	flag.Parse()
    50  	logs.InitLogs()
    51  	if err := logsapi.ValidateAndApply(c, featureGate); err != nil {
    52  		fmt.Fprintf(os.Stderr, "%v\n", err)
    53  		os.Exit(1)
    54  	}
    55  	args := flag.CommandLine.Args()
    56  	if len(args) > 0 {
    57  		fmt.Fprintf(os.Stderr, "Unexpected additional command line arguments:\n    %s\n", strings.Join(args, "\n    "))
    58  		os.Exit(1)
    59  	}
    60  
    61  	// Initialize contextual logging.
    62  	logger := klog.LoggerWithValues(klog.LoggerWithName(klog.Background(), "example"), "foo", "bar")
    63  	ctx := klog.NewContext(context.Background(), logger)
    64  
    65  	// Produce some output.
    66  	example.Run(ctx)
    67  }
    68  

View as plain text