Go Reference ยท Logging, Flags and Testing
Go log/slog package
Reference for Go log/slog: Logger, TextHandler, JSONHandler, levels, attributes, groups, With, ReplaceAttr, LogValuer and custom handlers for structured logs.
The package log/slog (added in Go 1.21) is the standard structured logger. Instead of one formatted sentence, each record has a time, a level, a message and any number of key-value attributes. A handler turns the record into text (key=value pairs) or JSON, so tools can filter and search by field.
You usually create one *slog.Logger with a handler, optionally make it the default with slog.SetDefault, and then call Info, Warn, Error or Debug with a message followed by alternating keys and values or typed slog.Attr values.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) logger.Info("user signed in", "user_id", 42, "method", "password")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func New(h Handler) *Logger func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler func SetDefault(l *Logger) func Default() *Logger func (l *Logger) Debug(msg string, args ...any) // also Info, Warn, Error func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) func (l *Logger) With(args ...any) *Logger func (l *Logger) WithGroup(name string) *Logger func (l *Logger) Enabled(ctx context.Context, level Level) bool type HandlerOptions struct { AddSource bool Level Leveler ReplaceAttr func(groups []string, a Attr) Attr }
| Name | Description |
|---|---|
Level |
LevelDebug (-4), LevelInfo (0), LevelWarn (4), LevelError (8). Any integer is allowed. |
args |
Alternating key and value, or slog.Attr values mixed in. |
HandlerOptions.Level |
Minimum level, a Level or a *LevelVar that you can change at runtime. Default is Info. |
ReplaceAttr |
Called for every attribute (also time, level, msg, source) to rename, edit or drop it. Return an empty Attr to drop. |
Edge cases: a key without a value is logged under the key !BADKEY. A handler with AddSource: true adds the call site (source=main.go:12). Since Go 1.24, slog.DiscardHandler drops everything.
Usage notes
- Typed attributes avoid mistakes.
slog.Int,String,Bool,Duration,Time,AnyandGroupcannot be misordered the way a loose"key", valuelist can, andLogAttrsavoids allocation in hot paths. Withis for context. Attach a request ID or component once, and every record from the derived logger carries it. A logger is immutable, soWithreturns a new one.- Groups nest keys: text output shows
db.table=users, JSON shows an object. - Redaction. Implement
LogValueron types holding secrets, or drop keys inReplaceAttr. - Dynamic levels. Use
slog.LevelVarto change verbosity without restarting. - Context variants (
InfoContext) pass the context to the handler, which can pull trace IDs from it. The standard handlers ignore it. - Bridging.
slog.SetDefaultalso routes the oldlogpackage through the handler.slog.NewLogLogger(handler, level)gives a*log.Loggerfor APIs such ashttp.Server.ErrorLog. - Custom handlers implement
Enabled,Handle,WithAttrsandWithGroup. Writing one correctly (especially groups) is subtle; wrap an existing handler when you can.
Related
- log, context and encoding/json
- Stringer
- Tutorial: Logging