humane

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2025 License: BSD-3-Clause Imports: 12 Imported by: 3

Documentation

Overview

Package humane provides a log/slog.Handler for a human-friendly version of logfmt. The idea for this format comes from Brandur Leach in his original post about logfmt. (In particular, this is the inspiration.)

Examples:

1. Get a slog logger using humane's handler with default options:

logger := slog.New(humane.NewHandler(os.Stdout, nil))
logger.Info("Message", "foo", "bar", "bizz", "buzz")

2. Get a slog logger using humane's handler with customized options:

func trimSource(_ []string, a slog.Attr) slog.Attr {
	if a.Key == slog.SourceKey {
		return slog.String(
			slog.SourceKey,
			filepath.Base(a.Value.String()),
		)
	}
	return a
}

func main() {
	opts := &humane.Options{
		Level:       slog.LevelError,
		ReplaceAttr: trimSource,
		TimeFormat:  time.Kitchen,
		AddSource:   true,
	}
	logger := slog.New(humane.NewHandler(os.Stderr, opts))
	// ... later
	logger.Error("Message", "error", err, "response", respStatus)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHandler

func NewHandler(w io.Writer, opts *Options) slog.Handler

NewHandler returns a log/slog.Handler using the receiver's options. Default options are used if opts is nil.

Types

type Options

type Options struct {
	Level       slog.Leveler
	ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
	TimeFormat  string
	AddSource   bool
}

Options are options for Humane's log/slog.Handler.

Level sets the minimum level to log. Humane uses log/slog.LevelInfo as its default. In order to set a different level, use one of the built-in choices for log/slog.Level or implement a log/slog.Leveler.

ReplaceAttr is a user-defined function that receives each non-group Attr before it is logged. The first argument is a slice of groups that contain the Attr. This slice is read-only; do not retain or modify it. By default, ReplaceAttr is nil, and no changes are made to Attrs. Note: Humane's handler does not apply ReplaceAttr to the level or message Attrs because the handler already formats these items in a specific way. However, Humane does apply ReplaceAttr to the time Attr (unless it's zero) and to the source Attr if AddSource is true.

TimeFormat defaults to "2006-01-02T03:04.05 MST". Set a format option to customize the presentation of the time. (See time.Time.Format for details about the format string.)

AddSource defaults to false. If AddSource is true, the handler adds to each log event an Attr with a key of log/slog.SourceKey and a value of "/path/to/file:line".

Directories

Path Synopsis
internal
pooled
Package pooled provides pool-allocated types.
Package pooled provides pool-allocated types.

Jump to

Keyboard shortcuts

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