slogutil

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 8 Imported by: 0

README

go-slogutil

CI Go Reference License

Handlers, formatters, and helpers for Go's log/slog. The missing batteries

Installation

go get github.com/philiprehberger/go-slogutil

Usage

Pretty Console Output (Development)
import "github.com/philiprehberger/go-slogutil"

logger := slog.New(slogutil.PrettyHandler(os.Stderr, &slogutil.PrettyHandlerOptions{
    Level:      slog.LevelDebug,
    TimeFormat: time.DateTime,
}))
logger.Info("server started", "port", 8080)
// Output: 2026-03-15 10:30:00 INFO server started port=8080
Multi Handler (Fan-out)
console := slogutil.PrettyHandler(os.Stderr, nil)
file := slog.NewJSONHandler(logFile, nil)

logger := slog.New(slogutil.Multi(console, file))
logger.Info("logged to both console and file")
Level Routing
stdout := slog.NewTextHandler(os.Stdout, nil)
stderr := slog.NewTextHandler(os.Stderr, nil)

logger := slog.New(slogutil.LevelRoute(map[slog.Level]slog.Handler{
    slog.LevelInfo:  stdout,
    slog.LevelError: stderr,
}))
logger.Info("goes to stdout")
logger.Error("goes to stderr")
Sampling
// Log only 1 in every 100 info messages (errors are always logged).
h := slogutil.Sampling(slog.NewJSONHandler(os.Stdout, nil), 100)
logger := slog.New(h)
Attribute Helpers
logger.Info("request handled",
    slogutil.Duration(elapsed),
    slogutil.HTTPRequest(r),
    slogutil.HTTPStatus(200),
    slogutil.TraceID("abc-123"),
)

if err != nil {
    logger.Error("failed", slogutil.Error(err))
}
Domain Attributes
import slogutil "github.com/philiprehberger/go-slogutil"

logger.Info("query complete",
    slogutil.Database("users", "localhost", 5432),
    slogutil.UserID("user-123"),
    slogutil.RequestID("req-abc"),
    slogutil.Latency(42 * time.Millisecond),
)

API

Function / Type Description
PrettyHandler(w, opts) Colorized console handler for development
PrettyHandlerOptions Options: Level, TimeFormat
Multi(handlers...) Fan-out to multiple handlers
LevelRoute(routes) Route records by level to different handlers
Sampling(handler, rate) Log 1 in every N records (errors always pass)
Duration(d) Formatted duration attr
Error(err) Error attr with "error" key
HTTPRequest(r) Group attr with method, path, remote_addr
HTTPStatus(code) Status code attr
TraceID(id) Trace ID attr
Stringer(key, v) Attr from any fmt.Stringer
Database(name, host, port) Group attr with database connection details
UserID(id) User identifier attr
RequestID(id) Request identifier attr
Latency(d) Latency in milliseconds attr

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package slogutil provides handlers, formatters, and helpers for log/slog.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Database added in v0.2.0

func Database(name, host string, port int) slog.Attr

Database returns an attribute group with database connection details.

func Duration

func Duration(d time.Duration) slog.Attr

Duration returns a slog.Attr with key "duration" and a human-readable string representation of d (e.g. "1.5s", "200ms").

func Error

func Error(err error) slog.Attr

Error returns a slog.Attr with key "error" and the error message as value. If err is nil, the attr value is "<nil>".

func HTTPRequest

func HTTPRequest(r *http.Request) slog.Attr

HTTPRequest returns a slog.Attr group named "http_request" containing the method, path, and remote address from the given request.

func HTTPStatus

func HTTPStatus(code int) slog.Attr

HTTPStatus returns a slog.Attr with key "status" and the HTTP status code as an integer value.

func Latency added in v0.2.0

func Latency(d time.Duration) slog.Attr

Latency returns an attribute with a latency duration in milliseconds.

func LevelRoute

func LevelRoute(routes map[slog.Level]slog.Handler) slog.Handler

LevelRoute returns a slog.Handler that routes records to different handlers based on the log level. If an exact level match is not found in routes, it falls back to the next lower level's handler. If no handler matches, the record is silently dropped.

Common usage routes errors to a stderr handler and info messages to stdout:

slog.New(slogutil.LevelRoute(map[slog.Level]slog.Handler{
    slog.LevelInfo:  stdoutHandler,
    slog.LevelError: stderrHandler,
}))

func Multi

func Multi(handlers ...slog.Handler) slog.Handler

Multi returns a slog.Handler that fans out log records to all provided handlers. Enabled returns true if any underlying handler is enabled for the given level. Handle sends each record to every handler; the first error encountered is returned.

func PrettyHandler

func PrettyHandler(w io.Writer, opts *PrettyHandlerOptions) slog.Handler

PrettyHandler returns a new slog.Handler that writes colorized, human-readable log lines to w. It is intended for development console output.

func RequestID added in v0.2.0

func RequestID(id string) slog.Attr

RequestID returns an attribute with a request identifier.

func Sampling

func Sampling(handler slog.Handler, rate int) slog.Handler

Sampling returns a slog.Handler that only passes 1 in every rate records to the underlying handler. This is useful for high-volume code paths where logging every event would be too expensive. Records at slog.LevelError or above are always logged regardless of the sampling rate. The counter is incremented atomically and is safe for concurrent use.

func Stringer

func Stringer(key string, v fmt.Stringer) slog.Attr

Stringer returns a slog.Attr with the given key and the result of calling String() on v. This is a convenience for types that implement fmt.Stringer.

func TraceID

func TraceID(id string) slog.Attr

TraceID returns a slog.Attr with key "trace_id" and the given trace identifier as a string value.

func UserID added in v0.2.0

func UserID(id string) slog.Attr

UserID returns an attribute with a user identifier.

Types

type PrettyHandlerOptions

type PrettyHandlerOptions struct {
	// Level is the minimum level to log. If nil, defaults to slog.LevelInfo.
	Level slog.Leveler

	// TimeFormat is the time layout string. If empty, defaults to time.DateTime.
	TimeFormat string
}

PrettyHandlerOptions configures the PrettyHandler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL