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
- Variables
- func ColorsDisabled() bool
- func Configure(cfg *Config)
- func Hyperlink(url, text string) string
- func IsTerminal() bool
- func IsVerbose() bool
- func PathLink(path string, line int) string
- func SetColorMode(mode ColorMode)
- func SetEnvPrefix(prefix string)
- func SetExitFunc(fn func(int))
- func SetFieldStyleLevel(level Level)
- func SetFieldTimeFormat(format string)
- func SetHandler(h Handler)
- func SetHyperlinkColumnFormat(format string)
- func SetHyperlinkDirFormat(format string)
- func SetHyperlinkFileFormat(format string)
- func SetHyperlinkLineFormat(format string)
- func SetHyperlinkPathFormat(format string)
- func SetHyperlinkPreset(name string) error
- func SetHyperlinksEnabled(enabled bool)
- func SetLevel(level Level)
- func SetLevelAlign(align LevelAlign)
- func SetLevelLabels(labels LevelMap)
- func SetOmitEmpty(omit bool)
- func SetOmitZero(omit bool)
- func SetOutput(out *Output)
- func SetOutputWriter(w io.Writer)
- func SetParts(order ...Part)
- func SetPrefixes(prefixes LevelMap)
- func SetQuoteChar(char rune)
- func SetQuoteChars(openChar, closeChar rune)
- func SetQuoteMode(mode QuoteMode)
- func SetReportTimestamp(report bool)
- func SetStyles(styles *Styles)
- func SetTimeFormat(format string)
- func SetTimeLocation(loc *time.Location)
- func SetVerbose(verbose bool)
- type AnimationBuilder
- func (fb *AnimationBuilder) Any(key string, val any) *T
- func (fb *AnimationBuilder) Anys(key string, vals []any) *T
- func (fb *AnimationBuilder) Base64(key string, val []byte) *T
- func (fb *AnimationBuilder) Bool(key string, val bool) *T
- func (fb *AnimationBuilder) Bools(key string, vals []bool) *T
- func (fb *AnimationBuilder) Bytes(key string, val []byte) *T
- func (b *AnimationBuilder) Column(key, path string, line, column int) *AnimationBuilder
- func (fb *AnimationBuilder) Duration(key string, val time.Duration) *T
- func (fb *AnimationBuilder) Durations(key string, vals []time.Duration) *T
- func (fb *AnimationBuilder) Err(err error) *T
- func (fb *AnimationBuilder) Float64(key string, val float64) *T
- func (fb *AnimationBuilder) Floats64(key string, vals []float64) *T
- func (fb *AnimationBuilder) Hex(key string, val []byte) *T
- func (fb *AnimationBuilder) Int(key string, val int) *T
- func (fb *AnimationBuilder) Int64(key string, val int64) *T
- func (fb *AnimationBuilder) Ints(key string, vals []int) *T
- func (fb *AnimationBuilder) Ints64(key string, vals []int64) *T
- func (fb *AnimationBuilder) JSON(key string, val any) *T
- func (b *AnimationBuilder) Line(key, path string, line int) *AnimationBuilder
- func (b *AnimationBuilder) Link(key, url, text string) *AnimationBuilder
- func (b *AnimationBuilder) Path(key, path string) *AnimationBuilder
- func (fb *AnimationBuilder) Percent(key string, val float64) *T
- func (b *AnimationBuilder) Prefix(prefix string) *AnimationBuilder
- func (b *AnimationBuilder) Progress(ctx context.Context, task ProgressTask) *WaitResult
- func (fb *AnimationBuilder) Quantities(key string, vals []string) *T
- func (fb *AnimationBuilder) Quantity(key, val string) *T
- func (fb *AnimationBuilder) RawJSON(key string, val []byte) *T
- func (b *AnimationBuilder) ShimmerDirection(d Direction) *AnimationBuilder
- func (fb *AnimationBuilder) Str(key, val string) *T
- func (fb *AnimationBuilder) Stringer(key string, val fmt.Stringer) *T
- func (fb *AnimationBuilder) Stringers(key string, vals []fmt.Stringer) *T
- func (fb *AnimationBuilder) Strs(key string, vals []string) *T
- func (fb *AnimationBuilder) Time(key string, val time.Time) *T
- func (b *AnimationBuilder) Type(s spinner.Spinner) *AnimationBuilder
- func (b *AnimationBuilder) URL(key, url string) *AnimationBuilder
- func (fb *AnimationBuilder) Uint(key string, val uint) *T
- func (fb *AnimationBuilder) Uint64(key string, val uint64) *T
- func (fb *AnimationBuilder) Uints(key string, vals []uint) *T
- func (fb *AnimationBuilder) Uints64(key string, vals []uint64) *T
- func (b *AnimationBuilder) Wait(ctx context.Context, task Task) *WaitResult
- type ColorMode
- type ColorStop
- type Config
- type Context
- func (fb *Context) Any(key string, val any) *T
- func (fb *Context) Anys(key string, vals []any) *T
- func (fb *Context) Base64(key string, val []byte) *T
- func (fb *Context) Bool(key string, val bool) *T
- func (fb *Context) Bools(key string, vals []bool) *T
- func (fb *Context) Bytes(key string, val []byte) *T
- func (c *Context) Column(key, path string, line, column int) *Context
- func (c *Context) Dict(key string, dict *Event) *Context
- func (fb *Context) Duration(key string, val time.Duration) *T
- func (fb *Context) Durations(key string, vals []time.Duration) *T
- func (fb *Context) Err(err error) *T
- func (fb *Context) Float64(key string, val float64) *T
- func (fb *Context) Floats64(key string, vals []float64) *T
- func (fb *Context) Hex(key string, val []byte) *T
- func (fb *Context) Int(key string, val int) *T
- func (fb *Context) Int64(key string, val int64) *T
- func (fb *Context) Ints(key string, vals []int) *T
- func (fb *Context) Ints64(key string, vals []int64) *T
- func (fb *Context) JSON(key string, val any) *T
- func (c *Context) Line(key, path string, line int) *Context
- func (c *Context) Link(key, url, text string) *Context
- func (c *Context) Logger() *Logger
- func (c *Context) Path(key, path string) *Context
- func (fb *Context) Percent(key string, val float64) *T
- func (c *Context) Prefix(prefix string) *Context
- func (fb *Context) Quantities(key string, vals []string) *T
- func (fb *Context) Quantity(key, val string) *T
- func (fb *Context) RawJSON(key string, val []byte) *T
- func (fb *Context) Str(key, val string) *T
- func (fb *Context) Stringer(key string, val fmt.Stringer) *T
- func (fb *Context) Stringers(key string, vals []fmt.Stringer) *T
- func (fb *Context) Strs(key string, vals []string) *T
- func (fb *Context) Time(key string, val time.Time) *T
- func (c *Context) URL(key, url string) *Context
- func (fb *Context) Uint(key string, val uint) *T
- func (fb *Context) Uint64(key string, val uint64) *T
- func (fb *Context) Uints(key string, vals []uint) *T
- func (fb *Context) Uints64(key string, vals []uint64) *T
- type Direction
- type Entry
- type Event
- func (e *Event) Any(key string, val any) *Event
- func (e *Event) Anys(key string, vals []any) *Event
- func (e *Event) Base64(key string, val []byte) *Event
- func (e *Event) Bool(key string, val bool) *Event
- func (e *Event) Bools(key string, vals []bool) *Event
- func (e *Event) Bytes(key string, val []byte) *Event
- func (e *Event) Column(key, path string, line, column int) *Event
- func (e *Event) Dict(key string, dict *Event) *Event
- func (e *Event) Duration(key string, val time.Duration) *Event
- func (e *Event) Durations(key string, vals []time.Duration) *Event
- func (e *Event) Err(err error) *Event
- func (e *Event) Float64(key string, val float64) *Event
- func (e *Event) Floats64(key string, vals []float64) *Event
- func (e *Event) Hex(key string, val []byte) *Event
- func (e *Event) Int(key string, val int) *Event
- func (e *Event) Int64(key string, val int64) *Event
- func (e *Event) Ints(key string, vals []int) *Event
- func (e *Event) Ints64(key string, vals []int64) *Event
- func (e *Event) JSON(key string, val any) *Event
- func (e *Event) Line(key, path string, line int) *Event
- func (e *Event) Link(key, url, text string) *Event
- func (e *Event) Msg(msg string)
- func (e *Event) Msgf(format string, args ...any)
- func (e *Event) Path(key, path string) *Event
- func (e *Event) Percent(key string, val float64) *Event
- func (e *Event) Prefix(prefix string) *Event
- func (e *Event) Quantities(key string, vals []string) *Event
- func (e *Event) Quantity(key, val string) *Event
- func (e *Event) RawJSON(key string, val []byte) *Event
- func (e *Event) Send()
- func (e *Event) Str(key, val string) *Event
- func (e *Event) Stringer(key string, val fmt.Stringer) *Event
- func (e *Event) Stringers(key string, vals []fmt.Stringer) *Event
- func (e *Event) Strs(key string, vals []string) *Event
- func (e *Event) Time(key string, val time.Time) *Event
- func (e *Event) Times(key string, vals []time.Time) *Event
- func (e *Event) URL(key, url string) *Event
- func (e *Event) Uint(key string, val uint) *Event
- func (e *Event) Uint64(key string, val uint64) *Event
- func (e *Event) Uints(key string, vals []uint) *Event
- func (e *Event) Uints64(key string, vals []uint64) *Event
- type Field
- type Handler
- type HandlerFunc
- type JSONMode
- type JSONSpacing
- type JSONStyles
- type Level
- type LevelAlign
- type LevelMap
- type LevelStyleMap
- type Logger
- func (l *Logger) Debug() *Event
- func (l *Logger) Dry() *Event
- func (l *Logger) Error() *Event
- func (l *Logger) Fatal() *Event
- func (l *Logger) Info() *Event
- func (l *Logger) Output() *Output
- func (l *Logger) SetExitFunc(fn func(int))
- func (l *Logger) SetFieldStyleLevel(level Level)
- func (l *Logger) SetFieldTimeFormat(format string)
- func (l *Logger) SetHandler(h Handler)
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) SetLevelAlign(align LevelAlign)
- func (l *Logger) SetLevelLabels(labels LevelMap)
- func (l *Logger) SetOmitEmpty(omit bool)
- func (l *Logger) SetOmitZero(omit bool)
- func (l *Logger) SetOutput(out *Output)
- func (l *Logger) SetOutputWriter(w io.Writer)
- func (l *Logger) SetParts(parts ...Part)
- func (l *Logger) SetPrefixes(prefixes LevelMap)
- func (l *Logger) SetQuoteChar(char rune)
- func (l *Logger) SetQuoteChars(openChar, closeChar rune)
- func (l *Logger) SetQuoteMode(mode QuoteMode)
- func (l *Logger) SetReportTimestamp(report bool)
- func (l *Logger) SetStyles(styles *Styles)
- func (l *Logger) SetTimeFormat(format string)
- func (l *Logger) SetTimeLocation(loc *time.Location)
- func (l *Logger) Trace() *Event
- func (l *Logger) Warn() *Event
- func (l *Logger) With() *Context
- type Output
- type Part
- type ProgressTask
- type ProgressUpdate
- func (fb *ProgressUpdate) Any(key string, val any) *T
- func (fb *ProgressUpdate) Anys(key string, vals []any) *T
- func (fb *ProgressUpdate) Base64(key string, val []byte) *T
- func (fb *ProgressUpdate) Bool(key string, val bool) *T
- func (fb *ProgressUpdate) Bools(key string, vals []bool) *T
- func (fb *ProgressUpdate) Bytes(key string, val []byte) *T
- func (fb *ProgressUpdate) Duration(key string, val time.Duration) *T
- func (fb *ProgressUpdate) Durations(key string, vals []time.Duration) *T
- func (fb *ProgressUpdate) Err(err error) *T
- func (fb *ProgressUpdate) Float64(key string, val float64) *T
- func (fb *ProgressUpdate) Floats64(key string, vals []float64) *T
- func (fb *ProgressUpdate) Hex(key string, val []byte) *T
- func (fb *ProgressUpdate) Int(key string, val int) *T
- func (fb *ProgressUpdate) Int64(key string, val int64) *T
- func (fb *ProgressUpdate) Ints(key string, vals []int) *T
- func (fb *ProgressUpdate) Ints64(key string, vals []int64) *T
- func (fb *ProgressUpdate) JSON(key string, val any) *T
- func (fb *ProgressUpdate) Percent(key string, val float64) *T
- func (fb *ProgressUpdate) Quantities(key string, vals []string) *T
- func (fb *ProgressUpdate) Quantity(key, val string) *T
- func (fb *ProgressUpdate) RawJSON(key string, val []byte) *T
- func (u *ProgressUpdate) Send()
- func (fb *ProgressUpdate) Str(key, val string) *T
- func (fb *ProgressUpdate) Stringer(key string, val fmt.Stringer) *T
- func (fb *ProgressUpdate) Stringers(key string, vals []fmt.Stringer) *T
- func (fb *ProgressUpdate) Strs(key string, vals []string) *T
- func (fb *ProgressUpdate) Time(key string, val time.Time) *T
- func (u *ProgressUpdate) Title(title string) *ProgressUpdate
- func (fb *ProgressUpdate) Uint(key string, val uint) *T
- func (fb *ProgressUpdate) Uint64(key string, val uint64) *T
- func (fb *ProgressUpdate) Uints(key string, vals []uint) *T
- func (fb *ProgressUpdate) Uints64(key string, vals []uint64) *T
- type QuoteMode
- type Style
- type StyleMap
- type Styles
- type Task
- type Threshold
- type ThresholdMap
- type ThresholdStyle
- type Thresholds
- type ValueStyleMap
- type WaitResult
- func (fb *WaitResult) Any(key string, val any) *T
- func (fb *WaitResult) Anys(key string, vals []any) *T
- func (fb *WaitResult) Base64(key string, val []byte) *T
- func (fb *WaitResult) Bool(key string, val bool) *T
- func (fb *WaitResult) Bools(key string, vals []bool) *T
- func (fb *WaitResult) Bytes(key string, val []byte) *T
- func (fb *WaitResult) Duration(key string, val time.Duration) *T
- func (fb *WaitResult) Durations(key string, vals []time.Duration) *T
- func (w *WaitResult) Err() error
- func (fb *WaitResult) Float64(key string, val float64) *T
- func (fb *WaitResult) Floats64(key string, vals []float64) *T
- func (fb *WaitResult) Hex(key string, val []byte) *T
- func (fb *WaitResult) Int(key string, val int) *T
- func (fb *WaitResult) Int64(key string, val int64) *T
- func (fb *WaitResult) Ints(key string, vals []int) *T
- func (fb *WaitResult) Ints64(key string, vals []int64) *T
- func (fb *WaitResult) JSON(key string, val any) *T
- func (w *WaitResult) Msg(msg string) error
- func (w *WaitResult) OnErrorLevel(level Level) *WaitResult
- func (w *WaitResult) OnErrorMessage(msg string) *WaitResult
- func (w *WaitResult) OnSuccessLevel(level Level) *WaitResult
- func (w *WaitResult) OnSuccessMessage(msg string) *WaitResult
- func (fb *WaitResult) Percent(key string, val float64) *T
- func (w *WaitResult) Prefix(prefix string) *WaitResult
- func (fb *WaitResult) Quantities(key string, vals []string) *T
- func (fb *WaitResult) Quantity(key, val string) *T
- func (fb *WaitResult) RawJSON(key string, val []byte) *T
- func (w *WaitResult) Send() error
- func (w *WaitResult) Silent() error
- func (fb *WaitResult) Str(key, val string) *T
- func (fb *WaitResult) Stringer(key string, val fmt.Stringer) *T
- func (fb *WaitResult) Stringers(key string, vals []fmt.Stringer) *T
- func (fb *WaitResult) Strs(key string, vals []string) *T
- func (fb *WaitResult) Time(key string, val time.Time) *T
- func (fb *WaitResult) Uint(key string, val uint) *T
- func (fb *WaitResult) Uint64(key string, val uint64) *T
- func (fb *WaitResult) Uints(key string, vals []uint) *T
- func (fb *WaitResult) Uints64(key string, vals []uint64) *T
Constants ¶
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" )
const DefaultEnvPrefix = "CLOG"
DefaultEnvPrefix is the default environment variable prefix.
const ErrorKey = "error"
ErrorKey is the default field key used by Event.Err and Context.Err.
const Nil = "<nil>"
Nil is the string representation used for nil values (e.g. in DefaultValueStyles).
Variables ¶
var Default = New(Stdout(ColorAuto))
Default is the default logger instance.
var DefaultSpinner = spinner.Spinner{ Frames: []string{"🌔", "🌓", "🌒", "🌑", "🌘", "🌗", "🌖", "🌕"}, FPS: spinner.Moon.FPS, }
DefaultSpinner is the default spinner animation.
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 ¶
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 PathLink ¶
PathLink creates a clickable terminal hyperlink for a file path. The line parameter is optional — pass 0 to omit line numbers.
func SetColorMode ¶
func SetColorMode(mode ColorMode)
SetColorMode sets the colour mode on the Default logger by recreating its Output with the given mode.
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 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 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
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 SetLevel ¶
func SetLevel(level Level)
SetLevel sets the minimum log level on the Default logger.
func SetLevelAlign ¶
func SetLevelAlign(align LevelAlign)
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 SetOutputWriter ¶ added in v0.3.1
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 SetPrefixes ¶
func SetPrefixes(prefixes LevelMap)
SetPrefixes sets the level prefixes 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 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 ¶
SetTimeLocation sets the timestamp timezone 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.
Types ¶
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, or Shimmer.
func Pulse ¶ added in v0.4.2
func Pulse(title string, stops ...ColorStop) *AnimationBuilder
Pulse creates a new AnimationBuilder with an animated color pulse on the title 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(title string, stops ...ColorStop) *AnimationBuilder
Shimmer creates a new AnimationBuilder with an animated gradient shimmer on the title 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(title string) *AnimationBuilder
Spinner creates a new AnimationBuilder with a rotating spinner animation.
func (*AnimationBuilder) Anys ¶ added in v0.4.2
Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.
func (*AnimationBuilder) Base64 ¶ added in v0.4.8
Base64 adds a []byte field encoded as a base64 string.
func (*AnimationBuilder) Bytes ¶ added in v0.4.7
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 Default logger's Output setting.
func (*AnimationBuilder) Duration ¶ added in v0.4.2
Duration adds a time.Duration field.
func (*AnimationBuilder) Durations ¶ added in v0.4.2
Durations adds a time.Duration slice field.
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) JSON ¶ added in v0.4.4
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 Default logger's Output setting.
func (*AnimationBuilder) Link ¶ added in v0.4.2
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 Default logger's Output setting.
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 Default logger's Output setting.
func (*AnimationBuilder) Percent ¶ added in v0.4.2
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 title 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 ProgressTask, ) *WaitResult
Progress executes the task with the animation whose title 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
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
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) 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
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
Stringers adds a field with a slice of fmt.Stringer values.
func (*AnimationBuilder) Type ¶ added in v0.4.2
func (b *AnimationBuilder) Type(s spinner.Spinner) *AnimationBuilder
Type sets the spinner animation type. Only meaningful when the builder was created with Spinner.
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 Default logger's Output setting.
func (*AnimationBuilder) Wait ¶ added in v0.4.2
func (b *AnimationBuilder) Wait(ctx context.Context, task Task) *WaitResult
Wait executes the task with the animation and returns a WaitResult for chaining. The animation displays as: <level> <icon> <title> <fields>.
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.
func (ColorMode) MarshalText ¶ added in v0.3.0
MarshalText implements encoding.TextMarshaler.
func (*ColorMode) UnmarshalText ¶ added in v0.3.0
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 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 {
// Verbose enables debug level logging and timestamps.
Verbose bool
// Output is the output to use (defaults to [Stdout]([ColorAuto])).
Output *Output
// Styles allows customising the visual styles.
Styles *Styles
}
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) Anys ¶
Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.
func (*Context) Bytes ¶ added in v0.4.7
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 ¶
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) Dict ¶
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
Duration adds a time.Duration field.
func (*Context) Durations ¶ added in v0.2.2
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) JSON ¶ added in v0.4.4
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 ¶
Line adds a file path field with a line number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.
func (*Context) Link ¶
Link adds a field as a clickable terminal hyperlink with custom URL and display text. Respects the logger's ColorMode setting.
func (*Context) 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 ¶
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
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) Quantities ¶ added in v0.2.2
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
RawJSON adds a field with pre-serialized JSON bytes, emitted verbatim without quoting or escaping. The bytes must be valid JSON.
func (*Context) Stringer ¶
Stringer adds a field by calling the value's String method. No-op if val is nil.
func (*Context) Stringers ¶
Stringers adds a field with a slice of fmt.Stringer values.
func (*Context) URL ¶ added in v0.2.1
URL adds a field as a clickable terminal hyperlink where the URL is also the display text. Respects the logger's ColorMode setting.
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 )
type Entry ¶
type Entry struct {
Fields []Field
Level Level
Message string
Prefix string
Time time.Time // Zero value if timestamps are disabled.
}
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 Dict ¶
func Dict() *Event
Dict returns a new detached Event for use as a nested dictionary field.
func (*Event) Anys ¶
Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.
func (*Event) Bytes ¶ added in v0.4.7
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 ¶
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 ¶
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
Duration adds a time.Duration field.
func (*Event) Durations ¶ added in v0.2.2
Durations adds a time.Duration slice field.
func (*Event) Err ¶
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) JSON ¶ added in v0.4.4
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 ¶
Line adds a file path field with a line number as a clickable terminal hyperlink. Respects the logger's ColorMode setting.
func (*Event) Link ¶
Link adds a field as a clickable terminal hyperlink with custom URL and display text. Respects the logger's ColorMode setting.
func (*Event) Msg ¶
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) Path ¶
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
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 (*Event) Quantities ¶ added in v0.2.2
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
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
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) Stringer ¶
Stringer adds a field by calling the value's String method. No-op if val is nil.
func (*Event) Stringers ¶
Stringers adds a field with a slice of fmt.Stringer values.
func (*Event) URL ¶ added in v0.2.1
URL adds a field as a clickable terminal hyperlink where the URL is also the display text. Respects the logger's ColorMode setting.
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.
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
// Spacing controls where spaces are inserted. Zero (default) means no spaces.
// Use JSONSpacingAll for {"key": "value", "n": 1} style output.
Spacing JSONSpacing
// OmitCommas omits the comma between items. JSONSpacingAfterComma still
// applies and can be used to keep a space separator: {"a":1 "b":2}.
OmitCommas bool
Key Style // Object keys
String Style // String values
Number Style // Numeric values — base fallback for all number sub-styles
NumberPositive Style // Positive numbers (with or without explicit sign); falls back to Number
NumberNegative Style // Negative numbers; falls back to Number
NumberZero Style // Zero; falls back to NumberPositive, then Number
NumberFloat Style // Floating-point values; falls back to Number
NumberInteger Style // Integer values; falls back to Number
True Style // true
False Style // false
Null Style // null
Brace Style // { } (nested)
RootBrace Style // { } (outermost object; falls back to Brace if nil)
Bracket Style // [ ] (nested)
RootBracket 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) 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 LevelAlign ¶
type LevelAlign int
LevelAlign controls how level labels are aligned when they have different widths.
const ( // AlignNone disables alignment padding. AlignNone LevelAlign = iota // AlignLeft left-aligns labels (pads with trailing spaces). AlignLeft // AlignRight right-aligns labels (pads with leading spaces). This is the default. AlignRight // AlignCenter center-aligns labels (pads with leading and trailing spaces). AlignCenter )
type LevelMap ¶
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
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 (*Logger) SetExitFunc ¶
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) SetFieldStyleLevel ¶ added in v0.1.2
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
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 ¶
SetHandler sets a custom log handler. When set, the handler receives all log entries instead of the built-in pretty formatter.
func (*Logger) SetLevelAlign ¶
func (l *Logger) SetLevelAlign(align LevelAlign)
SetLevelAlign sets the alignment mode for level labels.
func (*Logger) SetLevelLabels ¶ added in v0.2.2
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 ¶
SetOmitEmpty enables or disables omitting fields with empty values. Empty means nil, empty strings, and nil or empty slices/maps.
func (*Logger) SetOmitZero ¶
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) SetOutputWriter ¶ added in v0.3.1
SetOutputWriter sets the output writer with ColorAuto.
func (*Logger) SetParts ¶
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) SetPrefixes ¶
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) SetQuoteChar ¶
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 ¶
SetQuoteChars sets separate opening and closing characters for quoting field values (e.g. '[' and ']', or '«' and '»').
func (*Logger) SetQuoteMode ¶
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 ¶
SetReportTimestamp enables or disables timestamp reporting.
func (*Logger) SetStyles ¶
SetStyles sets the display styles. If styles is nil, DefaultStyles is used.
func (*Logger) SetTimeFormat ¶
SetTimeFormat sets the timestamp format string.
func (*Logger) SetTimeLocation ¶
SetTimeLocation sets the timezone for timestamps. Defaults to time.Local. If loc is nil, time.Local is used.
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
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:
- ColorAuto respects TTY detection and NO_COLOR.
- ColorAlways forces colors even on non-TTY writers.
- ColorNever disables all colors.
func TestOutput ¶ added in v0.3.1
TestOutput returns a non-TTY Output with colors disabled, suitable for tests.
func (*Output) ColorsDisabled ¶ added in v0.3.1
ColorsDisabled returns true if this output should suppress colors.
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
Renderer returns the lipgloss.Renderer configured for this output.
func (*Output) Width ¶ added in v0.3.1
Width returns the terminal width, or 0 for non-TTY writers. The value is lazily detected and cached; call Output.RefreshWidth to re-detect.
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 ProgressTask ¶
type ProgressTask func(context.Context, *ProgressUpdate) error
ProgressTask is a function executed by AnimationBuilder.Progress. The ProgressUpdate allows updating the animation's title and fields.
type ProgressUpdate ¶
type ProgressUpdate struct {
// contains filtered or unexported fields
}
ProgressUpdate is a fluent builder for updating an animation's title and fields during a ProgressTask. Call ProgressUpdate.Title and field methods to build the update, then ProgressUpdate.Send to apply it atomically.
func (*ProgressUpdate) Anys ¶
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
Base64 adds a []byte field encoded as a base64 string.
func (*ProgressUpdate) Bytes ¶ added in v0.4.7
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
Duration adds a time.Duration field.
func (*ProgressUpdate) Durations ¶ added in v0.2.2
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) JSON ¶ added in v0.4.4
JSON marshals val to JSON and adds it as a highlighted field. On marshal error the field value is the error string.
func (*ProgressUpdate) Percent ¶ added in v0.3.0
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
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
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 (u *ProgressUpdate) Send()
Send applies the accumulated title and field changes to the animation atomically.
func (*ProgressUpdate) Str ¶
func (fb *ProgressUpdate) Str(key, val string) *T
Str adds a string field.
func (*ProgressUpdate) Stringer ¶ added in v0.4.1
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
Stringers adds a field with a slice of fmt.Stringer values.
func (*ProgressUpdate) Title ¶
func (u *ProgressUpdate) Title(title string) *ProgressUpdate
Title sets the animation's displayed title.
type StyleMap ¶ added in v0.3.0
StyleMap maps string keys to lipgloss styles (e.g. field key names or unit strings).
type Styles ¶
type Styles struct {
// 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 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
// Gradient stops for Percent fields (default: red → yellow → green).
PercentGradient []ColorStop
// Decimal places for Percent display (default 0 = "75%", 1 -> "75.0%", etc).
PercentPrecision int
// Quantity unit -> thresholds (evaluated high->low).
QuantityThresholds ThresholdMap
// Unit string -> style override (e.g. "km" -> green).
QuantityUnits StyleMap
// Case-insensitive quantity unit matching (default true).
QuantityUnitsIgnoreCase bool
// Style for key/value [SeparatorText].
Separator Style
// Separator between key and value (default "=").
SeparatorText string
// Style for the timestamp prefix.
Timestamp Style
// Values maps typed values to styles. Keys use Go equality
// Allows diffentiating between e.g. `true` (bool) and "true" (string)
Values ValueStyleMap
}
Styles holds lipgloss styles for the logger's pretty output. Pointer fields can be set to nil to disable that style entirely.
type Task ¶
Task is a function executed by AnimationBuilder.Wait.
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 ValueStyleMap ¶ added in v0.3.0
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) Anys ¶
Anys adds a slice of arbitrary values. Individual elements are highlighted using reflection to determine their type.
func (*WaitResult) Bytes ¶ added in v0.4.7
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
Duration adds a time.Duration field.
func (*WaitResult) Durations ¶ added in v0.2.2
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 title.
func (*WaitResult) JSON ¶ added in v0.4.4
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 original animation title 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. Defaults to the error string.
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 title.
func (*WaitResult) Percent ¶ added in v0.3.0
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
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
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. Returns the error from the task.
func (*WaitResult) Silent ¶
func (w *WaitResult) Silent() error
Silent returns just the error without logging anything.
func (*WaitResult) Stringer ¶ added in v0.4.4
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
Stringers adds a field with a slice of fmt.Stringer values.