log

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 14 Imported by: 0

README

log logo

LOG

A fast, zero-allocation slog handler for Go CLIs

CI Go Reference License

Table of contents

Overview

nekrassov01/log provides CLIHandler, a log/slog handler for readable CLI output. Use it with slog.Logger to display messages, attributes, and groups with compact level labels. Colors are enabled automatically for terminals and omitted for files and pipes.

The visual style is inspired by charmbracelet/log.

Features

CLI-focused output with structured logging support:

  • Native log/slog integration
  • Zero-allocation hot paths
  • Terminal-aware colors with Windows support
  • Custom styles and log levels
  • Nested attributes and selective redaction
  • Concurrent-safe handler and derived loggers

Installation

Install with:

go get github.com/nekrassov01/log@latest

Quick start

Use the default style to show CLI execution details alongside timestamps, source functions, and a label:

package main

import (
	"log/slog"
	"os"

	"github.com/nekrassov01/log"
)

func main() {
	handler := log.NewCLIHandler(os.Stdout,
		log.WithTime(),
		log.WithLevel(slog.LevelDebug),
		log.WithSourceFunction(),
		log.WithLabel("DEFAULT STYLE:"),
	)
	logger := slog.New(handler).
		WithGroup("default").
		With(
			slog.String("version", "1.0.0"),
			slog.String("command", "build"),
		)
	logger.Debug("debug message")
	logger.Info("info message")
	logger.Warn("warn message")
	logger.Error("error message")
}

The default-style output from examples/main.go, shown on dark and light backgrounds:

Four log levels with CLI command details on a dark background

Four log levels with CLI command details on a light background

The default minimum level is INFO. Time, source, and label output are opt-in. The default output contains the level, message, and any attributes.

Customization

Configure output, appearance, and attribute replacement through separate options:

  • Add WithTime(), WithSourceFunction() or WithSourcePath(), and WithLabel() for context. Use CLIHandler.WithLabel() to derive a handler with a different label.
  • Use WithStyle(NewStyle(...)) to customize colors, affixes, and attribute separators, along with level text and alignment.
  • Use WithAttrReplacer() to redact, transform, or remove ordinary attributes, including nested ones.

For example, change the message color while keeping the remaining default styles:

handler := log.NewCLIHandler(os.Stdout,
	log.WithStyle(log.NewStyle(
		log.WithMessageStyle(log.MessageStyle{
			Color: log.NewColor(log.CodeFgCyan),
		}),
	)),
)

Built-in components are styled separately and do not pass through the attribute replacer. They are the time, level, and source, followed by the label and message.

To distinguish application logs from a library's logs, derive handlers with different labels. Derived handlers keep the other options and share the output lock:

handler := log.NewCLIHandler(os.Stderr, log.WithTime())
app := slog.New(handler.WithLabel("APP:"))
sdk := slog.New(handler.WithLabel("SDK:"))

If a shared request logger attaches a request_body attribute that your application does not need, omit it at the handler:

handler := log.NewCLIHandler(os.Stdout,
	log.WithAttrReplacer(func(_ []string, attr slog.Attr) slog.Attr {
		if attr.Key == "request_body" {
			return slog.Attr{}
		}
		return attr
	}),
)

This removes the named attribute, not sensitive content in messages or other attributes. Avoid logging secrets at their source whenever possible.

See examples/main.go and the API reference.

Performance

The serial benchmarks below show zero-allocation writes with all built-in output enabled and with 64 preformatted attributes.

Attach repeated attributes with Logger.With to format them once and reuse the output. For attributes that change on each write, Logger.LogAttrs accepts typed values directly.

Results

Representative serial results on Apple M2, darwin/arm64. Each value is the median of three runs of 100,000 iterations.

Workload allocs/op ns/op B/op
Level and message 0 229.9 0
Time, level, source function, label, and message 0 265.4 0
5 integer attributes per write 0 354.2 0
6 integer attributes per write 1 407.5 48
64 preformatted integer attributes 0 249.9 0

Measured with io.Discard, excluding terminal colors, output locking, and operating-system I/O. Input construction and handler setup are outside the timed loop.

Zero allocation is workload-dependent: slog.Record allocates storage beyond five top-level attributes per write. Any formatting, LogValuer implementations, and outputs exceeding retained buffer capacities can also allocate.

Workloads

The suite follows the workload categories in zerolog's benchmarks, adapted to slog and CLI output. It is not an output-equivalent comparison with zerolog's JSON encoding.

