clog

package module
v0.5.11 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 27 Imported by: 0

README

clog

A highly customizable structured logger for command-line tools with a zerolog-inspired fluent API, terminal-aware colours, hyperlinks, animations, and custom log levels.

Demo

clog demo

Installation

go get github.com/gechr/clog

Quick Start

package main

import (
  "fmt"

  "github.com/gechr/clog"
)

func main() {
  clog.Info().Str("port", "8080").Msg("Server started")
  clog.Warn().Str("path", "/old").Msg("Deprecated endpoint")
  err := fmt.Errorf("connection refused")
  clog.Error().Err(err).Msg("Connection failed")
}

Output:

INF ℹ️ Server started port=8080
WRN ⚠️ Deprecated endpoint path=/old
ERR ❌ Connection failed error=connection refused

Documentation

Full documentation is available at gechr.github.io/clog.

Documentation

Overview

Package clog provides structured CLI logging with terminal-aware colours, hyperlinks, and spinners.

It uses a zerolog-style fluent API for building log entries:

clog.Info().Str("port", "8080").Msg("Server started")

The default output is a pretty terminal formatter. A custom Handler can be set for alternative formats (e.g. JSON).

Index

Constants

View Source
const (
	// LevelTrace is the "trace" level string.
	LevelTrace = "trace"
	// LevelDebug is the "debug" level string.
	LevelDebug = "debug"
	// LevelInfo is the "info" level string.
	LevelInfo = "info"
	// LevelDry is the "dry" level string.
	LevelDry = "dry"
	// LevelWarn is the "warn" level string.
	LevelWarn = "warn"
	// LevelError is the "error" level string.
	LevelError = "error"
	// LevelFatal is the "fatal" level string.
	LevelFatal = "fatal"
)
View Source
const DefaultEnvPrefix = "CLOG"

DefaultEnvPrefix is the default environment variable prefix.

View Source
const ErrorKey = "error"

ErrorKey is the default field key used by Event.Err and Context.Err.

View Source
const Nil = "<nil>"

Nil is the string representation used for nil values (e.g. in DefaultValueStyles).

Variables

View Source
var (
	// BarBasic uses only ASCII characters for maximum terminal compatibility.
	//
	//	[=====>    ] 50%
	BarBasic = BarStyle{
		CapLeft:     "[",
		CapRight:    "]",
		CapStyle:    defaultCapStyle,
		CharEmpty:   ' ',
		CharFill:    '=',
		CharHead:    '>',
		Separator:   " ",
		WidgetRight: WidgetPercent(),
		WidthMax:    barDefaultWidthMax,
		WidthMin:    barDefaultBarWidthMin,
	}

	// BarBlock uses solid block characters without sub-cell resolution.
	//
	//	│█████░░░░░│ 50%
	BarBlock = BarStyle{
		CapLeft:     "│",
		CapRight:    "│",
		CapStyle:    defaultCapStyle,
		CharEmpty:   '░',
		CharFill:    '█',
		Separator:   " ",
		WidgetRight: WidgetPercent(),
		WidthMax:    barDefaultWidthMax,
		WidthMin:    barDefaultBarWidthMin,
	}

	// BarDash uses a simple dash for filled cells and spaces for empty.
	//
	//	[-----     ] 50%
	BarDash = BarStyle{
		CapLeft:     "[",
		CapRight:    "]",
		CapStyle:    defaultCapStyle,
		CharEmpty:   ' ',
		CharFill:    '-',
		Separator:   " ",
		WidgetRight: WidgetPercent(),
		WidthMax:    barDefaultWidthMax,
		WidthMin:    barDefaultBarWidthMin,
	}

	// BarGradient uses block-element characters with 8x sub-cell resolution
	// for the smoothest possible progression.
	//
	//	│██████▍   │ 64%
	BarGradient = BarStyle{
		CapLeft:      "│",
		CapRight:     "│",
		CapStyle:     defaultCapStyle,
		CharEmpty:    ' ',
		CharFill:     '█',
		GradientFill: []rune{'▏', '▎', '▍', '▌', '▋', '▊', '▉'},
		Separator:    " ",
		WidgetRight:  WidgetPercent(),
		WidthMax:     barDefaultWidthMax,
		WidthMin:     barDefaultBarWidthMin,
	}

	// BarThin uses box-drawing characters with half-cell resolution for smooth
	// progress, inspired by Python's Rich library. This is the default style.
	//
	//	[━━━━━╸╺──────] 45%
	BarThin = BarStyle{
		CapLeft:     "[",
		CapRight:    "]",
		CapStyle:    defaultCapStyle,
		CharEmpty:   '─',
		CharFill:    '━',
		HalfEmpty:   '╺',
		HalfFilled:  '╸',
		Separator:   " ",
		WidgetRight: WidgetPercent(),
		WidthMax:    barDefaultWidthMax,
		WidthMin:    barDefaultBarWidthMin,
	}

	// BarSmooth uses block characters with a half-block leading edge for
	// smoother progression than [BarBlock].
	//
	//	│████▌     │ 45%
	BarSmooth = BarStyle{
		CapLeft:     "│",
		CapRight:    "│",
		CapStyle:    defaultCapStyle,
		CharEmpty:   ' ',
		CharFill:    '█',
		HalfFilled:  '▌',
		Separator:   " ",
		WidgetRight: WidgetPercent(),
		WidthMax:    barDefaultWidthMax,
		WidthMin:    barDefaultBarWidthMin,
	}
)

Predefined bar styles for common visual appearances. Pass any of these to AnimationBuilder.Style to change the bar's look.

