/devslog

Developing handler for Go's log/slog

Primary LanguageGoMIT LicenseMIT

🧻 devslog - slog.Handler for developing code

License: MIT Go Report Card Go Reference

devslog is zero dependency custom logging handler for Go's standard log/slog package that provides structured logging with colorful and indented structure for developing.

Develop with this output

image

Instead of these outputs

TextHandler image JSONHandler image

Install

go get github.com/golang-cz/devslog@latest

Examples

Logger without options

w := os.Stdout

logger := slog.New(devslog.NewHandler(w, nil))

// set global logger
slog.SetDefault(logger)

Logger with custom options

w := os.Stdout

// new logger with options
opts := &devslog.Options{
	MaxSlicePrintSize: 4,
	SortKeys:          true,
	TimeFormat:        "[06:05]"
}

logger := slog.New(devslog.NewHandler(w, opts))

// optional: set global logger
slog.SetDefault(logger)

Logger with default slog options

Handler accept default slog.HandlerOptions

w := os.Stdout

// slog.HandlerOptions
slogOpts := &slog.HandlerOptions{
	AddSource:   true,
	Level:       slog.LevelDebug,
}

// new logger with options
opts := &devslog.Options{
	HandlerOptions:    slogOpts,
	MaxSlicePrintSize: 4,
	SortKeys:          true,
}

logger := slog.New(devslog.NewHandler(w, opts))

// optional: set global logger
slog.SetDefault(logger)

Example of initialization with production

production := false

w := os.Stdout

slogOpts := &slog.HandlerOptions{
	AddSource: true,
	Level:     slog.LevelDebug,
}

var logger *slog.Logger
if production {
	logger = slog.New(slog.NewJSONHandler(w, slogOpts))
} else {
	opts := &devslog.Options{
		HandlerOptions:    slogOpts,
		MaxSlicePrintSize: 10,
		SortKeys:          true,
	}

	logger = slog.New(devslog.NewHandler(w, opts))
}

// optional: set global logger
slog.SetDefault(logger)

Options

Parameter Description Default Value
MaxSlicePrintSize Specifies the maximum number of elements to print for a slice. 50 uint
SortKeys Determines if attributes should be sorted by keys. false bool
TimeFormat Time format for timestamp. "[15:06:05]" string