Each benchmark family measures a different part of log handling:

Benchmark suffix Measured work
Disabled Level filtering with and without supplied attributes
Message Empty, escaped, Unicode, invalid UTF-8, and large messages
BuiltIns Optional time, source path, source function, and label output
AttrType Scalars, groups, LogValuer, and Any values
AttrCount Flat attribute lists, including the five-to-six attribute allocation boundary in slog.Record
GroupDepth Per-write traversal of nested attribute groups, with one leaf at every depth
AttrReplacer No replacement, identity, redaction, removal, and expansion into a group
WithAttrs Handler derivation and attribute preformatting, without writing a record
Parallel Shared-handler throughput, with and without the output lock

Measurement boundaries

Benchmark inputs, case tables, mock types, and shared helpers live in benchmarks/helper_test.go. The benchmark functions contain setup and timed operations.

  • AttrsAtSetup measures writes after attributes have been preformatted. Setup is not timed.
  • AttrsAtWrite measures attribute resolution and formatting on every write. Input attributes are constructed before timing.
  • WithAttrs measures setup itself, appending attributes to a handler that already has one cached attribute.
  • AttrType excludes input construction and initial Any boxing. LogValuer resolution and any values it creates are timed.
  • Source benchmarks repeatedly use the same logging call site; they primarily measure cached lookups.
  • Parallel/Discard bypasses the handler's output lock. Parallel/Writer uses a stateless writer that exercises that lock without operating-system I/O. Parallel ns/op measures aggregate throughput, not individual call latency.
  • Writers are not terminals. Terminal colors, console I/O, and Windows translation are not measured.
  • Large messages and deep groups can exceed the pool's capacity limits and require allocations on subsequent writes.

Running

Reproduce the benchmark families summarized in Results:

go test -run '^$' -bench '^BenchmarkCLIHandler_(BuiltIns|AttrCount)$' -benchmem -benchtime=100000x -count=3 ./benchmarks

Run every case with a fixed iteration count:

go test -run '^$' -bench . -benchmem -benchtime=100000x -count=3 ./benchmarks

Run only the attribute-count cases:

go test -run '^$' -bench '^BenchmarkCLIHandler_AttrCount$' -benchmem -benchtime=100000x -count=3 ./benchmarks

Run parallel cases with different processor counts:

go test -run '^$' -bench '^BenchmarkCLIHandler_Parallel$' -benchmem -cpu=1,2,4 -count=3 ./benchmarks

Raw results

Full output for the BuiltIns and AttrCount benchmark families, including all three runs:

goos: darwin
goarch: arm64
pkg: github.com/nekrassov01/log/benchmarks
cpu: Apple M2
BenchmarkCLIHandler_BuiltIns/None-8               100000  232.1 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/None-8               100000  229.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/None-8               100000  220.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Time-8               100000  250.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Time-8               100000  252.1 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Time-8               100000  246.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourcePath-8         100000  222.5 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourcePath-8         100000  224.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourcePath-8         100000  222.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourceFunction-8     100000  222.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourceFunction-8     100000  221.6 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/SourceFunction-8     100000  223.0 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Label-8              100000  218.5 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Label-8              100000  217.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/Label-8              100000  221.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/All-8                100000  264.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/All-8                100000  265.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_BuiltIns/All-8                100000  275.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtSetup-8    100000  229.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtSetup-8    100000  216.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtSetup-8    100000  212.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtWrite-8    100000  217.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtWrite-8    100000  595.3 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/0/AttrsAtWrite-8    100000  214.1 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtSetup-8    100000  216.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtSetup-8    100000  214.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtSetup-8    100000  221.5 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtWrite-8    100000  251.7 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtWrite-8    100000  252.0 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/1/AttrsAtWrite-8    100000  249.6 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtSetup-8    100000  216.7 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtSetup-8    100000  217.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtSetup-8    100000  221.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtWrite-8    100000  335.6 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtWrite-8    100000  334.8 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/4/AttrsAtWrite-8    100000  331.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtSetup-8    100000  215.0 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtSetup-8    100000  216.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtSetup-8    100000  221.1 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtWrite-8    100000  354.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtWrite-8    100000  359.3 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/5/AttrsAtWrite-8    100000  353.6 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtSetup-8    100000  217.1 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtSetup-8    100000  222.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtSetup-8    100000  218.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtWrite-8    100000  736.1 ns/op     48 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtWrite-8    100000  406.3 ns/op     48 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/6/AttrsAtWrite-8    100000  407.5 ns/op     48 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtSetup-8   100000  221.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtSetup-8   100000  222.2 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtSetup-8   100000  224.7 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtWrite-8   100000  733.1 ns/op    448 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtWrite-8   100000  773.7 ns/op    448 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/16/AttrsAtWrite-8   100000  810.4 ns/op    448 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtSetup-8   100000  249.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtSetup-8   100000  255.3 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtSetup-8   100000  245.9 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtWrite-8   100000   2216 ns/op   2689 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtWrite-8   100000   2200 ns/op   2689 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/64/AttrsAtWrite-8   100000   2208 ns/op   2689 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtSetup-8  100000  256.0 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtSetup-8  100000  254.5 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtSetup-8  100000  255.4 ns/op      0 B/op  0 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtWrite-8  100000   8407 ns/op  10249 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtWrite-8  100000   8469 ns/op  10249 B/op  1 allocs/op
BenchmarkCLIHandler_AttrCount/256/AttrsAtWrite-8  100000   8757 ns/op  10248 B/op  1 allocs/op
PASS
ok    github.com/nekrassov01/log/benchmarks  5.346s

Author

nekrassov01

License

MIT

Documentation

Overview

Package log provides a slog.Handler for structured, human-readable CLI output.

CLIHandler formats time, level, source, label, and message as built-in output components, followed by ordinary attributes with dot-separated group names. Style controls their appearance; AttrReplacer applies only to ordinary attributes. Configured colors are enabled for terminal files and omitted for other writers.

Pass the result of NewCLIHandler to slog.New to create a logger.

Index

Constants

View Source
const (
	CodeReset        = 0
	CodeBold         = 1
	CodeFaint        = 2
	CodeItalic       = 3
	CodeUnderline    = 4
	CodeBlinkSlow    = 5
	CodeBlinkRapid   = 6
	CodeReverseVideo = 7
	CodeConcealed    = 8
	CodeCrossedOut   = 9

	CodeFgBlack   = 30
	CodeFgRed     = 31
	CodeFgGreen   = 32
	CodeFgYellow  = 33
	CodeFgBlue    = 34
	CodeFgMagenta = 35
	CodeFgCyan    = 36
	CodeFgWhite   = 37

	CodeFgHiBlack   = 90
	CodeFgHiRed     = 91
	CodeFgHiGreen   = 92
	CodeFgHiYellow  = 93
	CodeFgHiBlue    = 94
	CodeFgHiMagenta = 95
	CodeFgHiCyan    = 96
	CodeFgHiWhite   = 97

	CodeBgBlack   = 40
	CodeBgRed     = 41
	CodeBgGreen   = 42
	CodeBgYellow  = 43
	CodeBgBlue    = 44
	CodeBgMagenta = 45
	CodeBgCyan    = 46
	CodeBgWhite   = 47

	CodeBgHiBlack   = 100
	CodeBgHiRed     = 101
	CodeBgHiGreen   = 102
	CodeBgHiYellow  = 103
	CodeBgHiBlue    = 104
	CodeBgHiMagenta = 105
	CodeBgHiCyan    = 106
	CodeBgHiWhite   = 107
)

SGR (Select Graphic Rendition) codes accepted by NewColor. Fg and Bg select foreground and background colors; Hi selects bright colors.

View Source
const Version = "0.0.3"

Version is the version of this package.

Variables

This section is empty.

Functions

This section is empty.

Types

type AffixStyle

type AffixStyle struct {
	Color *Color
	Text  string
}

AffixStyle decorates a literal prefix or suffix. Text is written verbatim, and Color applies only to Text. Empty Text produces no output; a nil Color adds no color.

type AttrReplacer

type AttrReplacer func(groups []string, attr slog.Attr) slog.Attr

AttrReplacer replaces each non-group ordinary attribute before formatting. It does not receive the built-in time, level, source, label, or message. Ordinary attributes with those names are still passed to the replacer.

slog.LogValuer values are resolved before and after the call. Returning a zero slog.Attr removes the attribute. If the result is a group, its children are traversed and each non-group child is passed to the replacer.

The groups slice contains the original enclosing group names, outermost first. The replacer must not modify or retain this slice. Empty group names are omitted. Calls may run concurrently, so the replacer must protect any shared mutable state.

type AttrStyle