View Source
var (
	SpinnerAesthetic = SpinnerStyle{
		Frames: []string{
			"▰▱▱▱▱▱▱",
			"▰▰▱▱▱▱▱",
			"▰▰▰▱▱▱▱",
			"▰▰▰▰▱▱▱",
			"▰▰▰▰▰▱▱",
			"▰▰▰▰▰▰▱",
			"▰▰▰▰▰▰▰",
			"▰▱▱▱▱▱▱",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerArc = SpinnerStyle{
		Frames: []string{"◜", "◠", "◝", "◞", "◡", "◟"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerArrow2 = SpinnerStyle{
		Frames: []string{"⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ "},
		FPS:    80 * time.Millisecond,
	}
	SpinnerArrow3 = SpinnerStyle{
		Frames: []string{"▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerBalloon = SpinnerStyle{
		Frames: []string{" ", ".", "o", "O", "@", "*", " "},
		FPS:    140 * time.Millisecond,
	}
	SpinnerBalloon2 = SpinnerStyle{
		Frames: []string{".", "o", "O", "°", "O", "o", "."},
		FPS:    120 * time.Millisecond,
	}
	SpinnerBetaWave = SpinnerStyle{
		Frames: []string{
			"ρββββββ",
			"βρβββββ",
			"ββρββββ",
			"βββρβββ",
			"ββββρββ",
			"βββββρβ",
			"ββββββρ",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerBinary = SpinnerStyle{
		Frames: []string{
			"010010",
			"001100",
			"100101",
			"111010",
			"111101",
			"010111",
			"101011",
			"111000",
			"110011",
			"110101",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerBluePulse = SpinnerStyle{
		Frames: []string{"🔹 ", "🔷 ", "🔵 ", "🔵 ", "🔷 "},
		FPS:    100 * time.Millisecond,
	}
	SpinnerBouncingBall = SpinnerStyle{
		Frames: []string{
			"( ●    )",
			"(  ●   )",
			"(   ●  )",
			"(    ● )",
			"(     ●)",
			"(    ● )",
			"(   ●  )",
			"(  ●   )",
			"( ●    )",
			"(●     )",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerBoxBounce = SpinnerStyle{
		Frames: []string{"▖", "▘", "▝", "▗"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerBoxBounce2 = SpinnerStyle{
		Frames: []string{"▌", "▀", "▐", "▄"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerChristmas = SpinnerStyle{
		Frames: []string{"🌲", "🎄"},
		FPS:    400 * time.Millisecond,
	}
	SpinnerCircle = SpinnerStyle{
		Frames: []string{"◡", "⊙", "◠"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerCircleHalves = SpinnerStyle{
		Frames: []string{"◐", "◓", "◑", "◒"},
		FPS:    50 * time.Millisecond,
	}
	SpinnerCircleQuarters = SpinnerStyle{
		Frames: []string{"◴", "◷", "◶", "◵"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerDot = SpinnerStyle{
		Frames: []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},
		FPS:    100 * time.Millisecond,
	}
	SpinnerDots = SpinnerStyle{
		Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerDots11 = SpinnerStyle{
		Frames: []string{"⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerDots12 = SpinnerStyle{
		Frames: []string{
			"⢀⠀",
			"⡀⠀",
			"⠄⠀",
			"⢂⠀",
			"⡂⠀",
			"⠅⠀",
			"⢃⠀",
			"⡃⠀",
			"⠍⠀",
			"⢋⠀",
			"⡋⠀",
			"⠍⠁",
			"⢋⠁",
			"⡋⠁",
			"⠍⠉",
			"⠋⠉",
			"⠋⠉",
			"⠉⠙",
			"⠉⠙",
			"⠉⠩",
			"⠈⢙",
			"⠈⡙",
			"⢈⠩",
			"⡀⢙",
			"⠄⡙",
			"⢂⠩",
			"⡂⢘",
			"⠅⡘",
			"⢃⠨",
			"⡃⢐",
			"⠍⡐",
			"⢋⠠",
			"⡋⢀",
			"⠍⡁",
			"⢋⠁",
			"⡋⠁",
			"⠍⠉",
			"⠋⠉",
			"⠋⠉",
			"⠉⠙",
			"⠉⠙",
			"⠉⠩",
			"⠈⢙",
			"⠈⡙",
			"⠈⠩",
			"⠀⢙",
			"⠀⡙",
			"⠀⠩",
			"⠀⢘",
			"⠀⡘",
			"⠀⠨",
			"⠀⢐",
			"⠀⡐",
			"⠀⠠",
			"⠀⢀",
			"⠀⡀",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots13 = SpinnerStyle{
		Frames: []string{"⣼", "⣹", "⢻", "⠿", "⡟", "⣏", "⣧", "⣶"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerDots14 = SpinnerStyle{
		Frames: []string{
			"⠉⠉",
			"⠈⠙",
			"⠀⠹",
			"⠀⢸",
			"⠀⣰",
			"⢀⣠",
			"⣀⣀",
			"⣄⡀",
			"⣆⠀",
			"⡇⠀",
			"⠏⠀",
			"⠋⠁",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots3 = SpinnerStyle{
		Frames: []string{"⠋", "⠙", "⠚", "⠞", "⠖", "⠦", "⠴", "⠲", "⠳", "⠓"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerDots4 = SpinnerStyle{
		Frames: []string{
			"⠄",
			"⠆",
			"⠇",
			"⠋",
			"⠙",
			"⠸",
			"⠰",
			"⠠",
			"⠰",
			"⠸",
			"⠙",
			"⠋",
			"⠇",
			"⠆",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots5 = SpinnerStyle{
		Frames: []string{
			"⠋",
			"⠙",
			"⠚",
			"⠒",
			"⠂",
			"⠂",
			"⠒",
			"⠲",
			"⠴",
			"⠦",
			"⠖",
			"⠒",
			"⠐",
			"⠐",
			"⠒",
			"⠓",
			"⠋",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots6 = SpinnerStyle{
		Frames: []string{
			"⠁",
			"⠉",
			"⠙",
			"⠚",
			"⠒",
			"⠂",
			"⠂",
			"⠒",
			"⠲",
			"⠴",
			"⠤",
			"⠄",
			"⠄",
			"⠤",
			"⠴",
			"⠲",
			"⠒",
			"⠂",
			"⠂",
			"⠒",
			"⠚",
			"⠙",
			"⠉",
			"⠁",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots7 = SpinnerStyle{
		Frames: []string{
			"⠈",
			"⠉",
			"⠋",
			"⠓",
			"⠒",
			"⠐",
			"⠐",
			"⠒",
			"⠖",
			"⠦",
			"⠤",
			"⠠",
			"⠠",
			"⠤",
			"⠦",
			"⠖",
			"⠒",
			"⠐",
			"⠐",
			"⠒",
			"⠓",
			"⠋",
			"⠉",
			"⠈",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots8 = SpinnerStyle{
		Frames: []string{
			"⠁",
			"⠁",
			"⠉",
			"⠙",
			"⠚",
			"⠒",
			"⠂",
			"⠂",
			"⠒",
			"⠲",
			"⠴",
			"⠤",
			"⠄",
			"⠄",
			"⠤",
			"⠠",
			"⠠",
			"⠤",
			"⠦",
			"⠖",
			"⠒",
			"⠐",
			"⠐",
			"⠒",
			"⠓",
			"⠋",
			"⠉",
			"⠈",
			"⠈",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots8Bit = SpinnerStyle{
		Frames: []string{
			"⠀",
			"⠁",
			"⠂",
			"⠃",
			"⠄",
			"⠅",
			"⠆",
			"⠇",
			"⡀",
			"⡁",
			"⡂",
			"⡃",
			"⡄",
			"⡅",
			"⡆",
			"⡇",
			"⠈",
			"⠉",
			"⠊",
			"⠋",
			"⠌",
			"⠍",
			"⠎",
			"⠏",
			"⡈",
			"⡉",
			"⡊",
			"⡋",
			"⡌",
			"⡍",
			"⡎",
			"⡏",
			"⠐",
			"⠑",
			"⠒",
			"⠓",
			"⠔",
			"⠕",
			"⠖",
			"⠗",
			"⡐",
			"⡑",
			"⡒",
			"⡓",
			"⡔",
			"⡕",
			"⡖",
			"⡗",
			"⠘",
			"⠙",
			"⠚",
			"⠛",
			"⠜",
			"⠝",
			"⠞",
			"⠟",
			"⡘",
			"⡙",
			"⡚",
			"⡛",
			"⡜",
			"⡝",
			"⡞",
			"⡟",
			"⠠",
			"⠡",
			"⠢",
			"⠣",
			"⠤",
			"⠥",
			"⠦",
			"⠧",
			"⡠",
			"⡡",
			"⡢",
			"⡣",
			"⡤",
			"⡥",
			"⡦",
			"⡧",
			"⠨",
			"⠩",
			"⠪",
			"⠫",
			"⠬",
			"⠭",
			"⠮",
			"⠯",
			"⡨",
			"⡩",
			"⡪",
			"⡫",
			"⡬",
			"⡭",
			"⡮",
			"⡯",
			"⠰",
			"⠱",
			"⠲",
			"⠳",
			"⠴",
			"⠵",
			"⠶",
			"⠷",
			"⡰",
			"⡱",
			"⡲",
			"⡳",
			"⡴",
			"⡵",
			"⡶",
			"⡷",
			"⠸",
			"⠹",
			"⠺",
			"⠻",
			"⠼",
			"⠽",
			"⠾",
			"⠿",
			"⡸",
			"⡹",
			"⡺",
			"⡻",
			"⡼",
			"⡽",
			"⡾",
			"⡿",
			"⢀",
			"⢁",
			"⢂",
			"⢃",
			"⢄",
			"⢅",
			"⢆",
			"⢇",
			"⣀",
			"⣁",
			"⣂",
			"⣃",
			"⣄",
			"⣅",
			"⣆",
			"⣇",
			"⢈",
			"⢉",
			"⢊",
			"⢋",
			"⢌",
			"⢍",
			"⢎",
			"⢏",
			"⣈",
			"⣉",
			"⣊",
			"⣋",
			"⣌",
			"⣍",
			"⣎",
			"⣏",
			"⢐",
			"⢑",
			"⢒",
			"⢓",
			"⢔",
			"⢕",
			"⢖",
			"⢗",
			"⣐",
			"⣑",
			"⣒",
			"⣓",
			"⣔",
			"⣕",
			"⣖",
			"⣗",
			"⢘",
			"⢙",
			"⢚",
			"⢛",
			"⢜",
			"⢝",
			"⢞",
			"⢟",
			"⣘",
			"⣙",
			"⣚",
			"⣛",
			"⣜",
			"⣝",
			"⣞",
			"⣟",
			"⢠",
			"⢡",
			"⢢",
			"⢣",
			"⢤",
			"⢥",
			"⢦",
			"⢧",
			"⣠",
			"⣡",
			"⣢",
			"⣣",
			"⣤",
			"⣥",
			"⣦",
			"⣧",
			"⢨",
			"⢩",
			"⢪",
			"⢫",
			"⢬",
			"⢭",
			"⢮",
			"⢯",
			"⣨",
			"⣩",
			"⣪",
			"⣫",
			"⣬",
			"⣭",
			"⣮",
			"⣯",
			"⢰",
			"⢱",
			"⢲",
			"⢳",
			"⢴",
			"⢵",
			"⢶",
			"⢷",
			"⣰",
			"⣱",
			"⣲",
			"⣳",
			"⣴",
			"⣵",
			"⣶",
			"⣷",
			"⢸",
			"⢹",
			"⢺",
			"⢻",
			"⢼",
			"⢽",
			"⢾",
			"⢿",
			"⣸",
			"⣹",
			"⣺",
			"⣻",
			"⣼",
			"⣽",
			"⣾",
			"⣿",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerDots9 = SpinnerStyle{
		Frames: []string{"⢹", "⢺", "⢼", "⣸", "⣇", "⡧", "⡗", "⡏"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerDotsCircle = SpinnerStyle{
		Frames: []string{"⢎ ", "⠎⠁", "⠊⠑", "⠈⠱", " ⡱", "⢀⡰", "⢄⡠", "⢆⡀"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerDqpb = SpinnerStyle{
		Frames: []string{"d", "q", "p", "b"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerDwarfFortress = SpinnerStyle{
		Frames: []string{
			" ██████£££  ",
			"☺██████£££  ",
			"☺██████£££  ",
			"☺▓█████£££  ",
			"☺▓█████£££  ",
			"☺▒█████£££  ",
			"☺▒█████£££  ",
			"☺░█████£££  ",
			"☺░█████£££  ",
			"☺ █████£££  ",
			" ☺█████£££  ",
			" ☺█████£££  ",
			" ☺▓████£££  ",
			" ☺▓████£££  ",
			" ☺▒████£££  ",
			" ☺▒████£££  ",
			" ☺░████£££  ",
			" ☺░████£££  ",
			" ☺ ████£££  ",
			"  ☺████£££  ",
			"  ☺████£££  ",
			"  ☺▓███£££  ",
			"  ☺▓███£££  ",
			"  ☺▒███£££  ",
			"  ☺▒███£££  ",
			"  ☺░███£££  ",
			"  ☺░███£££  ",
			"  ☺ ███£££  ",
			"   ☺███£££  ",
			"   ☺███£££  ",
			"   ☺▓██£££  ",
			"   ☺▓██£££  ",
			"   ☺▒██£££  ",
			"   ☺▒██£££  ",
			"   ☺░██£££  ",
			"   ☺░██£££  ",
			"   ☺ ██£££  ",
			"    ☺██£££  ",
			"    ☺██£££  ",
			"    ☺▓█£££  ",
			"    ☺▓█£££  ",
			"    ☺▒█£££  ",
			"    ☺▒█£££  ",
			"    ☺░█£££  ",
			"    ☺░█£££  ",
			"    ☺ █£££  ",
			"     ☺█£££  ",
			"     ☺█£££  ",
			"     ☺▓£££  ",
			"     ☺▓£££  ",
			"     ☺▒£££  ",
			"     ☺▒£££  ",
			"     ☺░£££  ",
			"     ☺░£££  ",
			"     ☺ £££  ",
			"      ☺£££  ",
			"      ☺£££  ",
			"      ☺▓££  ",
			"      ☺▓££  ",
			"      ☺▒££  ",
			"      ☺▒££  ",
			"      ☺░££  ",
			"      ☺░££  ",
			"      ☺ ££  ",
			"       ☺££  ",
			"       ☺££  ",
			"       ☺▓£  ",
			"       ☺▓£  ",
			"       ☺▒£  ",
			"       ☺▒£  ",
			"       ☺░£  ",
			"       ☺░£  ",
			"       ☺ £  ",
			"        ☺£  ",
			"        ☺£  ",
			"        ☺▓  ",
			"        ☺▓  ",
			"        ☺▒  ",
			"        ☺▒  ",
			"        ☺░  ",
			"        ☺░  ",
			"        ☺   ",
			"        ☺  &",
			"        ☺ ☼&",
			"       ☺ ☼ &",
			"       ☺☼  &",
			"      ☺☼  & ",
			"      ‼   & ",
			"     ☺   &  ",
			"    ‼    &  ",
			"   ☺    &   ",
			"  ‼     &   ",
			" ☺     &    ",
			"‼      &    ",
			"      &     ",
			"      &     ",
			"     &   ░  ",
			"     &   ▒  ",
			"    &    ▓  ",
			"    &    £  ",
			"   &    ░£  ",
			"   &    ▒£  ",
			"  &     ▓£  ",
			"  &     ££  ",
			" &     ░££  ",
			" &     ▒££  ",
			"&      ▓££  ",
			"&      £££  ",
			"      ░£££  ",
			"      ▒£££  ",
			"      ▓£££  ",
			"      █£££  ",
			"     ░█£££  ",
			"     ▒█£££  ",
			"     ▓█£££  ",
			"     ██£££  ",
			"    ░██£££  ",
			"    ▒██£££  ",
			"    ▓██£££  ",
			"    ███£££  ",
			"   ░███£££  ",
			"   ▒███£££  ",
			"   ▓███£££  ",
			"   ████£££  ",
			"  ░████£££  ",
			"  ▒████£££  ",
			"  ▓████£££  ",
			"  █████£££  ",
			" ░█████£££  ",
			" ▒█████£££  ",
			" ▓█████£££  ",
			" ██████£££  ",
			" ██████£££  ",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerEllipsis = SpinnerStyle{
		Frames: []string{"", ".", "..", "..."},
		FPS:    333 * time.Millisecond,
	}
	SpinnerFingerDance = SpinnerStyle{
		Frames: []string{"🤘 ", "🤟 ", "🖖 ", "✋ ", "🤚 ", "👆 "},
		FPS:    160 * time.Millisecond,
	}
	SpinnerFish = SpinnerStyle{
		Frames: []string{
			"~~~~~~~~~~~~~~~~~~~~",
			"> ~~~~~~~~~~~~~~~~~~",
			"º> ~~~~~~~~~~~~~~~~~",
			"(º> ~~~~~~~~~~~~~~~~",
			"((º> ~~~~~~~~~~~~~~~",
			"<((º> ~~~~~~~~~~~~~~",
			"><((º> ~~~~~~~~~~~~~",
			" ><((º> ~~~~~~~~~~~~",
			"~ ><((º> ~~~~~~~~~~~",
			"~~ <>((º> ~~~~~~~~~~",
			"~~~ ><((º> ~~~~~~~~~",
			"~~~~ <>((º> ~~~~~~~~",
			"~~~~~ ><((º> ~~~~~~~",
			"~~~~~~ <>((º> ~~~~~~",
			"~~~~~~~ ><((º> ~~~~~",
			"~~~~~~~~ <>((º> ~~~~",
			"~~~~~~~~~ ><((º> ~~~",
			"~~~~~~~~~~ <>((º> ~~",
			"~~~~~~~~~~~ ><((º> ~",
			"~~~~~~~~~~~~ <>((º> ",
			"~~~~~~~~~~~~~ ><((º>",
			"~~~~~~~~~~~~~~ <>((º",
			"~~~~~~~~~~~~~~~ ><((",
			"~~~~~~~~~~~~~~~~ <>(",
			"~~~~~~~~~~~~~~~~~ ><",
			"~~~~~~~~~~~~~~~~~~ <",
			"~~~~~~~~~~~~~~~~~~~~",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerFistBump = SpinnerStyle{
		Frames: []string{
			"🤜\u3000\u3000\u3000\u3000🤛 ",
			"🤜\u3000\u3000\u3000\u3000🤛 ",
			"🤜\u3000\u3000\u3000\u3000🤛 ",
			"\u3000🤜\u3000\u3000🤛\u3000 ",
			"\u3000\u3000🤜🤛\u3000\u3000 ",
			"\u3000🤜✨🤛\u3000\u3000 ",
			"🤜\u3000✨\u3000🤛\u3000 ",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerFlip = SpinnerStyle{
		Frames: []string{
			"_",
			"_",
			"_",
			"-",
			"`",
			"`",
			"'",
			"´",
			"-",
			"_",
			"_",
			"_",
		},
		FPS: 70 * time.Millisecond,
	}
	SpinnerGlobe = SpinnerStyle{
		Frames: []string{"🌍", "🌎", "🌏"},
		FPS:    250 * time.Millisecond,
	}
	SpinnerGrenade = SpinnerStyle{
		Frames: []string{
			"،  ",
			"′  ",
			" ´ ",
			" ‾ ",
			"  ⸌",
			"  ⸊",
			"  |",
			"  ⁎",
			"  ⁕",
			" ෴ ",
			"  ⁓",
			"   ",
			"   ",
			"   ",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerGrowHorizontal = SpinnerStyle{
		Frames: []string{
			"▏",
			"▎",
			"▍",
			"▌",
			"▋",
			"▊",
			"▉",
			"▊",
			"▋",
			"▌",
			"▍",
			"▎",
		},
		FPS: 120 * time.Millisecond,
	}
	SpinnerGrowVertical = SpinnerStyle{
		Frames: []string{"▁", "▃", "▄", "▅", "▆", "▇", "▆", "▅", "▄", "▃"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerHamburger = SpinnerStyle{
		Frames: []string{"☱", "☲", "☴", "☲"},
		FPS:    333 * time.Millisecond,
	}
	SpinnerJump = SpinnerStyle{
		Frames: []string{"⢄", "⢂", "⢁", "⡁", "⡈", "⡐", "⡠"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerLayer = SpinnerStyle{
		Frames: []string{"-", "=", "≡"},
		FPS:    150 * time.Millisecond,
	}
	SpinnerLine = SpinnerStyle{
		Frames: []string{"|", "/", "-", "\\"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerLine2 = SpinnerStyle{
		Frames: []string{"⠂", "-", "–", "-", "–", "-"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerMaterial = SpinnerStyle{
		Frames: []string{
			"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"███████▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"████████▁▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"██████████▁▁▁▁▁▁▁▁▁▁",
			"███████████▁▁▁▁▁▁▁▁▁",
			"█████████████▁▁▁▁▁▁▁",
			"██████████████▁▁▁▁▁▁",
			"██████████████▁▁▁▁▁▁",
			"▁██████████████▁▁▁▁▁",
			"▁██████████████▁▁▁▁▁",
			"▁██████████████▁▁▁▁▁",
			"▁▁██████████████▁▁▁▁",
			"▁▁▁██████████████▁▁▁",
			"▁▁▁▁█████████████▁▁▁",
			"▁▁▁▁██████████████▁▁",
			"▁▁▁▁██████████████▁▁",
			"▁▁▁▁▁██████████████▁",
			"▁▁▁▁▁██████████████▁",
			"▁▁▁▁▁██████████████▁",
			"▁▁▁▁▁▁██████████████",
			"▁▁▁▁▁▁██████████████",
			"▁▁▁▁▁▁▁█████████████",
			"▁▁▁▁▁▁▁█████████████",
			"▁▁▁▁▁▁▁▁████████████",
			"▁▁▁▁▁▁▁▁████████████",
			"▁▁▁▁▁▁▁▁▁███████████",
			"▁▁▁▁▁▁▁▁▁███████████",
			"▁▁▁▁▁▁▁▁▁▁██████████",
			"▁▁▁▁▁▁▁▁▁▁██████████",
			"▁▁▁▁▁▁▁▁▁▁▁▁████████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
			"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
			"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
			"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
			"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
			"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
			"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"██████▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"████████▁▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"█████████▁▁▁▁▁▁▁▁▁▁▁",
			"███████████▁▁▁▁▁▁▁▁▁",
			"████████████▁▁▁▁▁▁▁▁",
			"████████████▁▁▁▁▁▁▁▁",
			"██████████████▁▁▁▁▁▁",
			"██████████████▁▁▁▁▁▁",
			"▁██████████████▁▁▁▁▁",
			"▁██████████████▁▁▁▁▁",
			"▁▁▁█████████████▁▁▁▁",
			"▁▁▁▁▁████████████▁▁▁",
			"▁▁▁▁▁████████████▁▁▁",
			"▁▁▁▁▁▁███████████▁▁▁",
			"▁▁▁▁▁▁▁▁█████████▁▁▁",
			"▁▁▁▁▁▁▁▁█████████▁▁▁",
			"▁▁▁▁▁▁▁▁▁█████████▁▁",
			"▁▁▁▁▁▁▁▁▁█████████▁▁",
			"▁▁▁▁▁▁▁▁▁▁█████████▁",
			"▁▁▁▁▁▁▁▁▁▁▁████████▁",
			"▁▁▁▁▁▁▁▁▁▁▁████████▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁███████▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁███████▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
			"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
		},
		FPS: 17 * time.Millisecond,
	}
	SpinnerMeter = SpinnerStyle{
		Frames: []string{"▱▱▱", "▰▱▱", "▰▰▱", "▰▰▰", "▰▰▱", "▰▱▱", "▱▱▱"},
		FPS:    143 * time.Millisecond,
	}
	SpinnerMindblown = SpinnerStyle{
		Frames: []string{
			"😐 ",
			"😐 ",
			"😮 ",
			"😮 ",
			"😦 ",
			"😦 ",
			"😧 ",
			"😧 ",
			"🤯 ",
			"💥 ",
			"✨ ",
			"\u3000 ",
			"\u3000 ",
			"\u3000 ",
		},
		FPS: 160 * time.Millisecond,
	}
	SpinnerMiniDot = SpinnerStyle{
		Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
		FPS:    83 * time.Millisecond,
	}
	SpinnerMonkey = SpinnerStyle{
		Frames: []string{"🙈", "🙉", "🙊"},
		FPS:    333 * time.Millisecond,
	}
	SpinnerMoon = SpinnerStyle{
		Frames: []string{"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"},
		FPS:    125 * time.Millisecond,
	}
	SpinnerNoise = SpinnerStyle{
		Frames: []string{"▓", "▒", "░"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerOrangeBluePulse = SpinnerStyle{
		Frames: []string{"🔸 ", "🔶 ", "🟠 ", "🟠 ", "🔶 ", "🔹 ", "🔷 ", "🔵 ", "🔵 ", "🔷 "},
		FPS:    100 * time.Millisecond,
	}
	SpinnerOrangePulse = SpinnerStyle{
		Frames: []string{"🔸 ", "🔶 ", "🟠 ", "🟠 ", "🔶 "},
		FPS:    100 * time.Millisecond,
	}
	SpinnerPipe = SpinnerStyle{
		Frames: []string{"┤", "┘", "┴", "└", "├", "┌", "┬", "┐"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerPoint = SpinnerStyle{
		Frames: []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"},
		FPS:    125 * time.Millisecond,
	}
	SpinnerPoints = SpinnerStyle{
		Frames: []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●"},
		FPS:    143 * time.Millisecond,
	}
	SpinnerPong = SpinnerStyle{
		Frames: []string{
			"▐⠂       ▌",
			"▐⠈       ▌",
			"▐ ⠂      ▌",
			"▐ ⠠      ▌",
			"▐  ⡀     ▌",
			"▐  ⠠     ▌",
			"▐   ⠂    ▌",
			"▐   ⠈    ▌",
			"▐    ⠂   ▌",
			"▐    ⠠   ▌",
			"▐     ⡀  ▌",
			"▐     ⠠  ▌",
			"▐      ⠂ ▌",
			"▐      ⠈ ▌",
			"▐       ⠂▌",
			"▐       ⠠▌",
			"▐       ⡀▌",
			"▐      ⠠ ▌",
			"▐      ⠂ ▌",
			"▐     ⠈  ▌",
			"▐     ⠂  ▌",
			"▐    ⠠   ▌",
			"▐    ⡀   ▌",
			"▐   ⠠    ▌",
			"▐   ⠂    ▌",
			"▐  ⠈     ▌",
			"▐  ⠂     ▌",
			"▐ ⠠      ▌",
			"▐ ⡀      ▌",
			"▐⠠       ▌",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerPulse = SpinnerStyle{
		Frames: []string{"█", "▓", "▒", "░"},
		FPS:    125 * time.Millisecond,
	}
	SpinnerRollingLine = SpinnerStyle{
		Frames: []string{"/  ", " - ", " \\ ", "  |", "  |", " \\ ", " - ", "/  "},
		FPS:    80 * time.Millisecond,
	}
	SpinnerRunner = SpinnerStyle{
		Frames: []string{"🚶 ", "🏃 "},
		FPS:    140 * time.Millisecond,
	}
	SpinnerSand = SpinnerStyle{
		Frames: []string{
			"⠁",
			"⠂",
			"⠄",
			"⡀",
			"⡈",
			"⡐",
			"⡠",
			"⣀",
			"⣁",
			"⣂",
			"⣄",
			"⣌",
			"⣔",
			"⣤",
			"⣥",
			"⣦",
			"⣮",
			"⣶",
			"⣷",
			"⣿",
			"⡿",
			"⠿",
			"⢟",
			"⠟",
			"⡛",
			"⠛",
			"⠫",
			"⢋",
			"⠋",
			"⠍",
			"⡉",
			"⠉",
			"⠑",
			"⠡",
			"⢁",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerShark = SpinnerStyle{
		Frames: []string{
			"▐|\\____________▌",
			"▐_|\\___________▌",
			"▐__|\\__________▌",
			"▐___|\\_________▌",
			"▐____|\\________▌",
			"▐_____|\\_______▌",
			"▐______|\\______▌",
			"▐_______|\\_____▌",
			"▐________|\\____▌",
			"▐_________|\\___▌",
			"▐__________|\\__▌",
			"▐___________|\\_▌",
			"▐____________|\\▌",
			"▐____________/|▌",
			"▐___________/|_▌",
			"▐__________/|__▌",
			"▐_________/|___▌",
			"▐________/|____▌",
			"▐_______/|_____▌",
			"▐______/|______▌",
			"▐_____/|_______▌",
			"▐____/|________▌",
			"▐___/|_________▌",
			"▐__/|__________▌",
			"▐_/|___________▌",
			"▐/|____________▌",
		},
		FPS: 120 * time.Millisecond,
	}
	SpinnerSimpleDots = SpinnerStyle{
		Frames: []string{".  ", ".. ", "...", "   "},
		FPS:    400 * time.Millisecond,
	}
	SpinnerSimpleDotsScrolling = SpinnerStyle{
		Frames: []string{".  ", ".. ", "...", " ..", "  .", "   "},
		FPS:    200 * time.Millisecond,
	}
	SpinnerSmiley = SpinnerStyle{
		Frames: []string{"😄 ", "😝 "},
		FPS:    200 * time.Millisecond,
	}
	SpinnerSoccerHeader = SpinnerStyle{
		Frames: []string{
			" 🧑⚽️       🧑 ",
			"🧑  ⚽️      🧑 ",
			"🧑   ⚽️     🧑 ",
			"🧑    ⚽️    🧑 ",
			"🧑     ⚽️   🧑 ",
			"🧑      ⚽️  🧑 ",
			"🧑       ⚽️🧑  ",
			"🧑      ⚽️  🧑 ",
			"🧑     ⚽️   🧑 ",
			"🧑    ⚽️    🧑 ",
			"🧑   ⚽️     🧑 ",
			"🧑  ⚽️      🧑 ",
		},
		FPS: 80 * time.Millisecond,
	}
	SpinnerSpeaker = SpinnerStyle{
		Frames: []string{"🔈 ", "🔉 ", "🔊 ", "🔉 "},
		FPS:    160 * time.Millisecond,
	}
	SpinnerSquareCorners = SpinnerStyle{
		Frames: []string{"◰", "◳", "◲", "◱"},
		FPS:    180 * time.Millisecond,
	}
	SpinnerSquish = SpinnerStyle{
		Frames: []string{"╫", "╪"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerStar2 = SpinnerStyle{
		Frames: []string{"+", "x", "*"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerTimeTravel = SpinnerStyle{
		Frames: []string{
			"🕛 ",
			"🕚 ",
			"🕙 ",
			"🕘 ",
			"🕗 ",
			"🕖 ",
			"🕕 ",
			"🕔 ",
			"🕓 ",
			"🕒 ",
			"🕑 ",
			"🕐 ",
		},
		FPS: 100 * time.Millisecond,
	}
	SpinnerToggle = SpinnerStyle{
		Frames: []string{"⊶", "⊷"},
		FPS:    250 * time.Millisecond,
	}
	SpinnerToggle10 = SpinnerStyle{
		Frames: []string{"㊂", "㊀", "㊁"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerToggle11 = SpinnerStyle{
		Frames: []string{"⧇", "⧆"},
		FPS:    50 * time.Millisecond,
	}
	SpinnerToggle12 = SpinnerStyle{
		Frames: []string{"☗", "☖"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerToggle13 = SpinnerStyle{
		Frames: []string{"=", "*", "-"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerToggle2 = SpinnerStyle{
		Frames: []string{"▫", "▪"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerToggle3 = SpinnerStyle{
		Frames: []string{"□", "■"},
		FPS:    120 * time.Millisecond,
	}
	SpinnerToggle4 = SpinnerStyle{
		Frames: []string{"■", "□", "▪", "▫"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerToggle5 = SpinnerStyle{
		Frames: []string{"▮", "▯"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerToggle6 = SpinnerStyle{
		Frames: []string{"ဝ", "၀"},
		FPS:    300 * time.Millisecond,
	}
	SpinnerToggle7 = SpinnerStyle{
		Frames: []string{"⦾", "⦿"},
		FPS:    80 * time.Millisecond,
	}
	SpinnerToggle8 = SpinnerStyle{
		Frames: []string{"◍", "◌"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerToggle9 = SpinnerStyle{
		Frames: []string{"◉", "◎"},
		FPS:    100 * time.Millisecond,
	}
	SpinnerTriangle = SpinnerStyle{
		Frames: []string{"◢", "◣", "◤", "◥"},
		FPS:    50 * time.Millisecond,
	}
	SpinnerWeather = SpinnerStyle{
		Frames: []string{
			"☀️ ",
			"☀️ ",
			"☀️ ",
			"🌤 ",
			"⛅️ ",
			"🌥 ",
			"☁️ ",
			"🌧 ",
			"🌨 ",
			"🌧 ",
			"🌨 ",
			"🌧 ",
			"🌨 ",
			"⛈ ",
			"🌨 ",
			"🌧 ",
			"🌨 ",
			"☁️ ",
			"🌥 ",
			"⛅️ ",
			"🌤 ",
			"☀️ ",
			"☀️ ",
		},
		FPS: 100 * time.Millisecond,
	}
)

Predefined spinner frame sets adapted from https://github.com/sindresorhus/cli-spinners Pass any of these to AnimationBuilder.Style to change the animation style.

View Source
var Default = New(Stdout(ColorAuto))

Default is the default logger instance.

Functions

func ColorsDisabled

func ColorsDisabled() bool

ColorsDisabled returns true if colours are disabled on the Default logger.

func Configure

func Configure(cfg *Config)

Configure sets up the Default logger with the given configuration. Call this once at application startup.

Note: this respects the log level environment variable - it won't reset the level if CLOG_LOG_LEVEL (or a custom prefix equivalent) was set and cfg.Verbose is false.

func Hyperlink(url, text string) string

Hyperlink wraps text in an OSC 8 terminal hyperlink escape sequence. Returns plain text when colours or hyperlinks are disabled globally.

func IsTerminal

func IsTerminal() bool

IsTerminal returns true if the Default logger's output is connected to a terminal.

func IsVerbose

func IsVerbose() bool

IsVerbose returns true if verbose/debug mode is enabled on the Default logger. Returns true for both TraceLevel and DebugLevel.

func NewSlogHandler added in v0.5.0

func NewSlogHandler(logger *Logger, opts *SlogOptions) slog.Handler

NewSlogHandler creates a slog.Handler that routes slog.Record entries through the given clog Logger.

func PathLink(path string, line int) string

PathLink creates a clickable terminal hyperlink for a file path. The line parameter is optional - pass 0 to omit line numbers.

func RegisterLevel added in v0.5.8

func RegisterLevel(level Level, cfg LevelConfig)

RegisterLevel registers a custom log level with the given numeric value and configuration. The level value must not conflict with a built-in level.

After registration the level works with ParseLevel, Level.MarshalText, Level.String, and the Default logger's labels, prefixes, and styles.

RegisterLevel panics if cfg.Name is empty or level conflicts with a built-in level.

func SetAnimationInterval added in v0.5.0

func SetAnimationInterval(d time.Duration)

SetAnimationInterval sets the minimum animation refresh interval on the Default logger.

func SetColorMode

func SetColorMode(mode ColorMode)

SetColorMode sets the colour mode on the Default logger by recreating its Output with the given mode.

func SetElapsedFormatFunc added in v0.4.15

func SetElapsedFormatFunc(fn func(time.Duration) string)

SetElapsedFormatFunc sets the elapsed format function on the Default logger.

func SetElapsedMinimum added in v0.4.15

func SetElapsedMinimum(d time.Duration)

SetElapsedMinimum sets the elapsed minimum threshold on the Default logger.

func SetElapsedPrecision added in v0.4.15

func SetElapsedPrecision(precision int)

SetElapsedPrecision sets the elapsed precision on the Default logger.

func SetElapsedRound added in v0.4.15

func SetElapsedRound(d time.Duration)

SetElapsedRound sets the elapsed rounding granularity on the Default logger.

func SetEnvPrefix added in v0.3.0

func SetEnvPrefix(prefix string)

SetEnvPrefix sets a custom environment variable prefix. Env vars are checked with the custom prefix first, then "CLOG" as fallback.

clog.SetEnvPrefix("MYAPP")
// Now checks MYAPP_LOG_LEVEL, then CLOG_LOG_LEVEL
// Now checks MYAPP_HYPERLINK_PATH_FORMAT, then CLOG_HYPERLINK_PATH_FORMAT
// etc.

func SetExitFunc

func SetExitFunc(fn func(int))

SetExitFunc sets the fatal-exit function on the Default logger.

func SetFieldSort added in v0.4.15

func SetFieldSort(sort Sort)

SetFieldSort sets the field sort order on the Default logger.

func SetFieldStyleLevel added in v0.1.2

func SetFieldStyleLevel(level Level)

SetFieldStyleLevel sets the minimum level for styled fields on the Default logger.

func SetFieldTimeFormat added in v0.1.1

func SetFieldTimeFormat(format string)

SetFieldTimeFormat sets the time format for time fields on the Default logger.

func SetHandler

func SetHandler(h Handler)

SetHandler sets the log handler on the Default logger.

func SetHyperlinkColumnFormat

func SetHyperlinkColumnFormat(format string)

SetHyperlinkColumnFormat configures the URL format for file+line+column hyperlinks (used by [Column]).

Accepts a full format string or a preset name (e.g. "vscode"). Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Use {path}, {line}, and {column} (or {col}) as placeholders. Examples:

  • vscode://file{path}:{line}:{column}
  • idea://open?file={path}&line={line}&column={column}

Default (empty): falls back to the line format.

func SetHyperlinkDirFormat

func SetHyperlinkDirFormat(format string)

SetHyperlinkDirFormat configures the URL format for directory hyperlinks.

Accepts a full format string or a preset name (e.g. "vscode"). Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Falls back to SetHyperlinkPathFormat if not set.

Use {path} as placeholder.

func SetHyperlinkFileFormat

func SetHyperlinkFileFormat(format string)

SetHyperlinkFileFormat configures the URL format for file-only hyperlinks (used by [Path] and PathLink with line 0, when the path is not a directory).

Accepts a full format string or a preset name (e.g. "vscode"). Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Falls back to SetHyperlinkPathFormat if not set.

Use {path} as placeholder.

func SetHyperlinkLineFormat

func SetHyperlinkLineFormat(format string)

SetHyperlinkLineFormat configures the URL format for file+line hyperlinks (used by [Line] and PathLink with line > 0).

Accepts a full format string or a preset name (e.g. "vscode"). Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Use {path} and {line} as placeholders. Examples:

  • vscode://file{path}:{line}
  • idea://open?file={path}&line={line}
  • subl://open?url=file://{path}&line={line}

Default (empty): file://{path}

func SetHyperlinkPathFormat

func SetHyperlinkPathFormat(format string)

SetHyperlinkPathFormat configures the generic fallback URL format for any path. This is used when no file-specific or directory-specific format is configured.

Accepts a full format string or a preset name (e.g. "vscode"). Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Use {path} as placeholder. Examples:

  • vscode://file{path}
  • idea://open?file={path}

Default (empty): file://{path}

func SetHyperlinkPreset added in v0.4.5

func SetHyperlinkPreset(name string) error

SetHyperlinkPreset configures all hyperlink format slots using a named preset. This is a convenience wrapper around the individual SetHyperlink*Format functions.

Known presets: cursor, kitty, macvim, textmate, vscode, vscode-insiders, vscodium.

Individual formats set afterwards (via SetHyperlink*Format or environment variables) override the preset for that specific slot.

func SetHyperlinksEnabled

func SetHyperlinksEnabled(enabled bool)

SetHyperlinksEnabled enables or disables all hyperlink rendering. When disabled, hyperlink functions return plain text without OSC 8 sequences.

func SetIndent added in v0.5.4

func SetIndent(levels int)

SetIndent sets the indent depth on the Default logger.

func SetIndentPrefixSeparator added in v0.5.4

func SetIndentPrefixSeparator(sep string)

SetIndentPrefixSeparator sets the indent prefix separator on the Default logger.

func SetIndentPrefixes added in v0.5.4

func SetIndentPrefixes(prefixes []string)

SetIndentPrefixes sets per-depth indent prefixes on the Default logger.

func SetIndentWidth added in v0.5.4

func SetIndentWidth(width int)

SetIndentWidth sets the indent width on the Default logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets the minimum log level on the Default logger.

func SetLevelAlign

func SetLevelAlign(align Align)

SetLevelAlign sets the level-label alignment on the Default logger.

func SetLevelLabels

func SetLevelLabels(labels LevelMap)

SetLevelLabels sets the level labels on the Default logger.

func SetOmitEmpty

func SetOmitEmpty(omit bool)

SetOmitEmpty enables or disables omitting empty fields on the Default logger.

func SetOmitZero

func SetOmitZero(omit bool)

SetOmitZero enables or disables omitting zero-value fields on the Default logger.

func SetOutput

func SetOutput(out *Output)

SetOutput sets the output on the Default logger.

func SetOutputWriter added in v0.3.1

func SetOutputWriter(w io.Writer)

SetOutputWriter sets the output writer on the Default logger with ColorAuto.

func SetParts

func SetParts(order ...Part)

SetParts sets the log-line part order on the Default logger.

func SetPercentFormatFunc added in v0.4.15

func SetPercentFormatFunc(fn func(float64) string)

SetPercentFormatFunc sets the percent format function on the Default logger.

func SetPercentPrecision added in v0.4.15

func SetPercentPrecision(precision int)

SetPercentPrecision sets the percent precision on the Default logger.

func SetPercentReverseGradient added in v0.5.11

func SetPercentReverseGradient(reverse bool)

SetPercentReverseGradient sets the percent gradient inversion on the Default logger.

func SetPrefixes

func SetPrefixes(prefixes LevelMap)

SetPrefixes sets the level prefixes on the Default logger.

func SetQuantityUnitsIgnoreCase added in v0.4.15

func SetQuantityUnitsIgnoreCase(ignoreCase bool)

SetQuantityUnitsIgnoreCase sets case-insensitive quantity unit matching on the Default logger.

func SetQuoteChar

func SetQuoteChar(char rune)

SetQuoteChar sets the quote character on the Default logger.

func SetQuoteChars

func SetQuoteChars(openChar, closeChar rune)

SetQuoteChars sets the opening and closing quote characters on the Default logger.

func SetQuoteMode

func SetQuoteMode(mode QuoteMode)

SetQuoteMode sets the quoting behaviour on the Default logger.

func SetReportTimestamp

func SetReportTimestamp(report bool)

SetReportTimestamp enables or disables timestamps on the Default logger.

func SetSeparatorText added in v0.4.15

func SetSeparatorText(sep string)

SetSeparatorText sets the key/value separator on the Default logger.

func SetStyles

func SetStyles(styles *Styles)

SetStyles sets the display styles on the Default logger.

func SetTimeFormat

func SetTimeFormat(format string)

SetTimeFormat sets the timestamp format on the Default logger.

func SetTimeLocation

func SetTimeLocation(loc *time.Location)

SetTimeLocation sets the timestamp timezone on the Default logger.

func SetTreeChars added in v0.5.6

func SetTreeChars(chars TreeChars)

SetTreeChars sets the tree-drawing characters on the Default logger.

func SetVerbose added in v0.3.0

func SetVerbose(verbose bool)

SetVerbose enables or disables verbose mode on the Default logger. When verbose is true, it always enables debug logging. When false, it respects the log level environment variable if set.

func WithContext added in v0.5.0

func WithContext(ctx context.Context) context.Context

WithContext stores the Default logger in ctx.

Types

type Align added in v0.4.17

type Align int

Align controls how text is aligned within a fixed-width column.

const (
	// AlignNone disables alignment padding.
	AlignNone Align = iota
	// AlignLeft left-aligns text (pads with trailing spaces).
	AlignLeft
	// AlignRight right-aligns text (pads with leading spaces).
	AlignRight
	// AlignCenter center-aligns text (pads with leading and trailing spaces).
	AlignCenter
)

type AnimationBuilder added in v0.4.2

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

AnimationBuilder configures an animation before execution. Create one with Spinner, Pulse, Shimmer, or Bar, or their Logger method equivalents.

func Bar added in v0.5.0

func Bar(msg string, total int) *AnimationBuilder

Bar creates a new AnimationBuilder using the Default logger with a determinate progress bar animation. total is the maximum progress value. Use ProgressUpdate.SetProgress to update progress.

func Pulse added in v0.4.2

func Pulse(msg string, stops ...ColorStop) *AnimationBuilder

Pulse creates a new AnimationBuilder using the Default logger with an animated color pulse on the message text. All characters fade uniformly between colors in the gradient. With no arguments, the default pulse gradient is used. Custom gradient stops can be passed to override the default.

func Shimmer added in v0.4.2

func Shimmer(msg string, stops ...ColorStop) *AnimationBuilder

Shimmer creates a new AnimationBuilder using the Default logger with an animated gradient shimmer on the message text. Each character is coloured independently based on its position in the wave. With no arguments, the default shimmer gradient is used. Custom gradient stops can be passed to override the default.

func Spinner

func Spinner(msg string) *AnimationBuilder

Spinner creates a new AnimationBuilder using the Default logger with a rotating spinner animation.

func (*AnimationBuilder) After added in v0.4.18

After sets a delay before the animation becomes visible. If the task completes before the delay elapses, no animation is shown at all. This is useful for operations that are usually fast but occasionally slow - the animation only appears when needed, avoiding visual noise.

func (*AnimationBuilder) Any added in v0.4.2

func (fb *AnimationBuilder) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*AnimationBuilder) Anys added in v0.4.2

func (fb *AnimationBuilder) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*AnimationBuilder) BarPercent added in v0.5.0

func (b *AnimationBuilder) BarPercent(key string) *AnimationBuilder

BarPercent enables an auto-updating percentage field that is injected on each animation tick for Bar animations. The key parameter is the field name (e.g. "progress"). When set, the default right-side percent widget is suppressed so the percentage appears only as a structured field.

The field respects the position where BarPercent is called relative to other field methods (e.g. Str, Int) on the builder. No-op for non-bar animations.

func (*AnimationBuilder) Base64 added in v0.4.8

func (fb *AnimationBuilder) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*AnimationBuilder) Bool added in v0.4.2

func (fb *AnimationBuilder) Bool(key string, val bool) *T

Bool adds a bool field.

func (*AnimationBuilder) Bools added in v0.4.2

func (fb *AnimationBuilder) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*AnimationBuilder) Bytes added in v0.4.7

func (fb *AnimationBuilder) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*AnimationBuilder) Column added in v0.4.2

func (b *AnimationBuilder) Column(key, path string, line, column int) *AnimationBuilder

Column adds a file path field with a line and column number as a clickable terminal hyperlink. Uses the builder's logger's Output setting.

func (*AnimationBuilder) Dedent added in v0.5.5

func (b *AnimationBuilder) Dedent() *AnimationBuilder

Dedent removes one indent level from the animation output, down to a minimum of zero. Mirrors AnimationBuilder.Indent.

func (*AnimationBuilder) Depth added in v0.5.4

func (b *AnimationBuilder) Depth(n int) *AnimationBuilder

Depth adds multiple indent levels to the animation output. Equivalent to calling AnimationBuilder.Indent n times.

func (*AnimationBuilder) Duration added in v0.4.2

func (fb *AnimationBuilder) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*AnimationBuilder) Durations added in v0.4.2

func (fb *AnimationBuilder) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*AnimationBuilder) Elapsed added in v0.4.14

func (b *AnimationBuilder) Elapsed(key string) *AnimationBuilder

Elapsed enables an auto-updating elapsed-time field that is injected on each animation tick and included in the final completion log. The key parameter is the field name (e.g. "elapsed"). The value is formatted using [formatElapsed] with [Styles.ElapsedPrecision].

The field respects the position where Elapsed is called relative to other field methods (e.g. Str, Int) on the builder.

func (*AnimationBuilder) Err added in v0.4.4

func (fb *AnimationBuilder) Err(err error) *T

Err adds an error field with key "error". No-op if err is nil.

Unlike Event.Err, context errors are always stored as a field because context fields have no Send/Msg finalisation semantics.

func (*AnimationBuilder) Errs added in v0.4.10

func (fb *AnimationBuilder) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*AnimationBuilder) Float64 added in v0.4.2

func (fb *AnimationBuilder) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*AnimationBuilder) Floats64 added in v0.4.2

func (fb *AnimationBuilder) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*AnimationBuilder) Hex added in v0.4.8

func (fb *AnimationBuilder) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*AnimationBuilder) Indent added in v0.5.4

func (b *AnimationBuilder) Indent() *AnimationBuilder

Indent adds one indent level to the animation output. Chainable.

func (*AnimationBuilder) Int added in v0.4.2

func (fb *AnimationBuilder) Int(key string, val int) *T

Int adds an int field.

func (*AnimationBuilder) Int64 added in v0.4.2

func (fb *AnimationBuilder) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*AnimationBuilder) Ints added in v0.4.2

func (fb *AnimationBuilder) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*AnimationBuilder) Ints64 added in v0.4.4

func (fb *AnimationBuilder) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*AnimationBuilder) JSON added in v0.4.4

func (fb *AnimationBuilder) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*AnimationBuilder) Line added in v0.4.2

func (b *AnimationBuilder) Line(key, path string, line int) *AnimationBuilder

Line adds a file path field with a line number as a clickable terminal hyperlink. Uses the builder's logger's Output setting.

func (b *AnimationBuilder) Link(key, url, text string) *AnimationBuilder

Link adds a field as a clickable terminal hyperlink with custom URL and display text. Uses the builder's logger's Output setting.

func (*AnimationBuilder) Parts added in v0.5.1

func (b *AnimationBuilder) Parts(parts ...Part) *AnimationBuilder

Parts overrides the log-line part order for this animation and its completion message. Parts not included are hidden.

func (*AnimationBuilder) Path added in v0.4.2

func (b *AnimationBuilder) Path(key, path string) *AnimationBuilder

Path adds a file path field as a clickable terminal hyperlink. Uses the builder's logger's Output setting.

func (*AnimationBuilder) Percent added in v0.4.2

func (fb *AnimationBuilder) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*AnimationBuilder) Prefix added in v0.4.2

func (b *AnimationBuilder) Prefix(prefix string) *AnimationBuilder

Prefix sets the icon displayed beside the message during animation. For Pulse and Shimmer this defaults to "⏳". For Spinner the prefix is the current spinner frame and this setting is ignored.

func (*AnimationBuilder) Progress added in v0.4.2

func (b *AnimationBuilder) Progress(
	ctx context.Context,
	task ProgressTaskFunc,
) *WaitResult

Progress executes the task with the animation whose message and fields can be updated via the ProgressUpdate builder. This is useful for multi-step operations where the animation should reflect the current step.

func (*AnimationBuilder) Quantities added in v0.4.2

func (fb *AnimationBuilder) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*AnimationBuilder) Quantity added in v0.4.2

func (fb *AnimationBuilder) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*AnimationBuilder) RawJSON added in v0.4.4

func (fb *AnimationBuilder) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*AnimationBuilder) ShimmerDirection added in v0.4.2

func (b *AnimationBuilder) ShimmerDirection(d Direction) *AnimationBuilder

ShimmerDirection sets the direction the shimmer wave travels. Defaults to DirectionRight. Use DirectionLeft to reverse or DirectionMiddleIn for a wave entering from both edges. Only meaningful when the builder was created with Shimmer.

func (*AnimationBuilder) Speed added in v0.5.0

func (b *AnimationBuilder) Speed(speed Speed) *AnimationBuilder

Speed sets the number of full animation cycles per second. For Shimmer this controls how fast the gradient wave sweeps across the text (default 0.5). For Pulse this controls the oscillation rate (default 0.5). Higher values produce faster animation. Values <= 0 are treated as the default.

func (*AnimationBuilder) Str added in v0.4.2

func (fb *AnimationBuilder) Str(key, val string) *T

Str adds a string field.

func (*AnimationBuilder) Stringer added in v0.4.4

func (fb *AnimationBuilder) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*AnimationBuilder) Stringers added in v0.4.4

func (fb *AnimationBuilder) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*AnimationBuilder) Strs added in v0.4.2

func (fb *AnimationBuilder) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*AnimationBuilder) Style added in v0.5.0

Style sets the animation style. Pass a SpinnerStyle for spinner animations or a BarStyle for bar animations.

func (*AnimationBuilder) Time added in v0.4.2

func (fb *AnimationBuilder) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*AnimationBuilder) Times added in v0.4.17

func (fb *AnimationBuilder) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*AnimationBuilder) Tree added in v0.5.6

Tree adds one tree-nesting level with the given position to the animation output. Chainable. See Context.Tree for details on tree indentation.

func (*AnimationBuilder) URL added in v0.4.2

func (b *AnimationBuilder) URL(key, url string) *AnimationBuilder

URL adds a field as a clickable terminal hyperlink where the URL is also the display text. Uses the builder's logger's Output setting.

func (*AnimationBuilder) Uint added in v0.4.2

func (fb *AnimationBuilder) Uint(key string, val uint) *T

Uint adds a uint field.

func (*AnimationBuilder) Uint64 added in v0.4.2

func (fb *AnimationBuilder) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*AnimationBuilder) Uints added in v0.4.4

func (fb *AnimationBuilder) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*AnimationBuilder) Uints64 added in v0.4.2

func (fb *AnimationBuilder) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*AnimationBuilder) Wait added in v0.4.2

func (b *AnimationBuilder) Wait(ctx context.Context, task TaskFunc) *WaitResult

Wait executes the task with the animation and returns a WaitResult for chaining. The animation displays as: <level> <icon> <message> <fields>.

func (*AnimationBuilder) When added in v0.5.1

func (fb *AnimationBuilder) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type AnimationStyle added in v0.5.0

type AnimationStyle interface {
	// contains filtered or unexported methods
}

AnimationStyle is an animation style that can be passed to AnimationBuilder.Style. Valid implementations are SpinnerStyle and BarStyle.

type BarAlign added in v0.5.0

type BarAlign int

BarAlign controls the horizontal placement of the progress bar within the terminal line.

const (
	// BarAlignRightPad pushes the bar to the right edge of the terminal (default).
	BarAlignRightPad BarAlign = iota
	// BarAlignLeftPad places the bar before the message, padding the message to the right edge.
	BarAlignLeftPad
	// BarAlignInline places the bar immediately after the message with no gap.
	BarAlignInline
	// BarAlignLeft places the bar before the message with no padding.
	BarAlignLeft
	// BarAlignRight places the bar after the message with no padding.
	BarAlignRight
)

type BarState added in v0.5.0

type BarState struct {
	Current int
	Total   int
	Elapsed time.Duration
	Rate    float64 // items per second (0 when elapsed or current is 0)
}

BarState holds progress information passed to BarWidget functions.

type BarStyle added in v0.5.0

type BarStyle struct {
	Align            BarAlign    // horizontal bar placement; default BarAlignRightPad
	CapLeft          string      // left bracket; default "["
	CapRight         string      // right bracket; default "]"
	CapStyle         Style       // lipgloss style for left/right caps; nil = plain text
	CharEmpty        rune        // full empty cell; default '─'
	CharFill         rune        // full filled cell; default '━'
	CharHead         rune        // decorative head at leading edge (1x resolution); 0 = disabled; ignored when HalfFilled is set
	GradientFill     []rune      // sub-cell fill chars, least→most filled; enables Nx resolution (N = len+1); overrides HalfFilled/CharHead
	HalfEmpty        rune        // half-cell at start of empty when HalfFilled is not shown; 0 = disabled
	HalfFilled       rune        // half-cell at leading edge of filled (enables 2x resolution); 0 = disabled
	ProgressGradient []ColorStop // when set, colors filled cells based on progress; overrides StyleFill foreground
	Separator        string      // separator between message, bar, and widget text; default " "
	StyleEmpty       Style       // lipgloss style for empty cells; nil = plain text
	StyleFill        Style       // lipgloss style for filled cells; nil = plain text
	Width            int         // fixed inner width; 0 = auto-size
	WidgetLeft       BarWidget   // widget to the left of the bar; nil = nothing
	WidgetRight      BarWidget   // widget to the right of the bar; nil = default padded percent
	WidthMax         int         // maximum auto-sized width; default 40
	WidthMin         int         // minimum auto-sized width; default 10
}

BarStyle configures the visual appearance of a determinate progress bar.

func DefaultBarStyle added in v0.5.0

func DefaultBarStyle() BarStyle

DefaultBarStyle returns the default BarStyle. It uses box-drawing characters with half-cell resolution for smooth progress.

type BarWidget added in v0.5.0

type BarWidget func(BarState) string

BarWidget renders a text label from the current bar state. Return "" to display nothing for this tick.

var WidgetNone BarWidget = func(BarState) string { return "" }

WidgetNone is a BarWidget that always returns "". Use it to explicitly suppress the default percent display.

func WidgetBytes added in v0.5.0

func WidgetBytes(opts ...WidgetOption) BarWidget

WidgetBytes returns a BarWidget that displays download-style progress in human-readable SI byte units (e.g. "1.5 GB / 2 GB"). The BarState Current and Total fields are interpreted as byte counts. Uses base-1000 units (kB, MB, GB). See WidgetIBytes for base-1024 (KiB, MiB, GiB). Default digits is 3; use WithDigits to change.

func WidgetBytesRate added in v0.5.3

func WidgetBytesRate(opts ...WidgetOption) BarWidget

WidgetBytesRate returns a BarWidget that displays throughput in SI byte units per second (e.g. "82.9 MB/s", "1.5 GB/s"). The result is right-aligned to the widest value seen so far to prevent the bar from jumping. Reuses the SI formatting from [humanBytes].

func WidgetETA added in v0.5.3

func WidgetETA(opts ...WidgetOption) BarWidget

WidgetETA returns a BarWidget that displays the estimated time remaining based on elapsed time and current progress (e.g. "ETA 2m30s", "ETA 5s"). The result is right-aligned to the widest value seen so far to prevent the bar from jumping as the ETA shrinks. Returns "" when the bar is complete (current >= total), "ETA ∞" when the rate is zero (no progress yet).

func WidgetIBytes added in v0.5.0

func WidgetIBytes(opts ...WidgetOption) BarWidget

WidgetIBytes returns a BarWidget that displays download-style progress in human-readable IEC byte units (e.g. "1.5 GiB / 2 GiB"). The BarState Current and Total fields are interpreted as byte counts. Uses base-1024 units (KiB, MiB, GiB). See WidgetBytes for base-1000 (kB, MB, GB). Default digits is 3; use WithDigits to change.

func WidgetIBytesRate added in v0.5.3

func WidgetIBytesRate(opts ...WidgetOption) BarWidget

WidgetIBytesRate returns a BarWidget that displays throughput in IEC byte units per second (e.g. "82.9 MiB/s", "1.5 GiB/s"). The result is right-aligned to the widest value seen so far to prevent the bar from jumping. Reuses the IEC formatting from [humanIBytes].

func WidgetPercent added in v0.5.0

func WidgetPercent(opts ...WidgetOption) BarWidget

WidgetPercent returns a BarWidget that displays padded percentage text (e.g. " 0%", " 50%", "100%"). The result is right-aligned to a fixed width to prevent the bar from jumping as digit count changes. Default digits is 0; use WithDigits for decimal places (1 → " 50%", "42.5%"). Trailing zeros are always stripped ("100.0%" → "100%").

func WidgetRate added in v0.5.3

func WidgetRate(opts ...WidgetOption) BarWidget

WidgetRate returns a BarWidget that displays throughput in items per second (e.g. "150/s", "1.5k/s"). The result is right-aligned to the widest value seen so far to prevent the bar from jumping. Use WithUnit to add a label: "150 ops/s".

func WidgetSeparator added in v0.5.7

func WidgetSeparator(s string, opts ...WidgetOption) BarWidget

WidgetSeparator returns a BarWidget that always renders the given string. Use it inside Widgets to place a visual divider between other widgets:

style.WidgetRight = clog.Widgets(clog.WidgetETA(), clog.WidgetSeparator("│"), clog.WidgetRate())

Pass WithStyle to apply a lipgloss style to the separator:

sep := new(lipgloss.NewStyle().Faint(true))
style.WidgetRight = clog.Widgets(clog.WidgetETA(), clog.WidgetSeparator("│", clog.WithStyle(sep)), clog.WidgetRate())

func Widgets added in v0.5.7

func Widgets(widgets ...BarWidget) BarWidget

Widgets combines multiple BarWidget functions into a single BarWidget. The outputs are joined with a space separator; empty outputs are skipped.

style.WidgetRight = clog.Widgets(clog.WidgetETA(), clog.WidgetRate())

type ColorMode

type ColorMode int

ColorMode controls how a Logger determines colour and hyperlink output.

ColorMode implements encoding.TextMarshaler and encoding.TextUnmarshaler, so it works directly with flag.TextVar and most flag libraries.

const (
	// ColorAuto uses global detection (terminal, NO_COLOR, etc.). This is the default.
	ColorAuto ColorMode = iota // auto
	// ColorAlways forces colours and hyperlinks, even when output is not a TTY.
	ColorAlways // always
	// ColorNever disables colours and hyperlinks.
	ColorNever // never
)

func (ColorMode) MarshalText added in v0.3.0

func (m ColorMode) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (ColorMode) String added in v0.3.0

func (i ColorMode) String() string

func (*ColorMode) UnmarshalText added in v0.3.0

func (m *ColorMode) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type ColorStop added in v0.3.0

type ColorStop struct {
	Position float64        // 0.0-1.0
	Color    colorful.Color // from github.com/lucasb-eyer/go-colorful
}

ColorStop defines a color at a specific position along a gradient. Position is in the range 0.0-1.0.

func DefaultBarGradient added in v0.5.0

func DefaultBarGradient() []ColorStop

DefaultBarGradient returns the default red → yellow → green gradient used for [BarStyle.ProgressGradient].

func DefaultPercentGradient added in v0.3.0

func DefaultPercentGradient() []ColorStop

DefaultPercentGradient returns the default red → yellow → green gradient used for [Styles.PercentGradient].

func DefaultPulseGradient added in v0.4.0

func DefaultPulseGradient() []ColorStop

DefaultPulseGradient returns a three-stop gradient for pulse effects: pastel light blue fading through light green to white.

func DefaultShimmerGradient added in v0.4.0

func DefaultShimmerGradient() []ColorStop

DefaultShimmerGradient returns a wave-shaped gradient for shimmer effects: a subtle red-to-green-to-blue cycle that wraps seamlessly.

type Config

type Config struct {
	// Output is the output to use (defaults to [Stdout]([ColorAuto])).
	Output *Output
	// Styles allows customising the visual styles.
	Styles *Styles
	// Verbose enables debug level logging and timestamps.
	Verbose bool
}

Config holds configuration options for the Default logger.

type Context

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

Context builds a sub-logger with preset fields. Created by Logger.With. Finalise with Context.Logger.

func With

func With() *Context

With returns a Context for building a sub-logger from the Default logger.

func (*Context) Any

func (fb *Context) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*Context) Anys

func (fb *Context) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*Context) Base64 added in v0.4.8

func (fb *Context) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*Context) Bool

func (fb *Context) Bool(key string, val bool) *T

Bool adds a bool field.

func (*Context) Bools

func (fb *Context) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*Context) Bytes added in v0.4.7

func (fb *Context) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*Context) Column

func (c *Context) Column(key, path string, line, column int) *Context

Column adds a file path field with a line and column number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (*Context) Dedent added in v0.5.5

func (c *Context) Dedent() *Context

Dedent removes one indent level from the sub-logger, down to a minimum of zero. Useful for pulling a child logger back toward the root when a parent logger is already indented.

func (*Context) Depth added in v0.5.4

func (c *Context) Depth(n int) *Context

Depth adds multiple indent levels at once. Equivalent to calling Context.Indent n times.

func (*Context) Dict

func (c *Context) Dict(key string, dict *Event) *Context

Dict adds a group of fields under a key prefix using dot notation. Build the nested fields using Dict to create a field-only Event:

logger := clog.With().Dict("db", clog.Dict().
    Str("host", "localhost").
    Int("port", 5432),
).Logger()

func (*Context) Duration added in v0.2.2

func (fb *Context) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*Context) Durations added in v0.2.2

func (fb *Context) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*Context) Err

func (fb *Context) Err(err error) *T

Err adds an error field with key "error". No-op if err is nil.

Unlike Event.Err, context errors are always stored as a field because context fields have no Send/Msg finalisation semantics.

func (*Context) Errs added in v0.4.10

func (fb *Context) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*Context) Float64

func (fb *Context) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*Context) Floats64

func (fb *Context) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*Context) Hex added in v0.4.8

func (fb *Context) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*Context) Indent added in v0.5.4

func (c *Context) Indent() *Context

Indent adds one indent level to the sub-logger. Chainable: With().Indent().Indent().Logger() produces two levels of indentation.

func (*Context) Int

func (fb *Context) Int(key string, val int) *T

Int adds an int field.

func (*Context) Int64 added in v0.4.1

func (fb *Context) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*Context) Ints

func (fb *Context) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*Context) Ints64 added in v0.4.4

func (fb *Context) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*Context) JSON added in v0.4.4

func (fb *Context) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*Context) Line

func (c *Context) Line(key, path string, line int) *Context

Line adds a file path field with a line number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (c *Context) Link(key, url, text string) *Context

Link adds a field as a clickable terminal hyperlink with custom URL and display text. Respects the logger's ColorMode setting.

func (*Context) Logger

func (c *Context) Logger() *Logger

Logger returns a new Logger with the accumulated fields and prefix. The returned Logger shares the parent's mutex to prevent interleaved output.

func (*Context) Path

func (c *Context) Path(key, path string) *Context

Path adds a file path field as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (*Context) Percent added in v0.3.0

func (fb *Context) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*Context) Prefix

func (c *Context) Prefix(prefix string) *Context

Prefix sets a custom prefix for the sub-logger.

func (*Context) Quantities added in v0.2.2

func (fb *Context) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*Context) Quantity added in v0.2.2

func (fb *Context) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*Context) RawJSON added in v0.4.4

func (fb *Context) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*Context) Str

func (fb *Context) Str(key, val string) *T

Str adds a string field.

func (*Context) Stringer

func (fb *Context) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*Context) Stringers

func (fb *Context) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*Context) Strs

func (fb *Context) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*Context) Time added in v0.1.1

func (fb *Context) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*Context) Times added in v0.4.17

func (fb *Context) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*Context) Tree added in v0.5.6

func (c *Context) Tree(pos TreePos) *Context

Tree adds one tree-nesting level with the given position. Each call deepens the tree by one level, drawing box-drawing connectors (├──, └──, │) automatically. Combine with Context.Indent to add space-based indent before the tree connectors.

func (*Context) URL added in v0.2.1

func (c *Context) URL(key, url string) *Context

URL adds a field as a clickable terminal hyperlink where the URL is also the display text. Respects the logger's ColorMode setting.

func (*Context) Uint added in v0.4.1

func (fb *Context) Uint(key string, val uint) *T

Uint adds a uint field.

func (*Context) Uint64

func (fb *Context) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*Context) Uints added in v0.4.4

func (fb *Context) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*Context) Uints64

func (fb *Context) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*Context) When added in v0.5.1

func (fb *Context) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type Direction added in v0.4.0

type Direction int

Direction controls which way an animation travels.

const (
	// DirectionRight moves the shimmer wave from left to right (default).
	DirectionRight Direction = iota
	// DirectionLeft moves the shimmer wave from right to left.
	DirectionLeft
	// DirectionMiddleIn sends the shimmer wave inward from both edges.
	DirectionMiddleIn
	// DirectionMiddleOut sends the shimmer wave outward from the center.
	DirectionMiddleOut
	// DirectionBounceIn sends the shimmer wave inward from both edges, then
	// bounces it back outward, creating a ping-pong effect.
	DirectionBounceIn
	// DirectionBounceOut sends the shimmer wave outward from the center, then
	// bounces it back inward, creating a ping-pong effect.
	DirectionBounceOut
)

type DividerBuilder added in v0.5.1

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

DividerBuilder configures and renders a horizontal divider line. Create one with Logger.Divider or the package-level Divider function.

Call DividerBuilder.Send to render a plain line, or DividerBuilder.Msg to render a line with an embedded title:

clog.Divider().Send()
clog.Divider().Msg("Build Phase")
clog.Divider().Char('═').Align(AlignCenter).Msg("Results")

func Divider added in v0.5.1

func Divider() *DividerBuilder

Divider returns a new DividerBuilder for rendering a horizontal rule using the Default logger.

func (*DividerBuilder) Align added in v0.5.1

func (b *DividerBuilder) Align(align Align) *DividerBuilder

Align sets the title alignment within the divider line. Default is AlignLeft.

func (*DividerBuilder) Char added in v0.5.1

func (b *DividerBuilder) Char(char rune) *DividerBuilder

Char sets the character used for the divider line. Default is '─'.

func (*DividerBuilder) Msg added in v0.5.1

func (b *DividerBuilder) Msg(title string)

Msg renders the divider with the given title text.

func (*DividerBuilder) Send added in v0.5.1

func (b *DividerBuilder) Send()

Send renders a plain divider line without a title.

func (*DividerBuilder) Width added in v0.5.1

func (b *DividerBuilder) Width(width int) *DividerBuilder

Width overrides the divider width in columns. By default the terminal width is used, falling back to 80 for non-TTY output.

type Entry

type Entry struct {
	Time    time.Time `json:"time,omitzero"`
	Level   Level     `json:"level"`
	Prefix  string    `json:"prefix,omitempty"`
	Indent  int       `json:"indent,omitempty"`
	Message string    `json:"message"`
	Fields  []Field   `json:"fields,omitempty"`
	Tree    []TreePos `json:"tree,omitempty"`
}

Entry represents a completed log entry passed to a Handler.

type Event

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

Event represents a log event being constructed. All methods are safe to call on a nil receiver - disabled events (when the log level is below the logger's minimum) are no-ops.

func Debug

func Debug() *Event

Debug returns a new debug-level Event from the Default logger.

func Dict

func Dict() *Event

Dict returns a new detached Event for use as a nested dictionary field.

func Dry

func Dry() *Event

Dry returns a new dry-level Event from the Default logger.

func Error

func Error() *Event

Error returns a new error-level Event from the Default logger.

func Fatal

func Fatal() *Event

Fatal returns a new fatal-level Event from the Default logger.

func Info

func Info() *Event

Info returns a new info-level Event from the Default logger.

func Log added in v0.5.8

func Log(level Level) *Event

Log returns a new Event at the given level from the Default logger. Use this for custom levels registered with RegisterLevel.

func Trace

func Trace() *Event

Trace returns a new trace-level Event from the Default logger.

func Warn

func Warn() *Event

Warn returns a new warn-level Event from the Default logger.

func (*Event) Any

func (e *Event) Any(key string, val any) *Event

Any adds a field with an arbitrary value.

func (*Event) Anys

func (e *Event) Anys(key string, vals []any) *Event

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*Event) Base64 added in v0.4.8

func (e *Event) Base64(key string, val []byte) *Event

Base64 adds a []byte field encoded as a base64 string.

func (*Event) Bool

func (e *Event) Bool(key string, val bool) *Event

Bool adds a bool field.

func (*Event) Bools

func (e *Event) Bools(key string, vals []bool) *Event

Bools adds a bool slice field.

func (*Event) Bytes added in v0.4.7

func (e *Event) Bytes(key string, val []byte) *Event

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*Event) Column

func (e *Event) Column(key, path string, line, column int) *Event

Column adds a file path field with a line and column number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (*Event) Dict

func (e *Event) Dict(key string, dict *Event) *Event

Dict adds a group of fields under a key prefix using dot notation. Build the nested fields using Dict to create a field-only Event:

clog.Info().Dict("request", clog.Dict().
    Str("method", "GET").
    Int("status", 200),
).Msg("handled")
// Output: INF ℹ️ handled request.method=GET request.status=200

func (*Event) Duration added in v0.2.2

func (e *Event) Duration(key string, val time.Duration) *Event

Duration adds a time.Duration field.

func (*Event) Durations added in v0.2.2

func (e *Event) Durations(key string, vals []time.Duration) *Event

Durations adds a time.Duration slice field.

func (*Event) Elapsed added in v0.5.1

func (e *Event) Elapsed(key string) *Event

Elapsed adds an elapsed-time field at the current position in the field list. The duration is measured from the first Elapsed call on this event until the event is finalised with Event.Send, Event.Msg, or Event.Msgf.

The key parameter is the field name (e.g. "elapsed"). The field uses the same formatting and styling as AnimationBuilder.Elapsed.

e := clog.Info().Str("step", "migrate").Elapsed("elapsed")
runMigrations()
e.Msg("done")
// Output: INF ℹ️ done step=migrate elapsed=2s

func (*Event) Err

func (e *Event) Err(err error) *Event

Err attaches an error to the event. No-op if err is nil.

If the event is finalised with Event.Send, the error message becomes the log message with no extra fields. If finalised with Event.Msg or Event.Msgf, the error is added as an "error" field alongside the message.

func (*Event) Errs added in v0.4.10

func (e *Event) Errs(key string, vals []error) *Event

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*Event) Float64

func (e *Event) Float64(key string, val float64) *Event

Float64 adds a float64 field.

func (*Event) Floats64

func (e *Event) Floats64(key string, vals []float64) *Event

Floats64 adds a float64 slice field.

func (*Event) Func added in v0.4.10

func (e *Event) Func(fn func(*Event)) *Event

Func executes fn with the event if the event is enabled (non-nil). This is useful for computing expensive fields lazily - the callback is skipped entirely when the log level is disabled.

func (*Event) Hex added in v0.4.8

func (e *Event) Hex(key string, val []byte) *Event

Hex adds a []byte field encoded as a hex string.

func (*Event) Int

func (e *Event) Int(key string, val int) *Event

Int adds an int field.

func (*Event) Int64 added in v0.4.1

func (e *Event) Int64(key string, val int64) *Event

Int64 adds an int64 field.

func (*Event) Ints

func (e *Event) Ints(key string, vals []int) *Event

Ints adds an int slice field.

func (*Event) Ints64 added in v0.4.4

func (e *Event) Ints64(key string, vals []int64) *Event

Ints64 adds an int64 slice field.

func (*Event) JSON added in v0.4.4

func (e *Event) JSON(key string, val any) *Event

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*Event) Line

func (e *Event) Line(key, path string, line int) *Event

Line adds a file path field with a line number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (e *Event) Link(key, url, text string) *Event

Link adds a field as a clickable terminal hyperlink with custom URL and display text. Respects the logger's ColorMode setting.

func (*Event) Msg

func (e *Event) Msg(msg string)

Msg finalises the event and writes the log entry. If Event.Err was called, the error is included as an "error" field. For FatalLevel events, Msg calls os.Exit(1) after writing.

func (*Event) Msgf

func (e *Event) Msgf(format string, args ...any)

Msgf finalises the event with a formatted message.

func (*Event) Parts added in v0.5.1

func (e *Event) Parts(parts ...Part) *Event

Parts overrides the log-line part order for this entry. Parts not included are hidden. This does not affect the logger's global parts.

func (*Event) Path

func (e *Event) Path(key, path string) *Event

Path adds a file path field as a clickable terminal hyperlink. Respects the logger's ColorMode setting.

func (*Event) Percent added in v0.3.0

func (e *Event) Percent(key string, val float64, opts ...PercentOption) *Event

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

Use WithPercentReverseGradient to flip the gradient for this field:

e.Percent("cpu", usage, clog.WithPercentReverseGradient())

func (*Event) Prefix

func (e *Event) Prefix(prefix string) *Event

Prefix overrides the default emoji prefix for this entry.

func (*Event) Quantities added in v0.2.2

func (e *Event) Quantities(key string, vals []string) *Event

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*Event) Quantity added in v0.2.2

func (e *Event) Quantity(key, val string) *Event

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*Event) RawJSON added in v0.4.4

func (e *Event) RawJSON(key string, val []byte) *Event

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*Event) Send

func (e *Event) Send()

Send finalises the event. If Event.Err was called, the error message is used as the log message (no "error" field is added). Any other fields on the event are preserved. If Event.Err was not called, the message is empty.

func (*Event) Str

func (e *Event) Str(key, val string) *Event

Str adds a string field.

func (*Event) Stringer

func (e *Event) Stringer(key string, val fmt.Stringer) *Event

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*Event) Stringers

func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event

Stringers adds a field with a slice of fmt.Stringer values.

func (*Event) Strs

func (e *Event) Strs(key string, vals []string) *Event

Strs adds a string slice field.

func (*Event) Time added in v0.1.1

func (e *Event) Time(key string, val time.Time) *Event

Time adds a time.Time field.

func (*Event) Times added in v0.4.4

func (e *Event) Times(key string, vals []time.Time) *Event

Times adds a time.Time slice field.

func (*Event) URL added in v0.2.1

func (e *Event) URL(key, url string) *Event

URL adds a field as a clickable terminal hyperlink where the URL is also the display text. Respects the logger's ColorMode setting.

func (*Event) Uint added in v0.4.1

func (e *Event) Uint(key string, val uint) *Event

Uint adds a uint field.

func (*Event) Uint64

func (e *Event) Uint64(key string, val uint64) *Event

Uint64 adds a uint64 field.

func (*Event) Uints added in v0.4.4

func (e *Event) Uints(key string, vals []uint) *Event

Uints adds a uint slice field.

func (*Event) Uints64

func (e *Event) Uints64(key string, vals []uint64) *Event

Uints64 adds a uint64 slice field.

func (*Event) When added in v0.5.1

func (e *Event) When(condition bool, fn func(*Event)) *Event

When calls fn with the event if condition is true and the event is enabled (non-nil). This is useful for conditionally adding fields without breaking the chain.

type Field

type Field struct {
	Key   string `json:"key"`
	Value any    `json:"value"`
}

Field is a typed key-value pair attached to a log entry.

type Group added in v0.5.0

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

Group manages a set of concurrent animations rendered as a multi-line block. Create one with Group or Logger.Group, add animations with Group.Add, then call Group.Wait to run the render loop.

func NewGroup added in v0.5.0

func NewGroup(ctx context.Context) *Group

NewGroup creates a new animation group using the Default logger.

func (*Group) Add added in v0.5.0

func (g *Group) Add(b *AnimationBuilder) *GroupEntry

Add registers an animation builder with the group and returns a GroupEntry for starting the task.

func (*Group) Wait added in v0.5.0

func (g *Group) Wait() *GroupResult

Wait runs the render loop, blocking until all tasks complete or the context is cancelled. After Wait returns, each task's err field is populated. The returned GroupResult can be used to log a single summary line; alternatively, use individual TaskResult values for per-task messages.

type GroupEntry added in v0.5.0

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

GroupEntry is returned by Group.Add and provides [Run] and [Progress] methods to start a task within the group.

func (*GroupEntry) Progress added in v0.5.0

func (ge *GroupEntry) Progress(task ProgressTaskFunc) *TaskResult

Progress starts a task with progress update capability and returns a TaskResult.

func (*GroupEntry) Run added in v0.5.0

func (ge *GroupEntry) Run(task TaskFunc) *TaskResult

Run starts a simple task (no progress updates) and returns a TaskResult.

type GroupResult added in v0.5.0

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

GroupResult holds the aggregate result of a Group.Wait and allows chaining a single summary log line instead of per-task messages.

func (*GroupResult) Any added in v0.5.0

func (fb *GroupResult) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*GroupResult) Anys added in v0.5.0

func (fb *GroupResult) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*GroupResult) Base64 added in v0.5.0

func (fb *GroupResult) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*GroupResult) Bool added in v0.5.0

func (fb *GroupResult) Bool(key string, val bool) *T

Bool adds a bool field.

func (*GroupResult) Bools added in v0.5.0

func (fb *GroupResult) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*GroupResult) Bytes added in v0.5.0

func (fb *GroupResult) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*GroupResult) Duration added in v0.5.0

func (fb *GroupResult) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*GroupResult) Durations added in v0.5.0

func (fb *GroupResult) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*GroupResult) Err added in v0.5.0

func (r *GroupResult) Err() error

Err returns the joined error, logging success at info level or failure at error level using the original message.

func (*GroupResult) Errs added in v0.5.0

func (fb *GroupResult) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*GroupResult) Float64 added in v0.5.0

func (fb *GroupResult) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*GroupResult) Floats64 added in v0.5.0

func (fb *GroupResult) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*GroupResult) Hex added in v0.5.0

func (fb *GroupResult) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*GroupResult) Int added in v0.5.0

func (fb *GroupResult) Int(key string, val int) *T

Int adds an int field.

func (*GroupResult) Int64 added in v0.5.0

func (fb *GroupResult) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*GroupResult) Ints added in v0.5.0

func (fb *GroupResult) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*GroupResult) Ints64 added in v0.5.0

func (fb *GroupResult) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*GroupResult) JSON added in v0.5.0

func (fb *GroupResult) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*GroupResult) Msg added in v0.5.0

func (r *GroupResult) Msg(msg string) error

Msg logs at success level with the given message if all tasks succeeded, or at error level with the joined error string on failure. Returns the error.

func (*GroupResult) OnErrorLevel added in v0.5.0

func (r *GroupResult) OnErrorLevel(level Level) *GroupResult

OnErrorLevel sets the log level for the error case.

func (*GroupResult) OnErrorMessage added in v0.5.0

func (r *GroupResult) OnErrorMessage(msg string) *GroupResult

OnErrorMessage sets a custom message for the error case.

func (*GroupResult) OnSuccessLevel added in v0.5.0

func (r *GroupResult) OnSuccessLevel(level Level) *GroupResult

OnSuccessLevel sets the log level for the success case.

func (*GroupResult) OnSuccessMessage added in v0.5.0

func (r *GroupResult) OnSuccessMessage(msg string) *GroupResult

OnSuccessMessage sets the message for the success case.

func (*GroupResult) Parts added in v0.5.1

func (r *GroupResult) Parts(parts ...Part) *GroupResult

Parts overrides the log-line part order for the completion message.

func (*GroupResult) Percent added in v0.5.0

func (fb *GroupResult) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*GroupResult) Prefix added in v0.5.0

func (r *GroupResult) Prefix(prefix string) *GroupResult

Prefix sets a custom emoji prefix for the completion log message.

func (*GroupResult) Quantities added in v0.5.0

func (fb *GroupResult) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*GroupResult) Quantity added in v0.5.0

func (fb *GroupResult) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*GroupResult) RawJSON added in v0.5.0

func (fb *GroupResult) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*GroupResult) Send added in v0.5.0

func (r *GroupResult) Send() error

Send finalises the result, logging at the configured success or error level. The error is the errors.Join of all task errors (nil when all succeeded).

func (*GroupResult) Silent added in v0.5.0

func (r *GroupResult) Silent() error

Silent returns the joined error without logging anything.

func (*GroupResult) Str added in v0.5.0

func (fb *GroupResult) Str(key, val string) *T

Str adds a string field.

func (*GroupResult) Stringer added in v0.5.0

func (fb *GroupResult) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*GroupResult) Stringers added in v0.5.0

func (fb *GroupResult) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*GroupResult) Strs added in v0.5.0

func (fb *GroupResult) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*GroupResult) Time added in v0.5.0

func (fb *GroupResult) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*GroupResult) Times added in v0.5.0

func (fb *GroupResult) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*GroupResult) Uint added in v0.5.0

func (fb *GroupResult) Uint(key string, val uint) *T

Uint adds a uint field.

func (*GroupResult) Uint64 added in v0.5.0

func (fb *GroupResult) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*GroupResult) Uints added in v0.5.0

func (fb *GroupResult) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*GroupResult) Uints64 added in v0.5.0

func (fb *GroupResult) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*GroupResult) When added in v0.5.1

func (fb *GroupResult) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type Handler

type Handler interface {
	Log(Entry)
}

Handler processes log entries. Implement this interface to customise how log entries are formatted and output (e.g. JSON logging).

When a Handler is set on a Logger, the Logger handles level checking, field accumulation, timestamps, and mutex locking. The Handler only needs to format and write the entry.

type HandlerFunc

type HandlerFunc func(Entry)

HandlerFunc is an adapter to use ordinary functions as Handler values.

func (HandlerFunc) Log

func (f HandlerFunc) Log(e Entry)

Log calls f(e).

type JSONMode added in v0.4.4

type JSONMode int

JSONMode controls how JSON is rendered.

const (
	// JSONModeJSON renders standard JSON (default).
	JSONModeJSON JSONMode = iota
	// JSONModeHuman renders in HJSON style: keys and simple string values are
	// unquoted, making output more readable at a glance.
	JSONModeHuman
	// JSONModeFlat flattens nested object keys using dot notation and renders
	// scalar values without unnecessary quotes. Arrays are kept intact.
	// Example: {"user":{"name":"alice"},"tags":["a","b"]}
	//       →  {user.name:alice,tags:[a,b]}
	JSONModeFlat
)

type JSONSpacing added in v0.4.4

type JSONSpacing uint

JSONSpacing is a bitmask controlling where spaces are inserted in JSON output.

