github.com/Azure/aad-pod-identity@v1.8.17/pkg/log/options.go (about)

     1  package log
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  
     7  	"k8s.io/component-base/config"
     8  	json "k8s.io/component-base/logs/json"
     9  	"k8s.io/klog/v2"
    10  )
    11  
    12  const (
    13  	logFormatFlagName = "log-format"
    14  	// default log format
    15  	textLogFormat = "text"
    16  	jsonLogFormat = "json"
    17  )
    18  
    19  // Options has klog format parameters.
    20  type Options struct {
    21  	LogFormat string
    22  }
    23  
    24  // NewOptions return new klog options.
    25  func NewOptions() *Options {
    26  	return &Options{
    27  		LogFormat: textLogFormat,
    28  	}
    29  }
    30  
    31  // AddFlags adds log-format flag.
    32  func (o *Options) AddFlags() {
    33  	fs := flag.CommandLine
    34  	fs.StringVar(&o.LogFormat, logFormatFlagName, textLogFormat, fmt.Sprintf("Sets the logging format. One of (%s|%s)", textLogFormat, jsonLogFormat))
    35  }
    36  
    37  // Validate validates the log-format flag.
    38  func (o *Options) Validate() error {
    39  	if o.LogFormat != textLogFormat && o.LogFormat != jsonLogFormat {
    40  		return fmt.Errorf("unknown logging format %s. Only \"%s\" and \"%s\" are supported", o.LogFormat, textLogFormat, jsonLogFormat)
    41  	}
    42  
    43  	return nil
    44  }
    45  
    46  // Apply set klog logger from LogFormat type.
    47  func (o *Options) Apply() error {
    48  	if err := o.Validate(); err != nil {
    49  		return err
    50  	}
    51  
    52  	if o.LogFormat == jsonLogFormat {
    53  		logger, _ := json.Factory{}.Create(config.FormatOptions{})
    54  		klog.SetLogger(logger)
    55  	}
    56  
    57  	return nil
    58  }