type AttrStyle struct {
	KeyColor   *Color
	ValueColor *Color
	Separator  string
}

AttrStyle decorates ordinary attributes without affecting built-in output. KeyColor also applies to the group path and separator. Separator is written verbatim; an empty value adds nothing.

type CLIHandler

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

CLIHandler implements slog.Handler for human-readable CLI output. Create a handler with NewCLIHandler; the zero value is not ready for use.

Its methods are safe for concurrent use. CLIHandler.WithAttrs, CLIHandler.WithGroup, and CLIHandler.WithLabel preserve the original attributes, groups, and label while sharing the output lock and source cache. Separately constructed handlers use separate locks.

func NewCLIHandler

func NewCLIHandler(w io.Writer, opts ...CLIHandlerOption) *CLIHandler

NewCLIHandler returns a handler that writes to w using opts. A nil w discards output. Zero-valued options are ignored.

By default, the handler uses DefaultStyle and a minimum level of slog.LevelInfo, with time, source, and label output disabled. Terminal detection requires an *os.File; terminal output is adapted for Windows when needed.

func (*CLIHandler) Enabled

func (o *CLIHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether level meets the configured minimum. It reads the level threshold on each call and ignores the context.

func (*CLIHandler) Handle

func (o *CLIHandler) Handle(_ context.Context, record slog.Record) error

Handle formats record and writes the result, followed by a newline. It returns any write error, including io.ErrShortWrite for a partial write. It ignores the context and does not check the minimum level.

func (*CLIHandler) WithAttrs

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

WithAttrs returns a handler with attrs appended to its existing attributes. Attributes are resolved, replaced, and formatted once under the current groups. An empty attrs slice returns the receiver.

func (*CLIHandler) WithGroup

func (o *CLIHandler) WithGroup(name string) slog.Handler

WithGroup returns a handler that adds name to the groups of subsequent attributes. Previously attached attributes and built-in output are unaffected. An empty name returns the receiver.

func (*CLIHandler) WithLabel added in v0.0.2

func (o *CLIHandler) WithLabel(label string) slog.Handler

WithLabel returns a handler that displays label before the message, replacing any existing label. An empty label omits the label and its decoration. The label keeps the receiver's LabelStyle. It is written verbatim and should contain only trusted text.

type CLIHandlerOption

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

CLIHandlerOption configures a CLIHandler. Its zero value has no effect.

func WithAttrReplacer

func WithAttrReplacer(replacer AttrReplacer) CLIHandlerOption

WithAttrReplacer sets the replacer for ordinary attributes. By default, attributes are not replaced. A nil replacer leaves the current setting unchanged. See AttrReplacer for its scope and concurrency requirements.

func WithLabel

func WithLabel(label string) CLIHandlerOption

WithLabel sets the label displayed before the message. An empty label, the default, omits the label and its decoration. The label is written verbatim and should contain only trusted text. Use CLIHandler.WithLabel to derive a handler with a different label.

func WithLevel

func WithLevel(level slog.Leveler) CLIHandlerOption

WithLevel sets the minimum level accepted by the handler. The default is slog.LevelInfo. A nil level leaves the current setting unchanged. Level is read on each enabled check, allowing updates through slog.LevelVar. Custom implementations must support concurrent Level calls.

func WithSourceFunction

func WithSourceFunction() CLIHandlerOption

WithSourceFunction enables the source function name and line number. Source output is disabled by default and omitted when a record has no location. The name is used as reported by the runtime, without shortening, and escaped when necessary. If multiple source options are specified, the last one wins.

func WithSourcePath

func WithSourcePath() CLIHandlerOption

WithSourcePath enables the source file path and line number. Source output is disabled by default and omitted when a record has no location. The path is used as reported by the runtime, without shortening, and escaped when necessary. If multiple source options are specified, the last one wins.

func WithStyle

func WithStyle(s *Style) CLIHandlerOption

WithStyle sets the output style, replacing DefaultStyle. A nil s leaves the current setting unchanged.

func WithTime

func WithTime() CLIHandlerOption

WithTime enables the built-in timestamp, which is disabled by default. A record with a zero Time still omits the timestamp and its decoration.

func WithTimeLayout

func WithTimeLayout(layout string) CLIHandlerOption

WithTimeLayout sets the layout for built-in time and ordinary time attributes. It applies to ordinary attributes even without WithTime. The default and the fallback for an empty layout are time.RFC3339. The built-in timestamp is written verbatim; ordinary time attributes are escaped when necessary. The layout should therefore contain only trusted text.

type Color

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

Color holds immutable SGR sequences for text styling. A nil *Color or a zero-valued Color adds no color.

func NewColor

func NewColor(codes ...int) *Color

NewColor returns a color that applies codes before text and resets SGR state after it. Codes are used in the given order without validation. Passing no codes disables coloring.

type LabelStyle

type LabelStyle struct {
	Color  *Color
	Prefix AffixStyle
	Suffix AffixStyle
	Width  int
}

LabelStyle decorates the text set by WithLabel or CLIHandler.WithLabel. An empty label omits all decoration. Color applies to the label and padding. Width sets the minimum label width, excluding affixes, without truncation. Padding is centered with any extra column on the right; non-positive Width adds none.

type LevelStyle

type LevelStyle struct {
	Color  *Color
	Prefix AffixStyle
	Suffix AffixStyle
	Text   string
	Width  int
}

LevelStyle decorates a built-in log level. Empty Text uses slog.Level.String. Color applies to the text and padding. Width sets the minimum text width, excluding affixes, without truncation. Padding is centered with any extra column on the right; non-positive Width adds none.

type MessageStyle

type MessageStyle struct {
	Color  *Color
	Prefix AffixStyle
	Suffix AffixStyle
}

MessageStyle decorates the log message. Prefix and Suffix surround the message; Color applies to the message itself. A nil Color adds no color.

type SourceStyle

type SourceStyle struct {
	Color  *Color
	Prefix AffixStyle
	Suffix AffixStyle
}

SourceStyle decorates the built-in source location. Prefix and Suffix surround the location; Color applies to the location itself. A nil Color adds no color. Source selection is controlled by WithSourcePath and WithSourceFunction.

type Style

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

Style holds immutable decoration settings for log output. Use NewStyle or DefaultStyle for the default appearance, and Style.With to derive a style without modifying the original.

The zero value adds no decoration and uses an empty attribute separator. Style does not enable or disable built-in output. Literal style text is written verbatim and should contain only trusted text.

func DefaultStyle

func DefaultStyle() *Style

DefaultStyle returns a new style with DBG, INF, WRN, and ERR level labels, angle brackets around source locations, and "=" between attribute keys and values. Its colors are used only for terminal output.

func NewStyle

func NewStyle(opts ...StyleOption) *Style

NewStyle returns DefaultStyle with opts applied in order. Zero-valued options are ignored.

func (*Style) With

func (o *Style) With(opts ...StyleOption) *Style

With returns an independent copy of the style with opts applied in order. It also works on a zero-valued Style. Zero-valued options are ignored.

type StyleOption

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

StyleOption configures a Style. Its zero value has no effect.

func WithAttrStyle

func WithAttrStyle(value AttrStyle) StyleOption

WithAttrStyle replaces the colors and key-value separator for ordinary attributes.

func WithLabelStyle

func WithLabelStyle(value LabelStyle) StyleOption

WithLabelStyle replaces the label's decoration and alignment. It does not set the label text.

func WithLevelStyle

func WithLevelStyle(value map[slog.Level]LevelStyle) StyleOption

WithLevelStyle merges value into the style's level styles, including custom levels. Entries with matching levels are replaced; other entries are preserved. The entries are copied when the option is applied. A nil or empty map has no effect.

func WithMessageStyle

func WithMessageStyle(value MessageStyle) StyleOption

WithMessageStyle replaces the message's decoration.

func WithSourceStyle

func WithSourceStyle(value SourceStyle) StyleOption

WithSourceStyle replaces the built-in source's decoration. It does not enable source output or select between file and function names.

func WithTimeStyle

func WithTimeStyle(value TimeStyle) StyleOption

WithTimeStyle replaces the built-in timestamp's decoration. It does not enable time output or change the time layout.

type TimeStyle

type TimeStyle struct {
	Color  *Color
	Prefix AffixStyle
	Suffix AffixStyle
}

TimeStyle decorates the built-in timestamp. Prefix and Suffix surround the timestamp; Color applies to the timestamp itself. A nil Color adds no color. The layout is set by WithTimeLayout.

Directories

Path Synopsis
Examples demonstrates the default and labeled styles and derived labels with terminal-aware coloring.
Examples demonstrates the default and labeled styles and derived labels with terminal-aware coloring.

Jump to

Keyboard shortcuts

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