Source File
level.go
Belonging Package
log/slog
// Copyright 2022 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package slogimport ()// A Level is the importance or severity of a log event.// The higher the level, the more important or severe the event.type Level int// Names for common levels.//// Level numbers are inherently arbitrary,// but we picked them to satisfy three constraints.// Any system can map them to another numbering scheme if it wishes.//// First, we wanted the default level to be Info, Since Levels are ints, Info is// the default value for int, zero.//// Second, we wanted to make it easy to use levels to specify logger verbosity.// Since a larger level means a more severe event, a logger that accepts events// with smaller (or more negative) level means a more verbose logger. Logger// verbosity is thus the negation of event severity, and the default verbosity// of 0 accepts all events at least as severe as INFO.//// Third, we wanted some room between levels to accommodate schemes with named// levels between ours. For example, Google Cloud Logging defines a Notice level// between Info and Warn. Since there are only a few of these intermediate// levels, the gap between the numbers need not be large. Our gap of 4 matches// OpenTelemetry's mapping. Subtracting 9 from an OpenTelemetry level in the// DEBUG, INFO, WARN and ERROR ranges converts it to the corresponding slog// Level range. OpenTelemetry also has the names TRACE and FATAL, which slog// does not. But those OpenTelemetry levels can still be represented as slog// Levels by using the appropriate integers.const (LevelDebug Level = -4LevelInfo Level = 0LevelWarn Level = 4LevelError Level = 8)// String returns a name for the level.// If the level has a name, then that name// in uppercase is returned.// If the level is between named values, then// an integer is appended to the uppercased name.// Examples://// LevelWarn.String() => "WARN"// (LevelInfo+2).String() => "INFO+2"func ( Level) () string {:= func( string, Level) string {if == 0 {return}return fmt.Sprintf("%s%+d", , )}switch {case < LevelInfo:return ("DEBUG", -LevelDebug)case < LevelWarn:return ("INFO", -LevelInfo)case < LevelError:return ("WARN", -LevelWarn)default:return ("ERROR", -LevelError)}}// MarshalJSON implements [encoding/json.Marshaler]// by quoting the output of [Level.String].func ( Level) () ([]byte, error) {// AppendQuote is sufficient for JSON-encoding all Level strings.// They don't contain any runes that would produce invalid JSON// when escaped.return strconv.AppendQuote(nil, .String()), nil}// UnmarshalJSON implements [encoding/json.Unmarshaler]// It accepts any string produced by [Level.MarshalJSON],// ignoring case.// It also accepts numeric offsets that would result in a different string on// output. For example, "Error-8" would marshal as "INFO".func ( *Level) ( []byte) error {, := strconv.Unquote(string())if != nil {return}return .parse()}// AppendText implements [encoding.TextAppender]// by calling [Level.String].func ( Level) ( []byte) ([]byte, error) {return append(, .String()...), nil}// MarshalText implements [encoding.TextMarshaler]// by calling [Level.AppendText].func ( Level) () ([]byte, error) {return .AppendText(nil)}// UnmarshalText implements [encoding.TextUnmarshaler].// It accepts any string produced by [Level.MarshalText],// ignoring case.// It also accepts numeric offsets that would result in a different string on// output. For example, "Error-8" would marshal as "INFO".func ( *Level) ( []byte) error {return .parse(string())}func ( *Level) ( string) ( error) {defer func() {if != nil {= fmt.Errorf("slog: level string %q: %w", , )}}():=:= 0if := strings.IndexAny(, "+-"); >= 0 {= [:], = strconv.Atoi([:])if != nil {return}}switch strings.ToUpper() {case "DEBUG":* = LevelDebugcase "INFO":* = LevelInfocase "WARN":* = LevelWarncase "ERROR":* = LevelErrordefault:return errors.New("unknown name")}* += Level()return nil}// Level returns the receiver.// It implements [Leveler].func ( Level) () Level { return }// A LevelVar is a [Level] variable, to allow a [Handler] level to change// dynamically.// It implements [Leveler] as well as a Set method,// and it is safe for use by multiple goroutines.// The zero LevelVar corresponds to [LevelInfo].type LevelVar struct {val atomic.Int64}// Level returns v's level.func ( *LevelVar) () Level {return Level(int(.val.Load()))}// Set sets v's level to l.func ( *LevelVar) ( Level) {.val.Store(int64())}func ( *LevelVar) () string {return fmt.Sprintf("LevelVar(%s)", .Level())}// AppendText implements [encoding.TextAppender]// by calling [Level.AppendText].func ( *LevelVar) ( []byte) ([]byte, error) {return .Level().AppendText()}// MarshalText implements [encoding.TextMarshaler]// by calling [LevelVar.AppendText].func ( *LevelVar) () ([]byte, error) {return .AppendText(nil)}// UnmarshalText implements [encoding.TextUnmarshaler]// by calling [Level.UnmarshalText].func ( *LevelVar) ( []byte) error {var Levelif := .UnmarshalText(); != nil {return}.Set()return nil}// A Leveler provides a [Level] value.//// As Level itself implements Leveler, clients typically supply// a Level value wherever a Leveler is needed, such as in [HandlerOptions].// Clients who need to vary the level dynamically can provide a more complex// Leveler implementation such as *[LevelVar].type Leveler interface {Level() Level}
![]() |
The pages are generated with Golds v0.7.9-preview. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |