Go 1.27 reference · Files, HTTP and Logging

Go log/slog Function

Write structured logs as key-value pairs in text or JSON, with levels and shared attributes.

Go 1.27 Since 1.21

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func New(h Handler) *Logger   func (l *Logger) Info(msg string, args ...any)

Parameters

ParameterDescription
NewJSONHandler / NewTextHandler Output format.
HandlerOptions{Level} Minimum level.
logger.With(...) Attributes on every line.
slog.Group Nested attributes.

Examples

Example 1
package main

import (
	"log/slog"
	"os"
)

// dropTime removes the timestamp so this example's output is reproducible.
func dropTime(groups []string, a slog.Attr) slog.Attr {
	if a.Key == slog.TimeKey && len(groups) == 0 {
		return slog.Attr{}
	}
	return a
}

func main() {
	opts := &slog.HandlerOptions{ReplaceAttr: dropTime}
	logger := slog.New(slog.NewJSONHandler(os.Stdout, opts)).With("service", "billing")
	logger.Info("charge created", "order", 42, "amount_cents", 1999)
	logger.Debug("not shown at the default Info level")
	logger.Warn("slow request", slog.Group("http", "path", "/pay", "ms", 1200))
}

Output

{"level":"INFO","msg":"charge created","service":"billing","order":42,"amount_cents":1999}
{"level":"WARN","msg":"slow request","service":"billing","http":{"path":"/pay","ms":1200}}

Run this on your computer — see “Get Started” for setup.

Text format with debug level
package main

import (
	"log/slog"
	"os"
)

func main() {
	opts := &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey {
			return slog.Attr{}
		}
		return a
	}}
	slog.New(slog.NewTextHandler(os.Stdout, opts)).Debug("cache miss", "key", "user:7")
}

Output

level=DEBUG msg="cache miss" key=user:7

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Go 1.21Added

Was this page helpful?