const (
	// JSONSpacingAfterColon inserts a space after each colon: {"key": "value"}.
	JSONSpacingAfterColon JSONSpacing = 1 << iota
	// JSONSpacingAfterComma inserts a space after each comma: {"a": 1, "b": 2}.
	JSONSpacingAfterComma
	// JSONSpacingBeforeObject inserts a space before a nested object value: {"key": {"n":1}}.
	JSONSpacingBeforeObject
	// JSONSpacingBeforeArray inserts a space before a nested array value: {"tags": ["a","b"]}.
	JSONSpacingBeforeArray
	// JSONSpacingAll enables all spacing options.
	JSONSpacingAll = JSONSpacingAfterColon | JSONSpacingAfterComma | JSONSpacingBeforeObject | JSONSpacingBeforeArray
)

type JSONStyles added in v0.4.4

type JSONStyles struct {
	// Mode controls rendering behaviour.
	// JSONModeJSON (default) preserves standard JSON quoting.
	// JSONModeHuman strips quotes from identifier-like keys and simple string values.
	// JSONModeFlat flattens nested object keys with dot notation; arrays are kept intact.
	Mode JSONMode
	// OmitCommas omits the comma between items. JSONSpacingAfterComma still
	// applies and can be used to keep a space separator: {"a":1 "b":2}.
	OmitCommas bool
	// Spacing controls where spaces are inserted. Zero (default) means no spaces.
	// Use JSONSpacingAll for {"key": "value", "n": 1} style output.
	Spacing JSONSpacing

	BoolFalse      Style // false
	BoolTrue       Style // true
	Key            Style // Object keys
	Null           Style // null
	Number         Style // Numeric values - base fallback for all number sub-styles
	NumberFloat    Style // Floating-point values; falls back to Number
	NumberInteger  Style // Integer values; falls back to Number
	NumberNegative Style // Negative numbers; falls back to Number
	NumberPositive Style // Positive numbers (with or without explicit sign); falls back to Number
	NumberZero     Style // Zero; falls back to NumberPositive, then Number
	String         Style // String values

	Brace       Style // { } (nested)
	BraceRoot   Style // { } (outermost object; falls back to Brace if nil)
	Bracket     Style // [ ] (nested)
	BracketRoot Style // [ ] (outermost array; falls back to Bracket if nil)
	Colon       Style // :
	Comma       Style // ,
}

