Keys for "built-in" attributes.
const ( // TimeKey is the key used by the built-in handlers for the time // when the log method is called. The associated Value is a [time.Time]. TimeKey = "time" // LevelKey is the key used by the built-in handlers for the level // of the log call. The associated value is a [Level]. LevelKey = "level" // MessageKey is the key used by the built-in handlers for the // message of the log call. The associated value is a string. MessageKey = "msg" // SourceKey is the key used by the built-in handlers for the source file // and line of the log call. The associated value is a *[Source]. SourceKey = "source" )
func Debug(msg string, args ...any)
Debug calls Logger.Debug on the default logger.
func DebugContext(ctx context.Context, msg string, args ...any)
DebugContext calls Logger.DebugContext on the default logger.
func Error(msg string, args ...any)
Error calls Logger.Error on the default logger.
func ErrorContext(ctx context.Context, msg string, args ...any)
ErrorContext calls Logger.ErrorContext on the default logger.
func Info(msg string, args ...any)
Info calls Logger.Info on the default logger.
func InfoContext(ctx context.Context, msg string, args ...any)
InfoContext calls Logger.InfoContext on the default logger.
func Log(ctx context.Context, level Level, msg string, args ...any)
Log calls Logger.Log on the default logger.
func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogAttrs calls Logger.LogAttrs on the default logger.
func NewLogLogger(h Handler, level Level) *log.Logger
NewLogLogger returns a new log.Logger such that each call to its Output method dispatches a Record to the specified handler. The logger acts as a bridge from the older log API to newer structured logging handlers.
func SetDefault(l *Logger)
SetDefault makes l the default Logger, which is used by the top-level functions Info, Debug and so on. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged using l's Handler, at a level controlled by SetLogLoggerLevel.
func Warn(msg string, args ...any)
Warn calls Logger.Warn on the default logger.
func WarnContext(ctx context.Context, msg string, args ...any)
WarnContext calls Logger.WarnContext on the default logger.
An Attr is a key-value pair.
type Attr struct { Key string Value Value }
func Any(key string, value any) Attr
Any returns an Attr for the supplied value. See AnyValue for how values are treated.
func Bool(key string, v bool) Attr
Bool returns an Attr for a bool.
func Duration(key string, v time.Duration) Attr
Duration returns an Attr for a time.Duration.
func Float64(key string, v float64) Attr
Float64 returns an Attr for a floating-point number.
func Group(key string, args ...any) Attr
Group returns an Attr for a Group Value. The first argument is the key; the remaining arguments are converted to Attrs as in Logger.Log.
Use Group to collect several key-value pairs under a single key on a log line, or as the result of LogValue in order to log a single value as multiple Attrs.
▹ Example
func Int(key string, value int) Attr
Int converts an int to an int64 and returns an Attr with that value.
func Int64(key string, value int64) Attr
Int64 returns an Attr for an int64.
func String(key, value string) Attr
String returns an Attr for a string value.
func Time(key string, v time.Time) Attr
Time returns an Attr for a time.Time. It discards the monotonic portion.
func Uint64(key string, v uint64) Attr
Uint64 returns an Attr for a uint64.
func (a Attr) Equal(b Attr) bool
Equal reports whether a and b have equal keys and values.
func (a Attr) String() string
A Handler handles log records produced by a Logger.
A typical handler may print log records to standard error, or write them to a file or database, or perhaps augment them with additional attributes and pass them on to another handler.
Any of the Handler's methods may be called concurrently with itself or with other methods. It is the responsibility of the Handler to manage this concurrency.
Users of the slog package should not invoke Handler methods directly. They should use the methods of Logger instead.
type Handler interface { // Enabled reports whether the handler handles records at the given level. // The handler ignores records whose level is lower. // It is called early, before any arguments are processed, // to save effort if the log event should be discarded. // If called from a Logger method, the first argument is the context // passed to that method, or context.Background() if nil was passed // or the method does not take a context. // The context is passed so Enabled can use its values // to make a decision. Enabled(context.Context, Level) bool // Handle handles the Record. // It will only be called when Enabled returns true. // The Context argument is as for Enabled. // It is present solely to provide Handlers access to the context's values. // Canceling the context should not affect record processing. // (Among other things, log messages may be necessary to debug a // cancellation-related problem.) // // Handle methods that produce output should observe the following rules: // - If r.Time is the zero time, ignore the time. // - If r.PC is zero, ignore it. // - Attr's values should be resolved. // - If an Attr's key and value are both the zero value, ignore the Attr. // This can be tested with attr.Equal(Attr{}). // - If a group's key is empty, inline the group's Attrs. // - If a group has no Attrs (even if it has a non-empty key), // ignore it. Handle(context.Context, Record) error // WithAttrs returns a new Handler whose attributes consist of // both the receiver's attributes and the arguments. // The Handler owns the slice: it may retain, modify or discard it. WithAttrs(attrs []Attr) Handler // WithGroup returns a new Handler with the given group appended to // the receiver's existing groups. // The keys of all subsequent attributes, whether added by With or in a // Record, should be qualified by the sequence of group names. // // How this qualification happens is up to the Handler, so long as // this Handler's attribute keys differ from those of another Handler // with a different sequence of group names. // // A Handler should treat WithGroup as starting a Group of Attrs that ends // at the end of the log event. That is, // // logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2)) // // should behave like // // logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) // // If the name is empty, WithGroup returns the receiver. WithGroup(name string) Handler }
▹ Example (LevelHandler)
HandlerOptions are options for a TextHandler or JSONHandler. A zero HandlerOptions consists entirely of default values.
type HandlerOptions struct { // AddSource causes the handler to compute the source code position // of the log statement and add a SourceKey attribute to the output. AddSource bool // Level reports the minimum record level that will be logged. // The handler discards records with lower levels. // If Level is nil, the handler assumes LevelInfo. // The handler calls Level.Level for each record processed; // to adjust the minimum level dynamically, use a LevelVar. Level Leveler // ReplaceAttr is called to rewrite each non-group attribute before it is logged. // The attribute's value has been resolved (see [Value.Resolve]). // If ReplaceAttr returns a zero Attr, the attribute is discarded. // // The built-in attributes with keys "time", "level", "source", and "msg" // are passed to this function, except that time is omitted // if zero, and source is omitted if AddSource is false. // // The first argument is a list of currently open groups that contain the // Attr. It must not be retained or modified. ReplaceAttr is never called // for Group attributes, only their contents. For example, the attribute // list // // Int("a", 1), Group("g", Int("b", 2)), Int("c", 3) // // results in consecutive calls to ReplaceAttr with the following arguments: // // nil, Int("a", 1) // []string{"g"}, Int("b", 2) // nil, Int("c", 3) // // ReplaceAttr can be used to change the default keys of the built-in // attributes, convert types (for example, to replace a `time.Time` with the // integer seconds since the Unix epoch), sanitize personal information, or // remove attributes from the output. ReplaceAttr func(groups []string, a Attr) Attr }
▹ Example (CustomLevels)
JSONHandler is a Handler that writes Records to an io.Writer as line-delimited JSON objects.
type JSONHandler struct {
// contains filtered or unexported fields
}
func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
NewJSONHandler creates a JSONHandler that writes to w, using the given options. If opts is nil, the default options are used.
func (h *JSONHandler) Enabled(_ context.Context, level Level) bool
Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.
func (h *JSONHandler) Handle(_ context.Context, r Record) error
Handle formats its argument Record as a JSON object on a single line.
If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output as with json.Marshal.
If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.
If the AddSource option is set and source information is available, the key is "source", and the value is a record of type Source.
The message's key is "msg".
To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].
Values are formatted as with an encoding/json.Encoder with SetEscapeHTML(false), with two exceptions.
First, an Attr whose Value is of type error is formatted as a string, by calling its Error method. Only errors in Attrs receive this special treatment, not errors embedded in structs, slices, maps or other data structures that are processed by the encoding/json package.
Second, an encoding failure does not cause Handle to return an error. Instead, the error message is formatted as a string.
Each call to Handle results in a single serialized call to io.Writer.Write.
func (h *JSONHandler) WithAttrs(attrs []Attr) Handler
WithAttrs returns a new JSONHandler whose attributes consists of h's attributes followed by attrs.
func (h *JSONHandler) WithGroup(name string) Handler
Kind is the kind of a Value.
type Kind int
const ( KindAny Kind = iota KindBool KindDuration KindFloat64 KindInt64 KindString KindTime KindUint64 KindGroup KindLogValuer )
func (k Kind) String() string
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 = -4 LevelInfo Level = 0 LevelWarn Level = 4 LevelError Level = 8 )
func SetLogLoggerLevel(level Level) (oldLevel Level)
SetLogLoggerLevel controls the level for the bridge to the log package.
Before SetDefault is called, slog top-level logging functions call the default log.Logger. In that mode, SetLogLoggerLevel sets the minimum level for those calls. By default, the minimum level is Info, so calls to Debug (as well as top-level logging calls at lower levels) will not be passed to the log.Logger. After calling
slog.SetLogLoggerLevel(slog.LevelDebug)
calls to Debug will be passed to the log.Logger.
After SetDefault is called, calls to the default log.Logger are passed to the slog default handler. In that mode, SetLogLoggerLevel sets the level at which those calls are logged. That is, after calling
slog.SetLogLoggerLevel(slog.LevelDebug)
A call to log.Printf will result in output at level LevelDebug.
SetLogLoggerLevel returns the previous value.
▹ Example (Log)
▹ Example (Slog)
func (l Level) Level() Level
Level returns the receiver. It implements Leveler.
func (l Level) MarshalJSON() ([]byte, error)
MarshalJSON implements encoding/json.Marshaler by quoting the output of Level.String.
func (l Level) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler by calling Level.String.
func (l Level) String() string
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 (l *Level) UnmarshalJSON(data []byte) error
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 (l *Level) UnmarshalText(data []byte) error
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".
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 {
// contains filtered or unexported fields
}
func (v *LevelVar) Level() Level
Level returns v's level.
func (v *LevelVar) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.
func (v *LevelVar) Set(l Level)
Set sets v's level to l.
func (v *LevelVar) String() string
func (v *LevelVar) UnmarshalText(data []byte) error
UnmarshalText implements encoding.TextUnmarshaler by calling Level.UnmarshalText.
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 }
A LogValuer is any Go value that can convert itself into a Value for logging.
This mechanism may be used to defer expensive operations until they are needed, or to expand a single value into a sequence of components.
type LogValuer interface { LogValue() Value }
▹ Example (Group)
▹ Example (Secret)
A Logger records structured information about each call to its Log, Debug, Info, Warn, and Error methods. For each call, it creates a Record and passes it to a Handler.
To create a new Logger, call New or a Logger method that begins "With".
type Logger struct {
// contains filtered or unexported fields
}
func Default() *Logger
Default returns the default Logger.
func New(h Handler) *Logger
New creates a new Logger with the given non-nil Handler.
func With(args ...any) *Logger
With calls Logger.With on the default logger.
func (l *Logger) Debug(msg string, args ...any)
Debug logs at LevelDebug.
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
DebugContext logs at LevelDebug with the given context.
func (l *Logger) Enabled(ctx context.Context, level Level) bool
Enabled reports whether l emits log records at the given context and level.
func (l *Logger) Error(msg string, args ...any)
Error logs at LevelError.
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
ErrorContext logs at LevelError with the given context.
func (l *Logger) Handler() Handler
Handler returns l's Handler.
func (l *Logger) Info(msg string, args ...any)
Info logs at LevelInfo.
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
InfoContext logs at LevelInfo with the given context.
func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
Log emits a log record with the current time and the given level and message. The Record's Attrs consist of the Logger's attributes followed by the Attrs specified by args.
The attribute arguments are processed as follows:
func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
LogAttrs is a more efficient version of Logger.Log that accepts only Attrs.
func (l *Logger) Warn(msg string, args ...any)
Warn logs at LevelWarn.
func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
WarnContext logs at LevelWarn with the given context.
func (l *Logger) With(args ...any) *Logger
With returns a Logger that includes the given attributes in each output operation. Arguments are converted to attributes as if by Logger.Log.
func (l *Logger) WithGroup(name string) *Logger
WithGroup returns a Logger that starts a group, if name is non-empty. The keys of all attributes added to the Logger will be qualified by the given name. (How that qualification happens depends on the [Handler.WithGroup] method of the Logger's Handler.)
If name is empty, WithGroup returns the receiver.
A Record holds information about a log event. Copies of a Record share state. Do not modify a Record after handing out a copy to it. Call NewRecord to create a new Record. Use Record.Clone to create a copy with no shared state.
type Record struct { // The time at which the output method (Log, Info, etc.) was called. Time time.Time // The log message. Message string // The level of the event. Level Level // The program counter at the time the record was constructed, as determined // by runtime.Callers. If zero, no program counter is available. // // The only valid use for this value is as an argument to // [runtime.CallersFrames]. In particular, it must not be passed to // [runtime.FuncForPC]. PC uintptr // contains filtered or unexported fields }
func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record
NewRecord creates a Record from the given arguments. Use Record.AddAttrs to add attributes to the Record.
NewRecord is intended for logging APIs that want to support a Handler as a backend.
func (r *Record) Add(args ...any)
Add converts the args to Attrs as described in Logger.Log, then appends the Attrs to the Record's list of Attrs. It omits empty groups.
func (r *Record) AddAttrs(attrs ...Attr)
AddAttrs appends the given Attrs to the Record's list of Attrs. It omits empty groups.
func (r Record) Attrs(f func(Attr) bool)
Attrs calls f on each Attr in the Record. Iteration stops if f returns false.
func (r Record) Clone() Record
Clone returns a copy of the record with no shared state. The original record and the clone can both be modified without interfering with each other.
func (r Record) NumAttrs() int
NumAttrs returns the number of attributes in the Record.
Source describes the location of a line of source code.
type Source struct { // Function is the package path-qualified function name containing the // source line. If non-empty, this string uniquely identifies a single // function in the program. This may be the empty string if not known. Function string `json:"function"` // File and Line are the file name and line number (1-based) of the source // line. These may be the empty string and zero, respectively, if not known. File string `json:"file"` Line int `json:"line"` }
TextHandler is a Handler that writes Records to an io.Writer as a sequence of key=value pairs separated by spaces and followed by a newline.
type TextHandler struct {
// contains filtered or unexported fields
}
func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
NewTextHandler creates a TextHandler that writes to w, using the given options. If opts is nil, the default options are used.
func (h *TextHandler) Enabled(_ context.Context, level Level) bool
Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.
func (h *TextHandler) Handle(_ context.Context, r Record) error
Handle formats its argument Record as a single line of space-separated key=value items.
If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output in RFC3339 format with millisecond precision.
If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.
If the AddSource option is set and source information is available, the key is "source" and the value is output as FILE:LINE.
The message's key is "msg".
To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].
If a value implements encoding.TextMarshaler, the result of MarshalText is written. Otherwise, the result of fmt.Sprint is written.
Keys and values are quoted with strconv.Quote if they contain Unicode space characters, non-printing characters, '"' or '='.
Keys inside groups consist of components (keys or group names) separated by dots. No further escaping is performed. Thus there is no way to determine from the key "a.b.c" whether there are two groups "a" and "b" and a key "c", or a single group "a.b" and a key "c", or single group "a" and a key "b.c". If it is necessary to reconstruct the group structure of a key even in the presence of dots inside components, use [HandlerOptions.ReplaceAttr] to encode that information in the key.
Each call to Handle results in a single serialized call to io.Writer.Write.
func (h *TextHandler) WithAttrs(attrs []Attr) Handler
WithAttrs returns a new TextHandler whose attributes consists of h's attributes followed by attrs.
func (h *TextHandler) WithGroup(name string) Handler
A Value can represent any Go value, but unlike type any, it can represent most small values without an allocation. The zero Value corresponds to nil.
type Value struct {
// contains filtered or unexported fields
}
func AnyValue(v any) Value
AnyValue returns a Value for the supplied value.
If the supplied value is of type Value, it is returned unmodified.
Given a value of one of Go's predeclared string, bool, or (non-complex) numeric types, AnyValue returns a Value of kind KindString, KindBool, KindUint64, KindInt64, or KindFloat64. The width of the original numeric type is not preserved.
Given a time.Time or time.Duration value, AnyValue returns a Value of kind KindTime or KindDuration. The monotonic time is not preserved.
For nil, or values of all other types, including named types whose underlying type is numeric, AnyValue returns a value of kind KindAny.
func BoolValue(v bool) Value
BoolValue returns a Value for a bool.
func DurationValue(v time.Duration) Value
DurationValue returns a Value for a time.Duration.
func Float64Value(v float64) Value
Float64Value returns a Value for a floating-point number.
func GroupValue(as ...Attr) Value
GroupValue returns a new Value for a list of Attrs. The caller must not subsequently mutate the argument slice.
func Int64Value(v int64) Value
Int64Value returns a Value for an int64.
func IntValue(v int) Value
IntValue returns a Value for an int.
func StringValue(value string) Value
StringValue returns a new Value for a string.
func TimeValue(v time.Time) Value
TimeValue returns a Value for a time.Time. It discards the monotonic portion.
func Uint64Value(v uint64) Value
Uint64Value returns a Value for a uint64.
func (v Value) Any() any
Any returns v's value as an any.
func (v Value) Bool() bool
Bool returns v's value as a bool. It panics if v is not a bool.
func (v Value) Duration() time.Duration
Duration returns v's value as a time.Duration. It panics if v is not a time.Duration.
func (v Value) Equal(w Value) bool
Equal reports whether v and w represent the same Go value.
func (v Value) Float64() float64
Float64 returns v's value as a float64. It panics if v is not a float64.
func (v Value) Group() []Attr
Group returns v's value as a []Attr. It panics if v's Kind is not KindGroup.
func (v Value) Int64() int64
Int64 returns v's value as an int64. It panics if v is not a signed integer.
func (v Value) Kind() Kind
Kind returns v's Kind.
func (v Value) LogValuer() LogValuer
LogValuer returns v's value as a LogValuer. It panics if v is not a LogValuer.
func (v Value) Resolve() (rv Value)
Resolve repeatedly calls LogValue on v while it implements LogValuer, and returns the result. If v resolves to a group, the group's attributes' values are not recursively resolved. If the number of LogValue calls exceeds a threshold, a Value containing an error is returned. Resolve's return value is guaranteed not to be of Kind KindLogValuer.
func (v Value) String() string
String returns Value's value as a string, formatted like fmt.Sprint. Unlike the methods Int64, Float64, and so on, which panic if v is of the wrong kind, String never panics.
func (v Value) Time() time.Time
Time returns v's value as a time.Time. It panics if v is not a time.Time.
func (v Value) Uint64() uint64
Uint64 returns v's value as a uint64. It panics if v is not an unsigned integer.
Name | Synopsis |
---|---|
.. |