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

     1  package logging
     2  
     3  // Copy-pasted from prometheus/common/promlog.
     4  // Copyright 2017 The Prometheus Authors
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  // http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  import (
    18  	"flag"
    19  
    20  	"github.com/go-kit/log/level"
    21  	"github.com/pkg/errors"
    22  	"github.com/sirupsen/logrus"
    23  )
    24  
    25  // Level is a settable identifier for the minimum level a log entry
    26  // must be have.
    27  type Level struct {
    28  	s      string
    29  	Logrus logrus.Level
    30  	Gokit  level.Option
    31  }
    32  
    33  // RegisterFlags adds the log level flag to the provided flagset.
    34  func (l *Level) RegisterFlags(f *flag.FlagSet) {
    35  	l.Set("info")
    36  	f.Var(l, "log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error]")
    37  }
    38  
    39  func (l *Level) String() string {
    40  	return l.s
    41  }
    42  
    43  // UnmarshalYAML implements yaml.Unmarshaler.
    44  func (l *Level) UnmarshalYAML(unmarshal func(interface{}) error) error {
    45  	var level string
    46  	if err := unmarshal(&level); err != nil {
    47  		return err
    48  	}
    49  	return l.Set(level)
    50  }
    51  
    52  // MarshalYAML implements yaml.Marshaler.
    53  func (l Level) MarshalYAML() (interface{}, error) {
    54  	return l.String(), nil
    55  }
    56  
    57  // Set updates the value of the allowed level.  Implments flag.Value.
    58  func (l *Level) Set(s string) error {
    59  	switch s {
    60  	case "debug":
    61  		l.Logrus = logrus.DebugLevel
    62  		l.Gokit = level.AllowDebug()
    63  	case "info":
    64  		l.Logrus = logrus.InfoLevel
    65  		l.Gokit = level.AllowInfo()
    66  	case "warn":
    67  		l.Logrus = logrus.WarnLevel
    68  		l.Gokit = level.AllowWarn()
    69  	case "error":
    70  		l.Logrus = logrus.ErrorLevel
    71  		l.Gokit = level.AllowError()
    72  	default:
    73  		return errors.Errorf("unrecognized log level %q", s)
    74  	}
    75  
    76  	l.s = s
    77  	return nil
    78  }