JSONStyles configures per-token lipgloss styles for JSON syntax highlighting. nil fields render the corresponding token unstyled.

Use DefaultJSONStyles as a starting point for customization.

func DefaultJSONStyles added in v0.4.4

func DefaultJSONStyles() *JSONStyles

DefaultJSONStyles returns dracula-inspired lipgloss styles for JSON tokens. True and False mirror DefaultValueStyles (green/red) for consistency.

func (*JSONStyles) WithRenderer added in v0.5.2

func (s *JSONStyles) WithRenderer(r *lipgloss.Renderer) *JSONStyles

WithRenderer rebinds all token styles to the given renderer. It mutates and returns the receiver for fluent chaining.

func (*JSONStyles) WithSpacing added in v0.4.4

func (s *JSONStyles) WithSpacing(spacing JSONSpacing) *JSONStyles

WithSpacing returns the receiver with the given spacing flags applied. It modifies and returns the same pointer for fluent chaining:

styles.FieldJSON = clog.DefaultJSONStyles().WithSpacing(clog.JSONSpacingAll)

type Level

type Level int

Level represents a log level.

Level implements encoding.TextMarshaler and encoding.TextUnmarshaler, so it works directly with flag.TextVar and most flag libraries.

const (
	TraceLevel Level = -10
	DebugLevel Level = -5
	InfoLevel  Level = 0
	DryLevel   Level = 2 // clog-specific, between Info and Warn
	WarnLevel  Level = 5
	ErrorLevel Level = 10
	FatalLevel Level = 15
)

