go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/logging/level.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package logging
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"flag"
    21  )
    22  
    23  // Level is an enumeration consisting of supported log levels.
    24  type Level int
    25  
    26  // Level implements flag.Value.
    27  var _ flag.Value = (*Level)(nil)
    28  
    29  // Defined log levels.
    30  const (
    31  	Debug Level = iota
    32  	Info
    33  	Warning
    34  	Error
    35  )
    36  
    37  // DefaultLevel is the default Level value.
    38  const DefaultLevel = Info
    39  
    40  // Set implements flag.Value.
    41  func (l *Level) Set(v string) error {
    42  	switch v {
    43  	case "debug":
    44  		*l = Debug
    45  	case "info":
    46  		*l = Info
    47  	case "warning":
    48  		*l = Warning
    49  	case "error":
    50  		*l = Error
    51  
    52  	default:
    53  		return errors.New("unknown log level value")
    54  	}
    55  	return nil
    56  }
    57  
    58  // String implements flag.Value.
    59  func (l Level) String() string {
    60  	switch l {
    61  	case Debug:
    62  		return "debug"
    63  	case Info:
    64  		return "info"
    65  	case Warning:
    66  		return "warning"
    67  	case Error:
    68  		return "error"
    69  
    70  	default:
    71  		return "unknown"
    72  	}
    73  }
    74  
    75  // SetLevel returns a new context with the given logging level.
    76  //
    77  // It can be retrieved with GetLevel(context).
    78  func SetLevel(ctx context.Context, l Level) context.Context {
    79  	return context.WithValue(ctx, levelKey, l)
    80  }
    81  
    82  // GetLevel returns the Level for this context. It will return DefaultLevel if
    83  // none is defined.
    84  func GetLevel(ctx context.Context) Level {
    85  	if l, ok := ctx.Value(levelKey).(Level); ok {
    86  		return l
    87  	}
    88  	return DefaultLevel
    89  }