github.com/weaveworks/common@v0.0.0-20230728070032-dd9e68f319d5/logging/format.go (about)

     1  package logging
     2  
     3  import (
     4  	"flag"
     5  
     6  	"github.com/pkg/errors"
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  // Format is a settable identifier for the output format of logs
    11  type Format struct {
    12  	s      string
    13  	Logrus logrus.Formatter
    14  }
    15  
    16  // RegisterFlags adds the log format flag to the provided flagset.
    17  func (f *Format) RegisterFlags(fs *flag.FlagSet) {
    18  	f.Set("logfmt")
    19  	fs.Var(f, "log.format", "Output log messages in the given format. Valid formats: [logfmt, json]")
    20  }
    21  
    22  func (f Format) String() string {
    23  	return f.s
    24  }
    25  
    26  // UnmarshalYAML implements yaml.Unmarshaler.
    27  func (f *Format) UnmarshalYAML(unmarshal func(interface{}) error) error {
    28  	var format string
    29  	if err := unmarshal(&format); err != nil {
    30  		return err
    31  	}
    32  	return f.Set(format)
    33  }
    34  
    35  // MarshalYAML implements yaml.Marshaler.
    36  func (f Format) MarshalYAML() (interface{}, error) {
    37  	return f.String(), nil
    38  }
    39  
    40  // Set updates the value of the output format.  Implements flag.Value
    41  func (f *Format) Set(s string) error {
    42  	switch s {
    43  	case "logfmt":
    44  		f.Logrus = &logrus.JSONFormatter{}
    45  	case "json":
    46  		f.Logrus = &logrus.JSONFormatter{}
    47  	default:
    48  		return errors.Errorf("unrecognized log format %q", s)
    49  	}
    50  	f.s = s
    51  	return nil
    52  }