func GetLevel

func GetLevel() Level

GetLevel returns the current log level of the Default logger.

func Levels added in v0.5.8

func Levels() []Level

Levels returns all registered levels (built-in and custom) in ascending severity order.

func ParseLevel added in v0.4.17

func ParseLevel(s string) (Level, error)

ParseLevel maps a level name string to a Level value. It accepts the canonical names ("trace", "debug", "info", "dry", "warn", "error", "fatal") plus aliases ("warning" → Warn, "critical" → Fatal). Matching is case-insensitive.

func (Level) MarshalText added in v0.4.17

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Level) String

func (l Level) String() string

String returns the short label for the level (e.g. "INF", "ERR").

func (*Level) UnmarshalText added in v0.4.17

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type LevelConfig added in v0.5.8

type LevelConfig struct {
	Name   string // canonical name for ParseLevel/MarshalText (e.g., "success") [required]
	Label  string // short display label (e.g., "SCS") [default: uppercase Name, max 3 chars]
	Prefix string // emoji prefix (e.g., "✅") [default: ""]
	Style  Style  // lipgloss style for the level label [default: nil]
}

LevelConfig configures a custom log level for use with RegisterLevel.

type LevelMap

type LevelMap map[Level]string

LevelMap maps levels to strings (used for labels, prefixes, etc.).

func DefaultLabels

func DefaultLabels() LevelMap

DefaultLabels returns a copy of the default level labels.

func DefaultPrefixes

func DefaultPrefixes() LevelMap

DefaultPrefixes returns a copy of the default emoji prefixes for each level.

type LevelStyleMap added in v0.3.0

type LevelStyleMap = map[Level]Style

LevelStyleMap maps log levels to lipgloss styles.

func DefaultMessageStyles

func DefaultMessageStyles() LevelStyleMap

DefaultMessageStyles returns the default per-level message styles (unstyled).

type Logger

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

Logger is the main structured logger.

func Ctx added in v0.5.0

func Ctx(ctx context.Context) *Logger

Ctx retrieves the logger from ctx. Returns Default if ctx is nil or contains no logger.

func New

func New(output *Output) *Logger

New creates a new Logger that writes to the given Output.

func NewWriter added in v0.3.1

func NewWriter(w io.Writer) *Logger

NewWriter creates a new Logger that writes to w with ColorAuto.

func (*Logger) Bar added in v0.5.0

func (l *Logger) Bar(msg string, total int) *AnimationBuilder

Bar creates a new AnimationBuilder with a determinate progress bar animation. total is the maximum progress value. Use ProgressUpdate.SetProgress to update progress.

func (*Logger) Debug

func (l *Logger) Debug() *Event

Debug returns a new Event at debug level, or nil if debug is disabled.

func (*Logger) Divider added in v0.5.1

func (l *Logger) Divider() *DividerBuilder

Divider returns a new DividerBuilder for rendering a horizontal rule.

func (*Logger) Dry

func (l *Logger) Dry() *Event

Dry returns a new Event at dry level, or nil if dry is disabled.

func (*Logger) Error

func (l *Logger) Error() *Event

Error returns a new Event at error level, or nil if error is disabled.

func (*Logger) Fatal

func (l *Logger) Fatal() *Event

Fatal returns a new Event at fatal level.

func (*Logger) Group added in v0.5.0

func (l *Logger) Group(ctx context.Context) *Group

Group creates a new animation group.

func (*Logger) Info

func (l *Logger) Info() *Event

Info returns a new Event at info level, or nil if info is disabled.

func (*Logger) Level added in v0.4.17

func (l *Logger) Level() Level

Level returns the current minimum log level.

func (*Logger) Log added in v0.5.8

func (l *Logger) Log(level Level) *Event

Log returns a new Event at the given level. Use this for custom levels registered with RegisterLevel.

func (*Logger) Output added in v0.3.1

func (l *Logger) Output() *Output

Output returns the logger's Output.

func (*Logger) Pulse added in v0.4.17

func (l *Logger) Pulse(msg string, stops ...ColorStop) *AnimationBuilder

Pulse creates a new AnimationBuilder with an animated color pulse on the message text. All characters fade uniformly between colors in the gradient. With no arguments, the default pulse gradient is used. Custom gradient stops can be passed to override the default.

func (*Logger) SetAnimationInterval added in v0.5.0

func (l *Logger) SetAnimationInterval(d time.Duration)

SetAnimationInterval sets a minimum refresh interval for all animations (spinners, bars, pulse, shimmer). Any animation whose built-in tick rate is faster than d will be clamped to d. The default is 67ms (~15fps). Zero means use built-in rates unchanged.

func (*Logger) SetColorMode

func (l *Logger) SetColorMode(mode ColorMode)

SetColorMode sets the colour mode by recreating the logger's Output with the given mode.

func (*Logger) SetElapsedFormatFunc added in v0.4.15

func (l *Logger) SetElapsedFormatFunc(fn func(time.Duration) string)

SetElapsedFormatFunc sets a custom format function for Elapsed fields. When set to nil (the default), the built-in [formatElapsed] is used.

func (*Logger) SetElapsedMinimum added in v0.4.15

func (l *Logger) SetElapsedMinimum(d time.Duration)

SetElapsedMinimum sets the minimum duration for Elapsed fields to be displayed. Elapsed values below this threshold are hidden. Defaults to time.Second. Set to 0 to show all values.

func (*Logger) SetElapsedPrecision added in v0.4.15

func (l *Logger) SetElapsedPrecision(precision int)

SetElapsedPrecision sets the number of decimal places for Elapsed display. For example, 0 = "3s", 1 = "3.2s", 2 = "3.21s". Defaults to 0.

func (*Logger) SetElapsedRound added in v0.4.15

func (l *Logger) SetElapsedRound(d time.Duration)

SetElapsedRound sets the rounding granularity for Elapsed values. Defaults to time.Second. Set to 0 to disable rounding.

func (*Logger) SetExitFunc

func (l *Logger) SetExitFunc(fn func(int))

SetExitFunc sets the function called by Fatal-level events. Defaults to os.Exit. This can be used in tests to intercept fatal exits. If fn is nil, the default os.Exit is used.

func (*Logger) SetFieldSort added in v0.4.15

func (l *Logger) SetFieldSort(sort Sort)

SetFieldSort sets the sort order for fields in log output. Default SortNone preserves insertion order.

func (*Logger) SetFieldStyleLevel added in v0.1.2

func (l *Logger) SetFieldStyleLevel(level Level)

SetFieldStyleLevel sets the minimum log level at which field values are styled (coloured). Events below this level render fields as plain text. Defaults to InfoLevel.

func (*Logger) SetFieldTimeFormat added in v0.1.1

func (l *Logger) SetFieldTimeFormat(format string)

SetFieldTimeFormat sets the format string used for time.Time field values added via Event.Time and Context.Time. Defaults to time.RFC3339.

func (*Logger) SetHandler

func (l *Logger) SetHandler(h Handler)

SetHandler sets a custom log handler. When set, the handler receives all log entries instead of the built-in pretty formatter.

func (*Logger) SetIndent added in v0.5.4

func (l *Logger) SetIndent(levels int)

SetIndent sets the indent depth (number of indent levels) on the logger.

func (*Logger) SetIndentPrefixSeparator added in v0.5.4

func (l *Logger) SetIndentPrefixSeparator(sep string)

SetIndentPrefixSeparator sets the separator appended after an indent prefix. Defaults to " " (a single space).

func (*Logger) SetIndentPrefixes added in v0.5.4

func (l *Logger) SetIndentPrefixes(prefixes []string)

SetIndentPrefixes sets per-depth decorations placed after the space-based indent. A trailing space is appended automatically. Prefixes are cycled: at depth N the prefix is prefixes[(N-1) % len(prefixes)]. For example, with []string{"│"}, depth 2 produces " │ " (4 spaces + "│" + space). Pass nil to clear.

func (*Logger) SetIndentWidth added in v0.5.4

func (l *Logger) SetIndentWidth(width int)

SetIndentWidth sets the number of spaces per indent level. Defaults to 2.

func (*Logger) SetLabelWidth added in v0.4.17

func (l *Logger) SetLabelWidth(width int)

SetLabelWidth sets an explicit minimum width for level labels. If width is 0, the width is computed automatically from the current labels.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

SetLevel sets the minimum log level.

func (*Logger) SetLevelAlign

func (l *Logger) SetLevelAlign(align Align)

SetLevelAlign sets the alignment mode for level labels.

func (*Logger) SetLevelLabels added in v0.2.2

func (l *Logger) SetLevelLabels(labels LevelMap)

