slogor

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 11 Imported by: 33

README

Slogor - A colorful slog handler

Slogor is a slog.Handler that writes colorful, human-readable logs to any io.Writer. It stays close to the standard library's own TextHandler in both behavior and output shape, so it's a drop-in replacement for local development and small services that don't need structured JSON.

slogor demo

✨ Features

  • 🚀 Fast and memory efficient: buffers are pooled, and attributes attached via With/WithGroup are rendered once and reused, not re-formatted on every log line
  • 🧑‍💻 Standard slog semantics: nested slog.Group, ReplaceAttr, LogValuer resolution and quoting all match slog.TextHandler
  • 🎉 Safe for concurrent use, including deriving many loggers from a shared base logger at once
  • 🌈 ANSI colored, with automatic Windows console support
  • ✅ Dependency free on every platform except Windows
  • ♻️ Customizable writer, level, time format, level strings and attribute rewriting
  • 🔧 Optional caller location (dir/file.go:line) per record

📦 Install

go get gitlab.com/greyxor/slogor

❓ Usage

package main

import (
	"log/slog"
	"os"
	"time"

	"gitlab.com/greyxor/slogor"
)

func main() {
	slog.SetDefault(slog.New(slogor.NewHandler(os.Stderr,
		slogor.SetLevel(slog.LevelDebug),
		slogor.SetTimeFormat(time.Stamp),
		slogor.ShowSource(),
	)))

	slog.Info("service started", slog.String("env", "production"))
	slog.Warn("cache miss", slog.String("key", "user:42"))

	logger := slog.With(slog.String("request_id", "8f3e1c"))
	logger.Error("request failed", slogor.Err(os.ErrDeadlineExceeded))
}

⚙️ Options

Pass any of these to slogor.NewHandler(w, ...):

Option Description Default
SetLevel(lvl slog.Leveler) Minimum level handled. Pass a *slog.LevelVar to change it at runtime (see below). slog.LevelInfo
SetTimeFormat(format string) Layout for the timestamp, e.g. time.Kitchen. An empty string hides it. hidden
ShowSource() Prefix each record with dir/file.go:line. disabled
SetLevelStr(m slogor.MapOfLevel) Override the strings used for each level. DEBUG/INFO /WARN /ERROR
SetReplaceAttr(fn) Rewrite or drop attributes before they're logged - same contract as slog.HandlerOptions.ReplaceAttr. none
DisableColor() Disable ANSI colors. colors enabled
Changing the level at runtime

SetLevel accepts any slog.Leveler, so passing a *slog.LevelVar instead of a plain slog.Level lets you change the minimum level after the handler has been built, from any goroutine:

level := new(slog.LevelVar) // defaults to slog.LevelInfo
logger := slog.New(slogor.NewHandler(os.Stderr, slogor.SetLevel(level)))

// later, e.g. when a config value or CLI flag changes:
level.Set(slog.LevelDebug)
Redacting or rewriting attributes

SetReplaceAttr is called for the built-in time/level/source/msg attributes as well as user-supplied ones (never for Group attributes themselves, though it is called for their contents), and can drop an attribute entirely by returning a zero slog.Attr:

slogor.SetReplaceAttr(func(groups []string, a slog.Attr) slog.Attr {
	if a.Key == "password" {
		return slog.String(a.Key, "REDACTED")
	}
	return a
})

🧪 Testing

go test ./...                    # run the test suite
go test ./... -race              # ... with the race detector
go test ./... -cover             # ... with a coverage summary
go test ./... -bench=. -benchmem # run benchmarks with allocation stats

👷 Thanks to contributors

Documentation

Overview

Package slogor provides a colorful, allocation-conscious slog.Handler close in spirit to log/slog's own TextHandler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Err

func Err(err error) slog.Attr

Err creates a slog.Attr wrapping err under the "err" key.

Types

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler is a slog.Handler that writes Records to an io.Writer as a sequence of colorful time, level, source, message and key=value pairs separated by spaces and followed by a newline. A Handler is safe for concurrent use by multiple goroutines, including concurrent calls to Handle, WithAttrs and WithGroup.

func NewHandler

func NewHandler(w io.Writer, fns ...OptionFn) *Handler

NewHandler creates a Handler that writes to w with the provided Options.

func (*Handler) Enabled

func (h *Handler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

func (*Handler) Handle

func (h *Handler) Handle(_ context.Context, record slog.Record) error

Handle processes the log record and writes it to the writer with appropriate formatting.

func (*Handler) WithAttrs

func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new handler with attrs rendered once and prepended to every subsequent record it handles.

func (*Handler) WithGroup

func (h *Handler) WithGroup(name string) slog.Handler

WithGroup returns a new handler in which subsequent attributes are nested under the given group name via a dot-joined key prefix.

type MapOfLevel added in v1.5.0

type MapOfLevel = map[slog.Level]string

MapOfLevel maps a slog.Level to the exact string used to render it. Levels not present in the map fall back to a "BASE+N"/"BASE-N" form derived from the nearest standard level, mirroring slog.Level.String.

type OptionFn added in v1.5.0

type OptionFn func(*options)

OptionFn configures a Handler. See NewHandler.

func DisableColor added in v1.5.0

func DisableColor() OptionFn

DisableColor disables ANSI color output.

func SetLevel added in v1.5.0

func SetLevel(lvl slog.Leveler) OptionFn

SetLevel sets the minimum log level to handle. By default, level INFO is set.

func SetLevelStr added in v1.5.0

func SetLevelStr(strLvl MapOfLevel) OptionFn

SetLevelStr sets the handler's level-to-string map. The default map is used if none is specified.

func SetReplaceAttr added in v1.7.0

func SetReplaceAttr(fn replaceAttrFunc) OptionFn

SetReplaceAttr sets a function to rewrite or drop attributes before they're logged, following the same contract as slog.HandlerOptions.ReplaceAttr. It is called for the built-in time, level, source and msg attributes as well as for user-supplied ones, but never for Group attributes (it is however called for their contents). Returning a zero slog.Attr drops the attribute.

func SetTimeFormat added in v1.5.0

func SetTimeFormat(format string) OptionFn

SetTimeFormat specifies the time format for the log records. By default, nothing is reported.

func ShowSource added in v1.5.0

func ShowSource() OptionFn

ShowSource indicates whether to display the source of the log records. By default, nothing is reported.

Jump to

Keyboard shortcuts

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