SetLevelLabels sets the level labels used in log output. Pass a map from Level to label string (e.g. {WarnLevel: "WARN"}). Missing levels fall back to the defaults.

func (*Logger) SetOmitEmpty

func (l *Logger) SetOmitEmpty(omit bool)

SetOmitEmpty enables or disables omitting fields with empty values. Empty means nil, empty strings, and nil or empty slices/maps.

func (*Logger) SetOmitZero

func (l *Logger) SetOmitZero(omit bool)

SetOmitZero enables or disables omitting fields with zero values. Zero means the zero value for any type (0, false, "", nil, etc.). This is a superset of Logger.SetOmitEmpty.

func (*Logger) SetOutput

func (l *Logger) SetOutput(out *Output)

SetOutput sets the output.

func (*Logger) SetOutputWriter added in v0.3.1

func (l *Logger) SetOutputWriter(w io.Writer)

SetOutputWriter sets the output writer with ColorAuto.

func (*Logger) SetParts

func (l *Logger) SetParts(parts ...Part)

SetParts sets the order in which parts appear in log output. Parts not included in the order are hidden. Parts can be reordered freely. Panics if no parts are provided.

func (*Logger) SetPercentFormatFunc added in v0.4.15

func (l *Logger) SetPercentFormatFunc(fn func(float64) string)

SetPercentFormatFunc sets a custom format function for Percent fields. When set to nil (the default), the built-in format is used.

func (*Logger) SetPercentPrecision added in v0.4.15

func (l *Logger) SetPercentPrecision(precision int)

SetPercentPrecision sets the number of decimal places for Percent display. For example, 0 = "75%", 1 = "75.0%". Defaults to 0.

func (*Logger) SetPercentReverseGradient added in v0.5.11

func (l *Logger) SetPercentReverseGradient(reverse bool)

SetPercentReverseGradient reverses the gradient direction for Percent fields. By default the gradient runs red (0%) → green (100%) - suitable for metrics where higher is better. Set reverse=true to flip it to green (0%) → red (100%) - suitable for metrics like CPU or disk usage where lower is better.

func (*Logger) SetPrefixes

func (l *Logger) SetPrefixes(prefixes LevelMap)

SetPrefixes sets the emoji prefixes used for each level. Pass a map from Level to prefix string. Missing levels fall back to the defaults.

func (*Logger) SetQuantityUnitsIgnoreCase added in v0.4.15

func (l *Logger) SetQuantityUnitsIgnoreCase(ignoreCase bool)

SetQuantityUnitsIgnoreCase sets whether quantity unit matching is case-insensitive. Defaults to true.

func (*Logger) SetQuoteChar

func (l *Logger) SetQuoteChar(char rune)

SetQuoteChar sets the character used to quote field values that contain spaces or special characters. The default (zero value) uses Go-style double-quoted strings via strconv.Quote. Setting a non-zero rune wraps values with that character on both sides (e.g. '\").

For asymmetric quotes (e.g. '[' and ']'), use Logger.SetQuoteChars.

func (*Logger) SetQuoteChars

func (l *Logger) SetQuoteChars(openChar, closeChar rune)

SetQuoteChars sets separate opening and closing characters for quoting field values (e.g. '[' and ']', or '«' and '»').

func (*Logger) SetQuoteMode

func (l *Logger) SetQuoteMode(mode QuoteMode)

SetQuoteMode sets the quoting behaviour for field values. QuoteAuto (default) quotes only when needed; QuoteAlways always quotes string/error/default-kind values; QuoteNever never quotes.

func (*Logger) SetReportTimestamp

func (l *Logger) SetReportTimestamp(report bool)

SetReportTimestamp enables or disables timestamp reporting.

func (*Logger) SetSeparatorText added in v0.4.15

func (l *Logger) SetSeparatorText(sep string)

SetSeparatorText sets the separator between field keys and values. Defaults to "=".

func (*Logger) SetStyles

func (l *Logger) SetStyles(styles *Styles)

SetStyles sets the display styles. If styles is nil, DefaultStyles is used.

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(format string)

SetTimeFormat sets the timestamp format string.

func (*Logger) SetTimeLocation

func (l *Logger) SetTimeLocation(loc *time.Location)

SetTimeLocation sets the timezone for timestamps. Defaults to time.Local. If loc is nil, time.Local is used.

func (*Logger) SetTreeChars added in v0.5.6

func (l *Logger) SetTreeChars(chars TreeChars)

SetTreeChars sets the box-drawing characters used for tree indentation. See DefaultTreeChars for the defaults.

func (*Logger) Shimmer added in v0.4.17

func (l *Logger) Shimmer(msg string, stops ...ColorStop) *AnimationBuilder

Shimmer creates a new AnimationBuilder with an animated gradient shimmer on the message text. Each character is coloured independently based on its position in the wave. With no arguments, the default shimmer gradient is used. Custom gradient stops can be passed to override the default.

func (*Logger) Spinner added in v0.4.17

func (l *Logger) Spinner(msg string) *AnimationBuilder

Spinner creates a new AnimationBuilder with a rotating spinner animation.

func (*Logger) Trace

func (l *Logger) Trace() *Event

Trace returns a new Event at trace level, or nil if trace is disabled.

func (*Logger) Warn

func (l *Logger) Warn() *Event

Warn returns a new Event at warn level, or nil if warn is disabled.

func (*Logger) With

func (l *Logger) With() *Context

With returns a Context for building a sub-logger with preset fields.

logger := clog.With().Str("component", "auth").Logger()
logger.Info().Str("user", "john").Msg("Authenticated")

func (*Logger) WithContext added in v0.5.0

func (l *Logger) WithContext(ctx context.Context) context.Context

WithContext returns a copy of ctx with the logger stored as a value.

type Output added in v0.3.1

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

Output bundles an io.Writer with its detected terminal capabilities (TTY, width, color profile). Each Logger holds an *Output so that capability detection is per-writer instead of per-process.

func NewOutput added in v0.3.1

func NewOutput(w io.Writer, mode ColorMode) *Output

NewOutput creates a new Output that wraps w. TTY detection is automatic for writers that expose an Fd() uintptr method (e.g. *os.File). The ColorMode determines how colors are handled:

func Stderr added in v0.3.1

func Stderr(mode ColorMode) *Output

Stderr returns a new Output for os.Stderr.

func Stdout added in v0.3.1

func Stdout(mode ColorMode) *Output

Stdout returns a new Output for os.Stdout.

func TestOutput added in v0.3.1

func TestOutput(w io.Writer) *Output

TestOutput returns a non-TTY Output with colors disabled, suitable for tests.

func (*Output) ColorsDisabled added in v0.3.1

func (o *Output) ColorsDisabled() bool

ColorsDisabled returns true if this output should suppress colors.

func (*Output) IsTTY added in v0.3.1

func (o *Output) IsTTY() bool

IsTTY returns true if the writer is connected to a terminal.

func (*Output) RefreshWidth added in v0.3.1

func (o *Output) RefreshWidth()

RefreshWidth clears the cached terminal width so that the next call to Output.Width re-queries the terminal.

func (*Output) Renderer added in v0.3.1

func (o *Output) Renderer() *lipgloss.Renderer

Renderer returns the lipgloss.Renderer configured for this output.

func (*Output) Width added in v0.3.1

func (o *Output) Width() int

Width returns the terminal width, or 0 for non-TTY writers. The value is lazily detected and cached; call Output.RefreshWidth to re-detect.

func (*Output) Writer added in v0.3.1

func (o *Output) Writer() io.Writer

Writer returns the underlying io.Writer.

type Part

type Part int

Part identifies a component of a formatted log line.

const (
	// PartTimestamp is the timestamp component.
	PartTimestamp Part = iota
	// PartLevel is the level label component.
	PartLevel
	// PartPrefix is the emoji prefix component.
	PartPrefix
	// PartMessage is the log message component.
	PartMessage
	// PartFields is the structured fields component.
	PartFields
)

func DefaultParts

func DefaultParts() []Part

DefaultParts returns the default ordering of log line parts: timestamp, level, prefix, message, fields.

type PercentOption added in v0.5.11

type PercentOption func(*percentValue)

PercentOption configures how a Event.Percent field is rendered.

func WithPercentReverseGradient added in v0.5.11

func WithPercentReverseGradient() PercentOption

WithPercentReverseGradient returns a PercentOption that flips the gradient direction for this field relative to the logger default. If the logger is using the normal gradient (red=0%, green=100%), the field renders inverted (green=0%, red=100%), and vice versa.

type ProgressTaskFunc added in v0.5.4

type ProgressTaskFunc func(context.Context, *ProgressUpdate) error

ProgressTaskFunc is a function executed by AnimationBuilder.Progress. The ProgressUpdate allows updating the animation's message and fields.

type ProgressUpdate

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

ProgressUpdate is a fluent builder for updating an animation's message and fields during a ProgressTaskFunc. Call ProgressUpdate.Msg and field methods to build the update, then ProgressUpdate.Send to apply it atomically.

func (*ProgressUpdate) AddTotal added in v0.5.3

func (p *ProgressUpdate) AddTotal(delta int) *ProgressUpdate

AddTotal atomically adds delta to the total progress value for a bar animation. The result is clamped to a minimum of 1. Use positive delta when discovering additional work; negative delta to shrink the total. No-op if this is not a bar animation.

func (*ProgressUpdate) Any

func (fb *ProgressUpdate) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*ProgressUpdate) Anys

func (fb *ProgressUpdate) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*ProgressUpdate) Base64 added in v0.4.8

func (fb *ProgressUpdate) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*ProgressUpdate) Bool

func (fb *ProgressUpdate) Bool(key string, val bool) *T

Bool adds a bool field.

func (*ProgressUpdate) Bools

func (fb *ProgressUpdate) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*ProgressUpdate) Bytes added in v0.4.7

func (fb *ProgressUpdate) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*ProgressUpdate) Duration added in v0.2.2

func (fb *ProgressUpdate) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*ProgressUpdate) Durations added in v0.2.2

func (fb *ProgressUpdate) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*ProgressUpdate) Err added in v0.4.1

func (fb *ProgressUpdate) Err(err error) *T

Err adds an error field with key "error". No-op if err is nil.

Unlike Event.Err, context errors are always stored as a field because context fields have no Send/Msg finalisation semantics.

func (*ProgressUpdate) Errs added in v0.4.10

func (fb *ProgressUpdate) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*ProgressUpdate) Float64

func (fb *ProgressUpdate) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*ProgressUpdate) Floats64

func (fb *ProgressUpdate) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*ProgressUpdate) Hex added in v0.4.8

func (fb *ProgressUpdate) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*ProgressUpdate) Int

func (fb *ProgressUpdate) Int(key string, val int) *T

Int adds an int field.

func (*ProgressUpdate) Int64 added in v0.4.1

func (fb *ProgressUpdate) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*ProgressUpdate) Ints

func (fb *ProgressUpdate) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*ProgressUpdate) Ints64 added in v0.4.4

func (fb *ProgressUpdate) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*ProgressUpdate) JSON added in v0.4.4

func (fb *ProgressUpdate) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*ProgressUpdate) Msg added in v0.4.12

func (p *ProgressUpdate) Msg(msg string) *ProgressUpdate

Msg sets the animation's displayed message.

func (*ProgressUpdate) Percent added in v0.3.0

func (fb *ProgressUpdate) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*ProgressUpdate) Quantities added in v0.2.2

func (fb *ProgressUpdate) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*ProgressUpdate) Quantity added in v0.2.2

func (fb *ProgressUpdate) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*ProgressUpdate) RawJSON added in v0.4.4

func (fb *ProgressUpdate) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*ProgressUpdate) Send

func (p *ProgressUpdate) Send()

Send applies the accumulated message and field changes to the animation atomically.

func (*ProgressUpdate) SetProgress added in v0.5.0

func (p *ProgressUpdate) SetProgress(current int) *ProgressUpdate

SetProgress sets the current progress value for a bar animation. Values are clamped to [0, total]. No-op if this is not a bar animation.

func (*ProgressUpdate) SetTotal added in v0.5.0

func (p *ProgressUpdate) SetTotal(total int) *ProgressUpdate

SetTotal updates the total progress value for a bar animation. No-op if this is not a bar animation.

func (*ProgressUpdate) Str

func (fb *ProgressUpdate) Str(key, val string) *T

Str adds a string field.

func (*ProgressUpdate) Stringer added in v0.4.1

func (fb *ProgressUpdate) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*ProgressUpdate) Stringers added in v0.4.1

func (fb *ProgressUpdate) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*ProgressUpdate) Strs

func (fb *ProgressUpdate) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*ProgressUpdate) Time added in v0.1.1

func (fb *ProgressUpdate) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*ProgressUpdate) Times added in v0.4.17

func (fb *ProgressUpdate) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*ProgressUpdate) Uint added in v0.4.1

func (fb *ProgressUpdate) Uint(key string, val uint) *T

Uint adds a uint field.

func (*ProgressUpdate) Uint64

func (fb *ProgressUpdate) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*ProgressUpdate) Uints added in v0.4.4

func (fb *ProgressUpdate) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*ProgressUpdate) Uints64

func (fb *ProgressUpdate) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*ProgressUpdate) When added in v0.5.1

func (fb *ProgressUpdate) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type QuoteMode

type QuoteMode int

QuoteMode controls how field values are quoted in log output.

const (
	// QuoteAuto quotes values only when they contain spaces, unprintable
	// characters, or embedded quotes. This is the default.
	QuoteAuto QuoteMode = iota
	// QuoteAlways quotes all string, error, and default-kind values.
	QuoteAlways
	// QuoteNever disables quoting entirely.
	QuoteNever
)

type SlogHandler added in v0.5.0

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

SlogHandler implements slog.Handler by routing records through a clog Logger.

func (*SlogHandler) Enabled added in v0.5.0

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

Enabled reports whether the handler handles records at the given level.

func (*SlogHandler) Handle added in v0.5.0

func (h *SlogHandler) Handle(_ context.Context, r slog.Record) error

Handle converts a slog.Record into a clog Event and logs it.

func (*SlogHandler) WithAttrs added in v0.5.0

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

WithAttrs returns a new SlogHandler with the given attrs preset.

func (*SlogHandler) WithGroup added in v0.5.0

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

WithGroup returns a new SlogHandler with the given group name appended.

type SlogOptions added in v0.5.0

type SlogOptions struct {
	// AddSource adds source file:line information to each log entry.
	AddSource bool
	// Level overrides the minimum log level. If nil, the logger's level is used.
	Level slog.Leveler
}

SlogOptions configures a SlogHandler.

type Sort added in v0.4.14

type Sort int

Sort controls how fields are sorted in output.

const (
	// SortNone preserves the insertion order of fields (default).
	SortNone Sort = iota
	// SortAscending sorts fields by key A→Z.
	SortAscending
	// SortDescending sorts fields by key Z→A.
	SortDescending
)

type Speed added in v0.5.0

type Speed = float64

Speed is the number of full animation cycles per second. Used by AnimationBuilder.Speed to control shimmer and pulse rate.

type SpinnerStyle added in v0.5.0

type SpinnerStyle struct {
	Frames    []string
	FPS       time.Duration
	Reverse   bool
	Boomerang bool
}

SpinnerStyle is a set of frames used in animating the spinner. Set Reverse to true to play the frames in reverse order. Set Boomerang to true to play the frames in a ping-pong loop so the animation smoothly reverses at each end instead of jumping from the last frame back to the first. For example, frames [a, b, c] play as [a, b, c, b, a, b, c, ...]. Boomerang and Reverse can be combined.

func DefaultSpinnerStyle added in v0.5.0

func DefaultSpinnerStyle() SpinnerStyle

DefaultSpinnerStyle returns the default SpinnerStyle. It uses SpinnerMoon in reverse.

type Style added in v0.4.4

type Style = *lipgloss.Style

Style is a convenience alias for *lipgloss.Style.

type StyleMap added in v0.3.0

type StyleMap = map[string]Style

StyleMap maps string keys to lipgloss styles (e.g. field key names or unit strings).

type Styles

type Styles struct {

	// Style for divider line characters (see [Logger.Divider]) [nil = plain text]
	DividerLine Style
	// Style for divider title text (see [DividerBuilder.Msg]) [nil = plain text]
	DividerTitle Style
	// Duration unit -> thresholds (evaluated high->low).
	DurationThresholds ThresholdMap
	// Duration unit -> style override (e.g. "s" -> yellow).
	DurationUnits StyleMap
	// Style for the numeric segments of duration values (e.g. "1" in "1m30s") [nil = plain text]
	FieldDurationNumber Style
	// Style for the unit segments of duration values (e.g. "m" in "1m30s") [nil = plain text]
	FieldDurationUnit Style
	// Style for the numeric segments of elapsed-time values [nil = falls back to FieldDurationNumber]
	FieldElapsedNumber Style
	// Style for the unit segments of elapsed-time values [nil = falls back to FieldDurationUnit]
	FieldElapsedUnit Style
	// Style for error field values [nil = plain text]
	FieldError Style
	// Per-token styles for JSON syntax highlighting.
	// nil disables JSON highlighting; use [DefaultJSONStyles] to enable.
	FieldJSON *JSONStyles
	// Style for int/float field values [nil = plain text]
	FieldNumber Style
	// Base style for Percent fields (foreground overridden by gradient). nil = gradient color only.
	FieldPercent Style
	// Style for the numeric part of quantity values (e.g. "5" in "5km") [nil = plain text]
	FieldQuantityNumber Style
	// Style for the unit part of quantity values (e.g. "km" in "5km") [nil = plain text]
	FieldQuantityUnit Style
	// Style for string field values [nil = plain text]
	FieldString Style
	// Style for time.Time field values [nil = plain text]
	FieldTime Style
	// Style for field key names without a per-key override.
	KeyDefault Style
	// Field key name -> value style (e.g. "path" -> blue).
	Keys StyleMap
	// Level label style (e.g. "INF", "ERR").
	Levels LevelStyleMap
	// Message text style per level.
	Messages LevelStyleMap
	// Prefix text style per level (e.g. make "warning" bold yellow).
	// nil entries render the prefix unstyled.
	Prefixes LevelStyleMap
	// Gradient stops for Percent fields (default: red → yellow → green).
	PercentGradient []ColorStop
	// Quantity unit -> thresholds (evaluated high->low).
	QuantityThresholds ThresholdMap
	// Unit string -> style override (e.g. "km" -> green).
	QuantityUnits StyleMap
	// Style for key/value separator.
	Separator Style
	// Style for the timestamp prefix.
	Timestamp Style
	// Values maps typed values to styles. Keys use Go equality.
	// Allows differentiating between e.g. `true` (bool) and "true" (string).
	Values ValueStyleMap
	// contains filtered or unexported fields
}

Styles holds lipgloss styles for the logger's pretty output. Pointer fields can be set to nil to disable that style entirely.

func DefaultStyles

func DefaultStyles() *Styles

DefaultStyles returns the default colour styles.

func (*Styles) WithRenderer added in v0.5.2

func (s *Styles) WithRenderer(r *lipgloss.Renderer) *Styles

WithRenderer rebinds all styles to the given renderer. This ensures styles render correctly when the logger's output differs from os.Stdout (e.g. logging to stderr while stdout is piped). It mutates and returns the receiver for fluent chaining.

type TaskFunc added in v0.5.4

type TaskFunc func(context.Context) error

TaskFunc is a function executed by AnimationBuilder.Wait.

type TaskResult added in v0.5.4

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

TaskResult holds the result of a group animation task. It mirrors WaitResult but reads its error from the task (set by Group.Wait).

func (*TaskResult) Any added in v0.5.4

func (fb *TaskResult) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*TaskResult) Anys added in v0.5.4

func (fb *TaskResult) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*TaskResult) Base64 added in v0.5.4

func (fb *TaskResult) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*TaskResult) Bool added in v0.5.4

func (fb *TaskResult) Bool(key string, val bool) *T

Bool adds a bool field.

func (*TaskResult) Bools added in v0.5.4

func (fb *TaskResult) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*TaskResult) Bytes added in v0.5.4

func (fb *TaskResult) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*TaskResult) Duration added in v0.5.4

func (fb *TaskResult) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*TaskResult) Durations added in v0.5.4

func (fb *TaskResult) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*TaskResult) Err added in v0.5.4

func (r *TaskResult) Err() error

Err returns the error, logging success or failure using the original message.

func (*TaskResult) Errs added in v0.5.4

func (fb *TaskResult) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*TaskResult) Float64 added in v0.5.4

func (fb *TaskResult) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*TaskResult) Floats64 added in v0.5.4

func (fb *TaskResult) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*TaskResult) Hex added in v0.5.4

func (fb *TaskResult) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*TaskResult) Int added in v0.5.4

func (fb *TaskResult) Int(key string, val int) *T

Int adds an int field.

func (*TaskResult) Int64 added in v0.5.4

func (fb *TaskResult) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*TaskResult) Ints added in v0.5.4

func (fb *TaskResult) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*TaskResult) Ints64 added in v0.5.4

func (fb *TaskResult) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*TaskResult) JSON added in v0.5.4

func (fb *TaskResult) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*TaskResult) Msg added in v0.5.4

func (r *TaskResult) Msg(msg string) error

Msg logs at success level with the given message on success, or at error level with the error string on failure. Returns the error.

func (*TaskResult) OnErrorLevel added in v0.5.4

func (r *TaskResult) OnErrorLevel(level Level) *TaskResult

OnErrorLevel sets the log level for the error case.

func (*TaskResult) OnErrorMessage added in v0.5.4

func (r *TaskResult) OnErrorMessage(msg string) *TaskResult

OnErrorMessage sets a custom message for the error case.

func (*TaskResult) OnSuccessLevel added in v0.5.4

func (r *TaskResult) OnSuccessLevel(level Level) *TaskResult

OnSuccessLevel sets the log level for the success case.

func (*TaskResult) OnSuccessMessage added in v0.5.4

func (r *TaskResult) OnSuccessMessage(msg string) *TaskResult

OnSuccessMessage sets the message for the success case.

func (*TaskResult) Parts added in v0.5.4

func (r *TaskResult) Parts(parts ...Part) *TaskResult

Parts overrides the log-line part order for the completion message.

func (*TaskResult) Percent added in v0.5.4

func (fb *TaskResult) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*TaskResult) Prefix added in v0.5.4

func (r *TaskResult) Prefix(prefix string) *TaskResult

Prefix sets a custom emoji prefix for the completion log message.

func (*TaskResult) Quantities added in v0.5.4

func (fb *TaskResult) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*TaskResult) Quantity added in v0.5.4

func (fb *TaskResult) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*TaskResult) RawJSON added in v0.5.4

func (fb *TaskResult) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*TaskResult) Send added in v0.5.4

func (r *TaskResult) Send() error

Send finalises the result, logging at the configured success or error level.

func (*TaskResult) Silent added in v0.5.4

func (r *TaskResult) Silent() error

Silent returns just the error without logging anything.

func (*TaskResult) Str added in v0.5.4

func (fb *TaskResult) Str(key, val string) *T

Str adds a string field.

func (*TaskResult) Stringer added in v0.5.4

func (fb *TaskResult) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*TaskResult) Stringers added in v0.5.4

func (fb *TaskResult) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*TaskResult) Strs added in v0.5.4

func (fb *TaskResult) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*TaskResult) Time added in v0.5.4

func (fb *TaskResult) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*TaskResult) Times added in v0.5.4

func (fb *TaskResult) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*TaskResult) Uint added in v0.5.4

func (fb *TaskResult) Uint(key string, val uint) *T

Uint adds a uint field.

func (*TaskResult) Uint64 added in v0.5.4

func (fb *TaskResult) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*TaskResult) Uints added in v0.5.4

func (fb *TaskResult) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*TaskResult) Uints64 added in v0.5.4

func (fb *TaskResult) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*TaskResult) When added in v0.5.4

func (fb *TaskResult) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type Threshold added in v0.3.0

type Threshold struct {
	Value float64        // Minimum numeric value (inclusive) to trigger this style.
	Style ThresholdStyle // Style overrides for number and unit segments.
}

Threshold defines a style override when a quantity's numeric value meets or exceeds the given threshold. Thresholds are evaluated in descending order - the first match wins.

type ThresholdMap added in v0.3.0

type ThresholdMap = map[string]Thresholds

ThresholdMap maps unit strings to their thresholds (evaluated high -> low).

type ThresholdStyle added in v0.3.1

type ThresholdStyle struct {
	Number Style // Override for the number segment (nil = keep default).
	Unit   Style // Override for the unit segment (nil = keep default).
}

ThresholdStyle holds optional style overrides for the number and unit segments of a quantity or duration value. nil fields keep the default style.

type Thresholds added in v0.3.0

type Thresholds = []Threshold

Thresholds is a list of Threshold entries, evaluated high -> low (first match wins).

type TreeChars added in v0.5.6

type TreeChars struct {
	First    string // connector for [TreeFirst]  (default "├── ")
	Middle   string // connector for [TreeMiddle] (default "├── ")
	Last     string // connector for [TreeLast]   (default "└── ")
	Continue string // ancestor line when parent is First/Middle (default "│   ")
	Blank    string // ancestor line when parent is Last         (default "    ")
}

TreeChars defines the box-drawing characters used by tree indentation. Override with Logger.SetTreeChars.

func DefaultTreeChars added in v0.5.6

func DefaultTreeChars() TreeChars

DefaultTreeChars returns the default box-drawing characters for tree indentation.

type TreePos added in v0.5.6

type TreePos int

TreePos identifies a node's position among its siblings in a tree.

const (
	// TreeFirst marks the first sibling. Renders the same as [TreeMiddle]
	// by default, but can be customised via [Logger.SetTreeChars].
	TreeFirst TreePos = iota
	// TreeMiddle marks a middle sibling (more siblings follow).
	TreeMiddle
	// TreeLast marks the last sibling (no more siblings follow).
	TreeLast
)

type ValueStyleMap added in v0.3.0

type ValueStyleMap = map[any]Style

ValueStyleMap maps typed values to lipgloss styles. Keys use Go equality (e.g. bool true != string "true").

func DefaultValueStyles

func DefaultValueStyles() ValueStyleMap

DefaultValueStyles returns sensible default styles for common value strings.

type WaitResult

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

WaitResult holds the result of an AnimationBuilder.Wait operation and allows chaining additional fields before finalising the log output.

func (*WaitResult) Any

func (fb *WaitResult) Any(key string, val any) *T

Any adds a field with an arbitrary value.

func (*WaitResult) Anys

func (fb *WaitResult) Anys(key string, vals []any) *T

Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.

func (*WaitResult) Base64 added in v0.4.8

func (fb *WaitResult) Base64(key string, val []byte) *T

Base64 adds a []byte field encoded as a base64 string.

func (*WaitResult) Bool

func (fb *WaitResult) Bool(key string, val bool) *T

Bool adds a bool field.

func (*WaitResult) Bools

func (fb *WaitResult) Bools(key string, vals []bool) *T

Bools adds a bool slice field.

func (*WaitResult) Bytes added in v0.4.7

func (fb *WaitResult) Bytes(key string, val []byte) *T

Bytes adds a []byte field. If val is valid JSON it is stored as [RawJSON] with syntax highlighting; otherwise it is stored as a plain string.

func (*WaitResult) Duration added in v0.2.2

func (fb *WaitResult) Duration(key string, val time.Duration) *T

Duration adds a time.Duration field.

func (*WaitResult) Durations added in v0.2.2

func (fb *WaitResult) Durations(key string, vals []time.Duration) *T

Durations adds a time.Duration slice field.

func (*WaitResult) Err

func (w *WaitResult) Err() error

Err returns the error, logging success at info level or failure at error level using the original animation message.

func (*WaitResult) Errs added in v0.4.10

func (fb *WaitResult) Errs(key string, vals []error) *T

Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").

func (*WaitResult) Float64

func (fb *WaitResult) Float64(key string, val float64) *T

Float64 adds a float64 field.

func (*WaitResult) Floats64

func (fb *WaitResult) Floats64(key string, vals []float64) *T

Floats64 adds a float64 slice field.

func (*WaitResult) Hex added in v0.4.8

func (fb *WaitResult) Hex(key string, val []byte) *T

Hex adds a []byte field encoded as a hex string.

func (*WaitResult) Int

func (fb *WaitResult) Int(key string, val int) *T

Int adds an int field.

func (*WaitResult) Int64 added in v0.4.1

func (fb *WaitResult) Int64(key string, val int64) *T

Int64 adds an int64 field.

func (*WaitResult) Ints

func (fb *WaitResult) Ints(key string, vals []int) *T

Ints adds an int slice field.

func (*WaitResult) Ints64 added in v0.4.4

func (fb *WaitResult) Ints64(key string, vals []int64) *T

Ints64 adds an int64 slice field.

func (*WaitResult) JSON added in v0.4.4

func (fb *WaitResult) JSON(key string, val any) *T

JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.

func (*WaitResult) Msg

func (w *WaitResult) Msg(msg string) error

Msg logs at info level with the given message on success, or at error level with the error string on failure. Returns the error.

func (*WaitResult) OnErrorLevel added in v0.2.0

func (w *WaitResult) OnErrorLevel(level Level) *WaitResult

OnErrorLevel sets the log level for the error case. Defaults to ErrorLevel.

func (*WaitResult) OnErrorMessage added in v0.2.0

func (w *WaitResult) OnErrorMessage(msg string) *WaitResult

OnErrorMessage sets a custom message for the error case. When set, the original error is added as an ErrorKey field alongside the custom message. Defaults to using the error string as the message with no extra field.

func (*WaitResult) OnSuccessLevel added in v0.2.0

func (w *WaitResult) OnSuccessLevel(level Level) *WaitResult

OnSuccessLevel sets the log level for the success case. Defaults to InfoLevel.

func (*WaitResult) OnSuccessMessage added in v0.2.0

func (w *WaitResult) OnSuccessMessage(msg string) *WaitResult

OnSuccessMessage sets the message for the success case. Defaults to the original animation message.

func (*WaitResult) Parts added in v0.5.1

func (w *WaitResult) Parts(parts ...Part) *WaitResult

Parts overrides the log-line part order for the completion message.

func (*WaitResult) Percent added in v0.3.0

func (fb *WaitResult) Percent(key string, val float64) *T

Percent adds a percentage field (0–100) with gradient color styling. Values are clamped to the 0–100 range. The color is interpolated from the [Styles.PercentGradient] stops (default: red → yellow → green).

func (*WaitResult) Prefix

func (w *WaitResult) Prefix(prefix string) *WaitResult

Prefix sets a custom emoji prefix for the completion log message.

func (*WaitResult) Quantities added in v0.2.2

func (fb *WaitResult) Quantities(key string, vals []string) *T

Quantities adds a quantity string slice field. Each element is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*WaitResult) Quantity added in v0.2.2

func (fb *WaitResult) Quantity(key, val string) *T

Quantity adds a quantity string field where numeric and unit segments are styled independently (e.g. "5m", "5.1km", "100MB"). The value is styled with [Styles.FieldQuantityNumber] and [Styles.FieldQuantityUnit].

func (*WaitResult) RawJSON added in v0.4.4

func (fb *WaitResult) RawJSON(key string, val []byte) *T

RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.

func (*WaitResult) Send added in v0.2.0

func (w *WaitResult) Send() error

Send finalises the result, logging at the configured success or error level. On failure, the error string is used as the message. If a custom error message was set via WaitResult.OnErrorMessage, the original error is included as an ErrorKey field. Returns the error from the task.

func (*WaitResult) Silent

func (w *WaitResult) Silent() error

Silent returns just the error without logging anything.

func (*WaitResult) Str

func (fb *WaitResult) Str(key, val string) *T

Str adds a string field.

func (*WaitResult) Stringer added in v0.4.4

func (fb *WaitResult) Stringer(key string, val fmt.Stringer) *T

Stringer adds a field by calling the value's String method. No-op if val is nil.

func (*WaitResult) Stringers added in v0.4.4

func (fb *WaitResult) Stringers(key string, vals []fmt.Stringer) *T

Stringers adds a field with a slice of fmt.Stringer values.

func (*WaitResult) Strs

func (fb *WaitResult) Strs(key string, vals []string) *T

Strs adds a string slice field.

func (*WaitResult) Time added in v0.1.1

func (fb *WaitResult) Time(key string, val time.Time) *T

Time adds a time.Time field.

func (*WaitResult) Times added in v0.4.17

func (fb *WaitResult) Times(key string, vals []time.Time) *T

Times adds a time.Time slice field.

func (*WaitResult) Uint added in v0.4.1

func (fb *WaitResult) Uint(key string, val uint) *T

Uint adds a uint field.

func (*WaitResult) Uint64

func (fb *WaitResult) Uint64(key string, val uint64) *T

Uint64 adds a uint64 field.

func (*WaitResult) Uints added in v0.4.4

func (fb *WaitResult) Uints(key string, vals []uint) *T

Uints adds a uint slice field.

func (*WaitResult) Uints64

func (fb *WaitResult) Uints64(key string, vals []uint64) *T

Uints64 adds a uint64 slice field.

func (*WaitResult) When added in v0.5.1

func (fb *WaitResult) When(condition bool, fn func(*T)) *T

When calls fn with the builder if condition is true. This is useful for conditionally adding fields without breaking the chain.

type WidgetOption added in v0.5.0

type WidgetOption func(*widget)

WidgetOption configures a bar widget constructor.

func WithDigits added in v0.5.0

func WithDigits(n int) WidgetOption

WithDigits configures the precision of formatted values.

  • WidgetBytes / WidgetIBytes: significant digits (default 3). 3 → "82.9 MB", "1 GB"; 2 → "83 MB", "5.5 GB"
  • WidgetPercent: decimal places (default 0). 0 → "42%"; 1 → "42.5%"

func WithStyle added in v0.5.9

func WithStyle(style Style) WidgetOption

WithStyle sets a lipgloss style applied to the widget's output string. Accepted by all built-in widgets. Empty outputs (e.g. WidgetETA when complete) are never styled.

func WithUnit added in v0.5.3

func WithUnit(unit string) WidgetOption

WithUnit sets a unit label for rate widgets. For example, WithUnit("ops") produces "150 ops/s" instead of "150/s".

Directories

Path Synopsis
banner command
bar command
custom-levels command
group command
indent command
json command
pulse command
shimmer command
spinner command
styles command
tree command

Jump to

Keyboard shortcuts

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