Documentation
¶
Overview ¶
Package clog provides structured CLI logging with terminal-aware colors, 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 AddHook(point HookPoint, fn func())
- func Bar(msg string, total int, opts ...bar.Option) *fx.Builder
- func ClearAllHooks()
- func ClearHooks(point HookPoint)
- func ColorsDisabled() bool
- func Configure(cfg *Config)
- func DefaultStyles() *style.Config
- func Group(ctx context.Context, opts ...fx.GroupOption) *fx.Group
- func Hyperlink(url, text string) string
- func IsTerminal() bool
- func IsVerbose() bool
- func PathLink(path string, line int) string
- func Pulse(msg string, opts ...pulse.Option) *fx.Builder
- func RegisterLevel(lvl Level, cfg LevelConfig)
- func SetAnimationInterval(d time.Duration)
- func SetColorMode(mode ColorMode)
- func SetEnvPrefix(prefix string)
- func SetExitCode(code int)
- func SetExitFunc(fn func(int))
- func SetFieldFormats(f FieldFormats)
- func SetFieldSort(sort Sort)
- func SetFieldStyleLevel(level Level)
- func SetFieldTimeFormat(format string)
- func SetHandler(h Handler)
- func SetIndent(levels int)
- func SetIndentPrefixSeparator(sep string)
- func SetIndentPrefixes(prefixes []string)
- func SetIndentWidth(width int)
- func SetJSONIndent(indent string)
- func SetJSONPrintMode(mode JSONPrintMode)
- func SetLabelWidth(width int)
- func SetLabels(labels LabelMap)
- func SetLevel(level Level)
- func SetLevelAlign(align Align)
- func SetNonTTYLevel(level Level)
- func SetOmitEmpty(omit bool)
- func SetOmitZero(omit bool)
- func SetOutput(out *Output)
- func SetOutputWriter(w io.Writer)
- func SetParts(order ...Part)
- func SetPrintIndent(indent string)
- func SetQuote(mode Quote)
- func SetQuoteChars(openChar, closeChar rune)
- func SetReportTimestamp(report bool)
- func SetSeparatorText(sep string)
- func SetSliceBrackets(openChar, closeChar rune)
- func SetSliceSeparator(sep string)
- func SetSmartQuoteChars(pairs ...QuotePair)
- func SetSmartQuotes(enabled bool)
- func SetSpinnerDefaults(opts ...spinner.Option)
- func SetStyles(styles *style.Config)
- func SetSymbols(symbols LabelMap)
- func SetTheme(p *theme.Pair)
- func SetTimeFormat(format string)
- func SetTimeLocation(loc *time.Location)
- func SetTreeChars(chars TreeChars)
- func SetVerbose(verbose bool)
- func SetWrap(wrap Wrap)
- func SetYAMLIndent(indent string)
- func SetYAMLIndentSequence(indent bool)
- func Shimmer(msg string, opts ...shimmer.Option) *fx.Builder
- func Spinner(msg string, opts ...spinner.Option) *fx.Builder
- func WithContext(ctx context.Context) context.Context
- type Align
- type ColorMode
- type Config
- type Context
- func (c *Context) Column(key, path string, line, column int) *Context
- func (c *Context) Dedent() *Context
- func (c *Context) Depth(n int) *Context
- func (c *Context) Dict(key string, dict *Event) *Context
- func (c *Context) Indent() *Context
- func (c *Context) Line(key, path string, line int) *Context
- func (c *Context) Link(key, url, text string) *Context
- func (c *Context) Links(key string, links []Link) *Context
- func (c *Context) Logger() *Logger
- func (c *Context) Path(key, path string) *Context
- func (c *Context) Symbol(symbol string) *Context
- func (c *Context) Tree(pos TreePos) *Context
- func (c *Context) URL(key, url string) *Context
- func (c *Context) URLs(key string, urls []string) *Context
- type DividerBuilder
- type Entry
- type Event
- func (e *Event) AnErr(key string, err error) *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) Disabled() bool
- func (e *Event) Discard() *Event
- func (e *Event) Duration(key string, val time.Duration) *Event
- func (e *Event) Durations(key string, vals []time.Duration) *Event
- func (e *Event) Elapsed(key string) *Event
- func (e *Event) Enabled() bool
- func (e *Event) Err(err error) *Event
- func (e *Event) Errs(key string, vals []error) *Event
- func (e *Event) ExitCode(code int) *Event
- func (e *Event) Float32(key string, val float32) *Event
- func (e *Event) Float64(key string, val float64) *Event
- func (e *Event) Floats32(key string, vals []float32) *Event
- func (e *Event) Floats64(key string, vals []float64) *Event
- func (e *Event) Fraction(key string, current, total int, opts ...fraction.Option) *Event
- func (e *Event) Func(fn func(*Event)) *Event
- func (e *Event) Hex(key string, val []byte) *Event
- func (e *Event) Int(key string, val int) *Event
- func (e *Event) Int8(key string, val int8) *Event
- func (e *Event) Int16(key string, val int16) *Event
- func (e *Event) Int32(key string, val int32) *Event
- func (e *Event) Int64(key string, val int64) *Event
- func (e *Event) Ints(key string, vals []int) *Event
- func (e *Event) Ints8(key string, vals []int8) *Event
- func (e *Event) Ints16(key string, vals []int16) *Event
- func (e *Event) Ints32(key string, vals []int32) *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) Links(key string, links []Link) *Event
- func (e *Event) Msg(msg string)
- func (e *Event) MsgFunc(createMsg func() string)
- func (e *Event) Msgf(format string, args ...any)
- func (e *Event) Parts(parts ...Part) *Event
- func (e *Event) Path(key, path string) *Event
- func (e *Event) Percent(key string, val float64, opts ...percent.Option) *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) Symbol(symbol string) *Event
- func (e *Event) Time(key string, val time.Time) *Event
- func (e *Event) TimeDiff(key string, t, start time.Time) *Event
- func (e *Event) Times(key string, vals []time.Time) *Event
- func (e *Event) URL(key, url string) *Event
- func (e *Event) URLs(key string, urls []string) *Event
- func (e *Event) Uint(key string, val uint) *Event
- func (e *Event) Uint8(key string, val uint8) *Event
- func (e *Event) Uint16(key string, val uint16) *Event
- func (e *Event) Uint32(key string, val uint32) *Event
- func (e *Event) Uint64(key string, val uint64) *Event
- func (e *Event) Uints(key string, vals []uint) *Event
- func (e *Event) Uints8(key string, vals []uint8) *Event
- func (e *Event) Uints16(key string, vals []uint16) *Event
- func (e *Event) Uints32(key string, vals []uint32) *Event
- func (e *Event) Uints64(key string, vals []uint64) *Event
- func (e *Event) When(condition bool, fn func(*Event)) *Event
- type Field
- type FieldAlignment
- type FieldFormats
- type GroupStatusFunc
- type Handler
- type HandlerFunc
- type HookPoint
- type JSONPrintMode
- type LabelMap
- type Level
- type LevelConfig
- type Link
- type Logger
- func (l *Logger) AddHook(point HookPoint, fn func())
- func (l *Logger) Bar(msg string, total int, opts ...bar.Option) *fx.Builder
- func (l *Logger) ClearAllHooks()
- func (l *Logger) ClearHooks(point HookPoint)
- func (l *Logger) Debug() *Event
- func (l *Logger) Dict() *Event
- func (l *Logger) Divider() *DividerBuilder
- func (l *Logger) Dry() *Event
- func (l *Logger) Error() *Event
- func (l *Logger) Fatal() *Event
- func (l *Logger) FieldFormats() FieldFormats
- func (l *Logger) Group(ctx context.Context, opts ...fx.GroupOption) *fx.Group
- func (l *Logger) Hint() *Event
- func (l *Logger) Info() *Event
- func (l *Logger) Level() Level
- func (l *Logger) LevelEnabled(level Level) bool
- func (l *Logger) Log(level Level) *Event
- func (l *Logger) LogFields(level Level, ts time.Time, msg string, fields []Field)
- func (l *Logger) Output() *Output
- func (l *Logger) Print() *Printer
- func (l *Logger) Pulse(msg string, opts ...pulse.Option) *fx.Builder
- func (l *Logger) SetAnimationInterval(d time.Duration)
- func (l *Logger) SetColorMode(mode ColorMode)
- func (l *Logger) SetExitCode(code int)
- func (l *Logger) SetExitFunc(fn func(int))
- func (l *Logger) SetFieldFormats(f FieldFormats)
- func (l *Logger) SetFieldSort(sort Sort)
- func (l *Logger) SetFieldStyleLevel(level Level)
- func (l *Logger) SetFieldTimeFormat(format string)
- func (l *Logger) SetHandler(h Handler)
- func (l *Logger) SetIndent(levels int)
- func (l *Logger) SetIndentPrefixSeparator(sep string)
- func (l *Logger) SetIndentPrefixes(prefixes []string)
- func (l *Logger) SetIndentWidth(width int)
- func (l *Logger) SetJSONIndent(indent string)
- func (l *Logger) SetJSONPrintMode(mode JSONPrintMode)
- func (l *Logger) SetLabelWidth(width int)
- func (l *Logger) SetLabels(labels LabelMap)
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) SetLevelAlign(align Align)
- func (l *Logger) SetNonTTYLevel(level Level)
- 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) SetPrintIndent(indent string)
- func (l *Logger) SetQuote(mode Quote)
- func (l *Logger) SetQuoteChars(openChar, closeChar rune)
- func (l *Logger) SetReportTimestamp(report bool)
- func (l *Logger) SetSeparatorText(sep string)
- func (l *Logger) SetSliceBrackets(openChar, closeChar rune)
- func (l *Logger) SetSliceSeparator(sep string)
- func (l *Logger) SetSmartQuoteChars(pairs ...QuotePair)
- func (l *Logger) SetSmartQuotes(enabled bool)
- func (l *Logger) SetSpinnerDefaults(opts ...spinner.Option)
- func (l *Logger) SetStyles(styles *style.Config)
- func (l *Logger) SetSymbols(symbols LabelMap)
- func (l *Logger) SetTheme(p *theme.Pair)
- func (l *Logger) SetTimeFormat(format string)
- func (l *Logger) SetTimeLocation(loc *time.Location)
- func (l *Logger) SetTreeChars(chars TreeChars)
- func (l *Logger) SetWrap(wrap Wrap)
- func (l *Logger) SetYAMLIndent(indent string)
- func (l *Logger) SetYAMLIndentSequence(indent bool)
- func (l *Logger) Shimmer(msg string, opts ...shimmer.Option) *fx.Builder
- func (l *Logger) Spinner(msg string, opts ...spinner.Option) *fx.Builder
- func (l *Logger) Trace() *Event
- func (l *Logger) Warn() *Event
- func (l *Logger) With() *Context
- func (l *Logger) WithContext(ctx context.Context) context.Context
- type Output
- func (o *Output) ColorsDisabled() bool
- func (o *Output) CursorPosition() (int, bool)
- func (o *Output) Height() int
- func (o *Output) Hyperlink(url, text string) string
- func (o *Output) IsTTY() bool
- func (o *Output) ListenResize() func()
- func (o *Output) LiveRegion() *core.LiveRegion
- func (o *Output) PathLink(path string, line, column int) string
- func (o *Output) RefreshHeight()
- func (o *Output) RefreshWidth()
- func (o *Output) Width() int
- func (o *Output) WriteLine(s string)
- func (o *Output) Writer() io.Writer
- type Part
- type Printer
- type Quote
- type QuotePair
- type Sort
- type Style
- type TaskResult
- type TreeChars
- type TreePos
- type Update
- type Wrap
Constants ¶
const ( LevelTrace = level.Trace LevelDebug = level.Debug LevelInfo = level.Info LevelHint = level.Hint LevelDry = level.Dry LevelWarn = level.Warn LevelError = level.Error LevelFatal = level.Fatal // UnsetLevel is passed to [SetNonTTYLevel] to disable the non-TTY level // filter. Its value is intentionally below all real log levels so the // check e.level < nonTTYLevel is always false, meaning no restriction. UnsetLevel = level.Unset )
const ( LevelTraceValue = level.TraceValue LevelDebugValue = level.DebugValue LevelInfoValue = level.InfoValue LevelHintValue = level.HintValue LevelDryValue = level.DryValue LevelWarnValue = level.WarnValue LevelErrorValue = level.ErrorValue LevelFatalValue = level.FatalValue )
const ( QuoteAuto = core.QuoteAuto QuoteAlways = core.QuoteAlways QuoteNever = core.QuoteNever )
const ( SortNone = core.SortNone SortAscending = core.SortAscending SortDescending = core.SortDescending )
const ( FieldAlignmentNone = fx.FieldAlignmentNone FieldAlignmentMessage = fx.FieldAlignmentMessage )
const ( PartTimestamp = core.PartTimestamp PartLevel = core.PartLevel PartSymbol = core.PartSymbol PartMessage = core.PartMessage PartFields = core.PartFields )
const ( TreeFirst = core.TreeFirst TreeMiddle = core.TreeMiddle TreeLast = core.TreeLast )
const DefaultEnvPrefix = "CLOG"
DefaultEnvPrefix is the default environment variable prefix.
const ErrorKey = core.ErrorKey
ErrorKey is the default field key used by Event.Err and [Context.Err].
const Nil = core.Nil
Nil is the string representation used for nil values.
Variables ¶
var Default = New(Stdout(ColorAuto))
Default is the default logger instance.
Functions ¶
func AddHook ¶ added in v0.7.19
func AddHook(point HookPoint, fn func())
AddHook registers a hook on the Default logger at the given HookPoint.
func Bar ¶ added in v0.5.0
Bar creates a new fx.Builder using the Default logger with a determinate progress bar animation. total is the maximum progress value. Use [Update.SetProgress] to update progress.
func ClearAllHooks ¶ added in v0.7.19
func ClearAllHooks()
ClearAllHooks removes all registered hooks on the Default logger.
func ClearHooks ¶ added in v0.7.19
func ClearHooks(point HookPoint)
ClearHooks removes all hooks at the given HookPoint on the Default logger.
func ColorsDisabled ¶
func ColorsDisabled() bool
ColorsDisabled returns true if colors 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 DefaultStyles ¶
DefaultStyles returns the default color styles.
func Group ¶ added in v0.5.0
Group creates a new animation group using the Default logger. Configure it with options from the fx package, e.g. fx.WithParallelism or fx.WithHideDone.
func Hyperlink ¶
Hyperlink wraps text in an OSC 8 terminal hyperlink escape sequence, using the Default logger's output and hyperlink configuration. Returns plain text when colors or hyperlinks are disabled.
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 LevelTrace and LevelDebug.
func PathLink ¶
PathLink creates a clickable terminal hyperlink for a file path, using the Default logger's output and hyperlink configuration. The line parameter is optional - pass 0 to omit line numbers.
func Pulse ¶ added in v0.4.2
Pulse creates a new fx.Builder using the Default logger with an animated color pulse on the message text. All characters fade uniformly between colors in the gradient. With no options, the default pulse gradient and speed are used. Use pulse.WithGradient and pulse.WithSpeed to customise the animation.
func RegisterLevel ¶ added in v0.5.8
func RegisterLevel(lvl 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, symbols, and styles.
RegisterLevel panics if cfg.Name is empty or level conflicts with a built-in level.
func SetAnimationInterval ¶ added in v0.5.0
SetAnimationInterval sets the minimum animation refresh interval on the Default logger.
func SetColorMode ¶
func SetColorMode(mode ColorMode)
SetColorMode sets the color 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 SetExitCode ¶ added in v0.7.17
func SetExitCode(code int)
SetExitCode sets the default fatal exit code on the Default logger.
func SetExitFunc ¶
func SetExitFunc(fn func(int))
SetExitFunc sets the fatal-exit function on the Default logger.
func SetFieldFormats ¶ added in v0.11.0
func SetFieldFormats(f FieldFormats)
SetFieldFormats replaces the field-format configuration 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 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 SetJSONIndent ¶ added in v0.8.1
func SetJSONIndent(indent string)
SetJSONIndent sets a JSON-specific indent on the Default logger.
func SetJSONPrintMode ¶ added in v0.8.1
func SetJSONPrintMode(mode JSONPrintMode)
SetJSONPrintMode sets the default JSONPrintMode on the Default logger.
func SetLabelWidth ¶ added in v0.11.0
func SetLabelWidth(width int)
SetLabelWidth sets an explicit minimum level-label width on the Default logger.
func SetLabels ¶ added in v0.6.0
func SetLabels(labels LabelMap)
SetLabels sets the level labels 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 SetNonTTYLevel ¶ added in v0.5.12
func SetNonTTYLevel(level Level)
SetNonTTYLevel sets the minimum log level for non-TTY writers on the Default logger. Pass UnsetLevel to restore the default behaviour.
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 SetPrintIndent ¶ added in v0.8.0
func SetPrintIndent(indent string)
SetPrintIndent sets the printer indentation string on the Default logger.
func SetQuote ¶ added in v0.9.0
func SetQuote(mode Quote)
SetQuote sets the quoting behaviour on the Default logger.
func SetQuoteChars ¶
func SetQuoteChars(openChar, closeChar rune)
SetQuoteChars sets the opening and closing quote characters 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 SetSliceBrackets ¶ added in v0.7.9
func SetSliceBrackets(openChar, closeChar rune)
SetSliceBrackets sets separate slice open/close bracket characters on the Default logger.
func SetSliceSeparator ¶ added in v0.7.9
func SetSliceSeparator(sep string)
SetSliceSeparator sets the slice element separator on the Default logger.
func SetSmartQuoteChars ¶ added in v0.11.4
func SetSmartQuoteChars(pairs ...QuotePair)
SetSmartQuoteChars sets the smart-quote delimiter preference order on the Default logger.
func SetSmartQuotes ¶ added in v0.11.4
func SetSmartQuotes(enabled bool)
SetSmartQuotes enables or disables content-adaptive quoting on the Default logger.
func SetSpinnerDefaults ¶ added in v0.11.0
SetSpinnerDefaults sets the default spinner configuration on the Default logger.
func SetSymbols ¶ added in v0.6.0
func SetSymbols(symbols LabelMap)
SetSymbols sets the level symbols 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 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 SetWrap ¶ added in v0.9.0
func SetWrap(wrap Wrap)
SetWrap sets the line wrapping behaviour on the Default logger.
func SetYAMLIndent ¶ added in v0.8.1
func SetYAMLIndent(indent string)
SetYAMLIndent sets a YAML-specific indent on the Default logger.
func SetYAMLIndentSequence ¶ added in v0.8.1
func SetYAMLIndentSequence(indent bool)
SetYAMLIndentSequence controls YAML sequence indentation on the Default logger.
func Shimmer ¶ added in v0.4.2
Shimmer creates a new fx.Builder using the Default logger with an animated gradient shimmer on the message text. Each character is colored independently based on its position in the wave. With no options, the default shimmer gradient, direction, and speed are used. Use shimmer.WithGradient, shimmer.WithDirection, and shimmer.WithSpeed to customise the animation.
func Spinner ¶
Spinner creates a new fx.Builder using the Default logger with a rotating spinner animation.
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 ColorMode ¶
type ColorMode int
ColorMode controls how a Logger determines color 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 Config ¶
type Config struct {
// Output is the output to use (defaults to [Stdout]([ColorAuto])).
Output *Output
// Styles allows customising the visual styles.
Styles *style.Config
// 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) 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) Dedent ¶ added in v0.5.5
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
Depth adds multiple indent levels at once. Equivalent to calling Context.Indent n times.
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) Indent ¶ added in v0.5.4
Indent adds one indent level to the sub-logger. Chainable: With().Indent().Indent().Logger() produces two levels of indentation.
func (*Context) Line ¶
Line adds a file path field with a line number as a clickable terminal hyperlink. Respects the logger's ColorMode setting. If line < 1, the line number is omitted and the field is rendered as a plain path hyperlink (equivalent to Context.Path).
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) Links ¶ added in v0.7.6
Links adds a string slice field where each element is a hyperlink.
func (*Context) Logger ¶
Logger returns a new Logger with the accumulated fields and symbol. 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) Tree ¶ added in v0.5.6
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.
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"`
Symbol string `json:"symbol,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 Dict ¶
func Dict() *Event
Dict returns a new detached Event for use as a nested dictionary field. The event uses the Default logger's output for hyperlink/color resolution.
func Hint ¶ added in v0.9.3
func Hint() *Event
Hint returns a new hint-level Event from the Default logger.
func Log ¶ added in v0.5.8
Log returns a new Event at the given level from the Default logger. Use this for custom levels registered with RegisterLevel.
func (*Event) AnErr ¶ added in v0.7.0
AnErr adds an error as a keyed field. No-op if err is nil. Unlike Event.Err, this does not interact with Event.Send or Event.Msg semantics - the error is simply added as a regular field with the given key.
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) Discard ¶ added in v0.7.0
Discard disables the event so Msg/Msgf/Send won't produce output. Returns nil to short-circuit subsequent field methods.
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) Elapsed ¶ added in v0.5.1
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 fx.Builder.Elapsed.
e := clog.Info().Str("step", "migrate").Elapsed("elapsed")
runMigrations()
e.Msg("done")
// Output: INF ℹ️ done step=migrate elapsed=2s
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) Errs ¶ added in v0.4.10
Errs adds an error slice field. Each error is converted to its message string; nil errors are rendered as Nil ("<nil>").
func (*Event) ExitCode ¶ added in v0.7.17
ExitCode sets the exit code for LevelFatal events. The default exit code is 1. This has no effect on non-fatal events.
func (*Event) Fraction ¶ added in v0.7.26
Fraction adds a current/total field with gradient color styling. The color is interpolated from the style.Config.PercentGradient stops (default: red → yellow → green) based on current/total progress. Current is clamped to [0, total].
func (*Event) Func ¶ added in v0.4.10
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) 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. If line < 1, the line number is omitted and the field is rendered as a plain path hyperlink (equivalent to Event.Path).
func (*Event) Links ¶ added in v0.7.6
Links adds a string slice field where each element is a hyperlink.
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 LevelFatal events, Msg calls os.Exit after writing. The exit code defaults to 1, but can be changed with Event.ExitCode or Logger.SetExitCode.
func (*Event) MsgFunc ¶ added in v0.7.0
MsgFunc finalises the event with a lazily-computed message. The function is only called if the event is enabled (non-nil).
func (*Event) Parts ¶ added in v0.5.1
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 ¶
Path adds a file path field as a clickable terminal hyperlink. Respects the logger's ColorMode setting.
func (*Event) Quantities ¶ added in v0.2.2
Quantities adds a quantity string slice field. Each element is styled with style.Config.FieldQuantityNumber and style.Config.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 style.Config.FieldQuantityNumber and style.Config.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) TimeDiff ¶ added in v0.7.0
TimeDiff adds the field key with the duration between t and start. If t is not after start, the duration is zero.
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.
func (*Event) URLs ¶ added in v0.7.6
URLs adds a string slice field where each element is a hyperlink with the URL as the display text.
type FieldAlignment ¶ added in v0.7.0
type FieldAlignment = fx.FieldAlignment
FieldAlignment controls optional group-level field alignment behavior.
type FieldFormats ¶ added in v0.11.0
type FieldFormats struct {
// DurationFormat overrides the formatter for [time.Duration] fields.
// It also applies to elapsed fields when ElapsedFormat is nil.
// nil means the built-in format.
DurationFormat func(time.Duration) string
// DurationGradientMax is the duration mapped to the end of the
// Duration gradient stops. 0 disables the gradient.
DurationGradientMax time.Duration
// ElapsedFormat overrides the formatter for elapsed-time fields.
// nil means DurationFormat, then the built-in format.
ElapsedFormat func(time.Duration) string
// ElapsedGradientMax is the duration mapped to the end of the
// Elapsed gradient stops. 0 disables the gradient.
ElapsedGradientMax time.Duration
// ElapsedMinimum hides elapsed fields below this duration.
// The default is [time.Second]; 0 shows all values.
ElapsedMinimum time.Duration
// ElapsedPrecision is the decimal precision for elapsed display
// (0 = "3s", 1 = "3.2s").
ElapsedPrecision int
// ElapsedRound is the rounding granularity for elapsed values.
// The default is [time.Second]; 0 disables rounding.
ElapsedRound time.Duration
// HyperlinkEnabled controls whether hyperlinks are rendered at all.
HyperlinkEnabled bool
// HyperlinkColumnFormat is the URL format for file+line+column links.
// Accepts a full format string or a preset name (e.g. "vscode").
HyperlinkColumnFormat string
// HyperlinkDirFormat is the URL format for directory links.
HyperlinkDirFormat string
// HyperlinkFileFormat is the URL format for file-only links.
HyperlinkFileFormat string
// HyperlinkLineFormat is the URL format for file+line links.
HyperlinkLineFormat string
// HyperlinkPathFormat is the generic fallback URL format for any path.
HyperlinkPathFormat string
// PercentFormat overrides the formatter for percent fields.
// It receives the display value (already scaled to 0–100).
// nil means the built-in format.
PercentFormat func(float64) string
// PercentMaximum is the input range maximum for percent values.
// 0 means the default of 1.0 (fractions); set 100 for 0–100 input.
PercentMaximum float64
// PercentPrecision is the decimal precision for percent display
// (0 = "75%", 1 = "75.0%").
PercentPrecision int
// PercentReverseGradient flips the percent gradient direction
// (green at 0%, red at 100%) for usage-style metrics.
PercentReverseGradient bool
// QuantityUnitsIgnoreCase enables case-insensitive quantity unit
// matching. Note the default via [DefaultFieldFormats] is true.
QuantityUnitsIgnoreCase bool
}
FieldFormats holds all field-formatting configuration for a Logger. Set it with Logger.SetFieldFormats; read the current snapshot with Logger.FieldFormats. Zero-value fields mean the documented default where one exists.
func DefaultFieldFormats ¶ added in v0.11.0
func DefaultFieldFormats() FieldFormats
DefaultFieldFormats returns the default field-format configuration: hyperlinks enabled, elapsed rounded to whole seconds and hidden below one second, case-insensitive quantity units, and built-in formatters.
type GroupStatusFunc ¶ added in v0.7.25
type GroupStatusFunc = fx.GroupStatusFunc
GroupStatusFunc is called each render tick with the number of completed and total tasks. Use the Update to set the message and fields.
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 HookPoint ¶ added in v0.7.19
type HookPoint int
HookPoint identifies when a hook fires during the log write lifecycle.
type JSONPrintMode ¶ added in v0.8.1
type JSONPrintMode int
JSONPrintMode controls how the Printer formats its output.
const ( // JSONPretty pretty-prints output with normalized indentation. JSONPretty JSONPrintMode = iota // JSONFlat flattens output to a single line, matching the compact // format used by inline log fields. JSONFlat // JSONPreserve keeps original whitespace intact, only adding syntax highlighting. JSONPreserve )
type LabelMap ¶ added in v0.6.0
LabelMap maps levels to strings (used for labels, symbols, etc.).
func DefaultLabels ¶
func DefaultLabels() LabelMap
DefaultLabels returns a copy of the default level labels.
func DefaultSymbols ¶ added in v0.6.0
func DefaultSymbols() LabelMap
DefaultSymbols returns a copy of the default emoji symbols for each level.
type Level ¶
Level represents a log level.
Level implements encoding.TextMarshaler and encoding.TextUnmarshaler, so it works directly with flag.TextVar and most flag libraries.
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
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.
type LevelConfig ¶ added in v0.5.8
type LevelConfig struct {
Label string // short display label (e.g. "SCS") [default: uppercase Name, max 3 chars]
Name string // canonical name for ParseLevel/MarshalText (e.g. "success") [required]
Style Style // lipgloss style for the level label [default: nil]
Symbol string // emoji symbol (e.g. "✅") [default: ""]
}
LevelConfig configures a custom log level for use with RegisterLevel.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is the main structured logger.
func Ctx ¶ added in v0.5.0
Ctx retrieves the logger from ctx. Returns Default if ctx is nil or contains no logger.
func New ¶
New creates a new Logger that writes to the given Output. If output is nil, it defaults to Stdout with ColorAuto.
func (*Logger) AddHook ¶ added in v0.7.19
AddHook registers a function to run at the given HookPoint. Multiple hooks per point are supported; they run in registration order. Hooks are called under the logger's mutex.
func (*Logger) Bar ¶ added in v0.5.0
Bar creates a new fx.Builder with a determinate progress bar animation. total is the maximum progress value. Use [Update.SetProgress] to update progress.
func (*Logger) ClearAllHooks ¶ added in v0.7.19
func (l *Logger) ClearAllHooks()
ClearAllHooks removes all registered hooks at every HookPoint.
func (*Logger) ClearHooks ¶ added in v0.7.19
ClearHooks removes all hooks registered at the given HookPoint.
func (*Logger) Dict ¶ added in v0.6.0
Dict returns a new detached Event for use as a nested dictionary field. The event uses the logger's output for hyperlink/color resolution.
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) FieldFormats ¶ added in v0.11.0
func (l *Logger) FieldFormats() FieldFormats
FieldFormats returns a copy of the logger's current field-format configuration.
func (*Logger) Group ¶ added in v0.5.0
Group creates a new animation group. Configure it with options from the fx package, e.g. fx.WithParallelism or fx.WithHideDone.
func (*Logger) Hint ¶ added in v0.9.3
Hint returns a new Event at hint level, or nil if hint is disabled.
func (*Logger) LevelEnabled ¶ added in v0.6.0
LevelEnabled reports whether the logger handles records at the given level.
func (*Logger) Log ¶ added in v0.5.8
Log returns a new Event at the given level. Use this for custom levels registered with RegisterLevel.
func (*Logger) LogFields ¶ added in v0.6.0
LogFields logs a message at the given level with the provided timestamp and fields. This is used by adapters (e.g. [sloghandler]) that build fields externally. Unlike direct Fatal() calls, LogFields does not trigger os.Exit for LevelFatal events -- adapters should not cause process termination.
func (*Logger) Print ¶ added in v0.8.0
Print returns a new Printer for writing styled output without a log level. The printer inherits the logger's print mode (see Logger.SetJSONPrintMode). Use Printer.Mode for per-call overrides.
func (*Logger) Pulse ¶ added in v0.4.17
Pulse creates a new fx.Builder with an animated color pulse on the message text. All characters fade uniformly between colors in the gradient. With no options, the default pulse gradient and speed are used. Use pulse.WithGradient and pulse.WithSpeed to customise the animation.
func (*Logger) SetAnimationInterval ¶ added in v0.5.0
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 ¶
SetColorMode sets the color mode by recreating the logger's Output with the given mode.
func (*Logger) SetExitCode ¶ added in v0.7.17
SetExitCode sets the default exit code for LevelFatal events. If code is 0, the default exit code (1) is used. This can be overridden per-event with Event.ExitCode.
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) SetFieldFormats ¶ added in v0.11.0
func (l *Logger) SetFieldFormats(f FieldFormats)
SetFieldFormats replaces the logger's field-format configuration (replace-all semantics, like Logger.SetParts). Hyperlink format fields accept preset names (e.g. "vscode"), which are expanded on store.
f := clog.DefaultFieldFormats() f.PercentPrecision = 1 logger.SetFieldFormats(f)
func (*Logger) SetFieldSort ¶ added in v0.4.15
SetFieldSort sets the sort order for fields in log output. Default SortNone preserves insertion order.
func (*Logger) SetFieldStyleLevel ¶ added in v0.1.2
SetFieldStyleLevel sets the minimum log level at which field values are styled (colored). Events below this level render fields as plain text. Defaults to LevelInfo.
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) SetIndent ¶ added in v0.5.4
SetIndent sets the indent depth (number of indent levels) on the logger.
func (*Logger) SetIndentPrefixSeparator ¶ added in v0.5.4
SetIndentPrefixSeparator sets the separator appended after an indent prefix. Defaults to " " (a single space).
func (*Logger) SetIndentPrefixes ¶ added in v0.5.4
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
SetIndentWidth sets the number of spaces per indent level. Defaults to 2.
func (*Logger) SetJSONIndent ¶ added in v0.8.1
SetJSONIndent sets a JSON-specific indentation string, overriding SetPrintIndent for JSON output only. Pass "" to clear and fall back to SetPrintIndent.
func (*Logger) SetJSONPrintMode ¶ added in v0.8.1
func (l *Logger) SetJSONPrintMode(mode JSONPrintMode)
SetJSONPrintMode sets the default JSONPrintMode for Printer JSON output. The default is JSONPretty. Per-call overrides are available via Printer.Mode.
func (*Logger) SetLabelWidth ¶ added in v0.4.17
SetLabelWidth sets an explicit minimum width for level labels. If width is 0, the width is computed automatically from the current labels.
func (*Logger) SetLabels ¶
SetLabels sets the level labels used in log output. Pass a map from Level to label string (e.g. {LevelWarn: "WARN"}). Missing levels fall back to the defaults.
func (*Logger) SetLevelAlign ¶
SetLevelAlign sets the alignment mode for level labels.
func (*Logger) SetNonTTYLevel ¶ added in v0.5.12
SetNonTTYLevel sets the minimum log level for non-TTY writers (CI, piped output, etc.). Events below this level are suppressed when the logger's output is not connected to a terminal, including animation progress lines. Pass UnsetLevel to restore the default behaviour.
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) SetOutput ¶
SetOutput sets the output. The logger's hyperlink formats are pushed to the new output so Output.PathLink and Output.Hyperlink keep honouring the logger's FieldFormats.
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) SetPrintIndent ¶ added in v0.8.0
SetPrintIndent sets the indentation string used by Printer output in [PrintMultiline] mode. Defaults to two spaces (" ").
func (*Logger) SetQuote ¶ added in v0.9.0
SetQuote 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) SetQuoteChars ¶
SetQuoteChars sets the opening and closing characters used to quote field values that contain spaces or special characters (e.g. '[' and ']', or '«' and '»'). Pass the same rune twice for symmetric quoting. The default (zero values) uses Go-style double-quoted strings via strconv.Quote.
func (*Logger) SetReportTimestamp ¶
SetReportTimestamp enables or disables timestamp reporting.
func (*Logger) SetSeparatorText ¶ added in v0.4.15
SetSeparatorText sets the separator between field keys and values. Defaults to "=".
func (*Logger) SetSliceBrackets ¶ added in v0.7.9
SetSliceBrackets sets the opening and closing characters for slice field values. Pass the same rune twice for symmetric brackets. Defaults to '[' and ']'.
func (*Logger) SetSliceSeparator ¶ added in v0.7.9
SetSliceSeparator sets the separator between elements in slice field values. Defaults to ", ".
func (*Logger) SetSmartQuoteChars ¶ added in v0.11.4
SetSmartQuoteChars sets the delimiter preference order used by smart quoting (see Logger.SetSmartQuotes). Each pair may use distinct open/close runes (e.g. {Open: '«', Close: '»'}); a zero Close mirrors Open. Passing no pairs restores the default order ('"', then '\”, then '`'). This configures the order only; it does not by itself enable smart quoting.
func (*Logger) SetSmartQuotes ¶ added in v0.11.4
SetSmartQuotes enables or disables content-adaptive quoting. When enabled, each quoted value is wrapped in the first delimiter pair (see Logger.SetSmartQuoteChars) whose delimiters do not occur in the value, so no escaping is needed; it falls back to Go-style escaped quoting only when no pair fits (or the value contains backslashes or non-printable runes). Smart quoting takes precedence over Logger.SetQuoteChars.
func (*Logger) SetSpinnerDefaults ¶ added in v0.11.0
SetSpinnerDefaults sets the default spinner configuration used by Logger.Spinner, built by applying opts over spinner.DefaultConfig.
func (*Logger) SetStyles ¶
SetStyles merges the given styles into the current style configuration. Non-nil pointer fields overwrite existing values; map fields are merged key-by-key. Pass nil to reset to DefaultStyles.
func (*Logger) SetSymbols ¶ added in v0.6.0
SetSymbols sets the emoji symbols used for each level. Pass a map from Level to symbol string. Missing levels fall back to the defaults.
func (*Logger) SetTheme ¶ added in v0.11.0
SetTheme sets the light/dark theme pair used for printer styles (JSON, YAML, TOML, HCL). The side matching the detected terminal background is applied lazily on the next write. Pass nil to restore the built-in default pair. For a fixed theme regardless of background, use theme.Single. Per-token overrides via SetStyles still apply.
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.
func (*Logger) SetTreeChars ¶ added in v0.5.6
SetTreeChars sets the box-drawing characters used for tree indentation. See DefaultTreeChars for the defaults.
func (*Logger) SetWrap ¶ added in v0.9.0
SetWrap sets the line wrapping behaviour. When set to WrapHard or WrapSoft, log lines exceeding the terminal width are wrapped before writing. WrapSoft prefers breaking at word boundaries. Has no effect on non-TTY outputs.
func (*Logger) SetYAMLIndent ¶ added in v0.8.1
SetYAMLIndent sets a YAML-specific indentation string, overriding SetPrintIndent for YAML output only. Pass "" to clear and fall back to SetPrintIndent.
func (*Logger) SetYAMLIndentSequence ¶ added in v0.8.1
SetYAMLIndentSequence controls whether YAML sequences (arrays) are indented under their parent key. Defaults to true. Pass false for compact output:
# true (default) tags: - a - b # false tags: - a - b
func (*Logger) Shimmer ¶ added in v0.4.17
Shimmer creates a new fx.Builder with an animated gradient shimmer on the message text. Each character is colored independently based on its position in the wave. With no options, the default shimmer gradient, direction, and speed are used. Use shimmer.WithGradient, shimmer.WithDirection, and shimmer.WithSpeed to customise the animation.
func (*Logger) Spinner ¶ added in v0.4.17
Spinner creates a new fx.Builder with a rotating spinner animation.
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) CursorPosition ¶ added in v0.11.0
CursorPosition reports the cursor's current 1-based row, if known. It returns false for non-TTY writers or when the terminal does not answer the cursor-position query in time.
func (*Output) Height ¶ added in v0.7.24
Height returns the terminal height, or 0 for non-TTY writers. The value is lazily detected and cached; call Output.RefreshHeight to re-detect.
func (*Output) Hyperlink ¶ added in v0.6.0
Hyperlink wraps text in an OSC 8 terminal hyperlink, using the Output's color settings and hyperlink configuration. Satisfies fx.Output.
func (*Output) ListenResize ¶ added in v0.7.25
func (o *Output) ListenResize() func()
ListenResize starts a background goroutine that refreshes the cached terminal width and height on SIGWINCH. Call the returned stop function to unregister the signal handler and release the goroutine. No-op for non-TTY outputs.
func (*Output) LiveRegion ¶ added in v0.11.0
func (o *Output) LiveRegion() *core.LiveRegion
LiveRegion returns the live-animation region for this output, creating it on first use. There is exactly one region per Output so every animation and log line on the same writer coordinates through it. The fx render loops discover the region via an optional-capability type assertion, which keeps the fx.Output interface (and external implementations) unchanged.
func (*Output) PathLink ¶ added in v0.6.0
PathLink creates a clickable terminal hyperlink for a file path, using the Output's color settings and hyperlink configuration. Satisfies fx.Output.
func (*Output) RefreshHeight ¶ added in v0.7.24
func (o *Output) RefreshHeight()
RefreshHeight re-queries the terminal for the current height and updates the cached value. If the query fails (or the writer is not a TTY) the cache is left untouched, so manually-seeded test heights survive a refresh.
func (*Output) RefreshWidth ¶ added in v0.3.1
func (o *Output) RefreshWidth()
RefreshWidth re-queries the terminal for the current width and updates the cached value. If the query fails (or the writer is not a TTY) the cache is left untouched, so manually-seeded test widths survive a refresh.
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.
func (*Output) WriteLine ¶ added in v0.11.0
WriteLine writes a fully formatted log line (or multi-line payload ending in a newline) to the underlying writer. While animations are live on this output, the write is routed through the core.LiveRegion so the animation block is displaced: erased, the line written above, and the block repainted below in one synchronized frame. Without an active region this is a plain write.
type Part ¶
Part identifies a component of a formatted log line.
func DefaultParts ¶
func DefaultParts() []Part
DefaultParts returns the default ordering of log line parts: timestamp, level, symbol, message, fields.
type Printer ¶ added in v0.8.0
type Printer struct {
// contains filtered or unexported fields
}
Printer outputs styled data directly to the logger's output, without requiring a log level. Create one with Logger.Print or the package-level Print function.
clog.Print().JSON(data)
clog.Print().RawJSON([]byte(`{"a":1}`))
func Print ¶ added in v0.8.0
func Print() *Printer
Print returns a new Printer for writing styled output from the Default logger.
func (*Printer) JSON ¶ added in v0.8.0
JSON marshals v to JSON and writes syntax-highlighted output. If marshalling fails, the error string is written instead.
func (*Printer) Mode ¶ added in v0.8.0
func (p *Printer) Mode(mode JSONPrintMode) *Printer
Mode sets the print mode for this call, overriding the logger default.
func (*Printer) RawHCL ¶ added in v0.8.1
RawHCL writes pre-serialized HCL bytes with syntax highlighting. Token colors are inherited from the logger's HCL configuration.
func (*Printer) RawJSON ¶ added in v0.8.0
RawJSON writes pre-serialized JSON bytes with syntax highlighting. Only token colors are inherited from the logger's JSON configuration; field-specific settings (Mode, Spacing, OmitCommas) are not applied.
func (*Printer) RawTOML ¶ added in v0.8.1
RawTOML writes pre-serialized TOML bytes with syntax highlighting. Token colors are inherited from the logger's TOML configuration.
func (*Printer) RawYAML ¶ added in v0.8.1
RawYAML writes pre-serialized YAML bytes with syntax highlighting. Token colors are inherited from the logger's YAML configuration.
type QuotePair ¶ added in v0.11.4
QuotePair is an opening/closing delimiter pair used for smart quoting (see Logger.SetSmartQuoteChars). A zero Close means Close equals Open (symmetric quoting).
type Style ¶ added in v0.4.4
Style is a pointer type (*lipgloss.Style). A nil Style means "no style" and is safe to pass wherever a Style is accepted.
type TaskResult ¶ added in v0.5.4
type TaskResult = fx.TaskResult
Convenience aliases so callers can reference common fx types without importing subpackages directly.
type TreeChars ¶ added in v0.5.6
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 Update ¶ added in v0.6.0
Convenience aliases so callers can reference common fx types without importing subpackages directly.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
banner
command
|
|
|
bar
command
|
|
|
group
command
|
|
|
indent
command
|
|
|
json
command
|
|
|
levels
command
|
|
|
printer
command
|
|
|
pulse
command
|
|
|
shimmer
command
|
|
|
spinner
command
|
|
|
styles
command
|
|
|
tree
command
|
|
|
field
|
|
|
fraction
Package fraction provides options for fraction field rendering in clog.
|
Package fraction provides options for fraction field rendering in clog. |
|
hyperlink
Package hyperlink provides terminal hyperlink rendering for clog.
|
Package hyperlink provides terminal hyperlink rendering for clog. |
|
percent
Package percent provides options for percent field rendering in clog.
|
Package percent provides options for percent field rendering in clog. |
|
Package fx provides terminal animation types (spinners, progress bars, shimmers, and pulses) with composable builders and group orchestration.
|
Package fx provides terminal animation types (spinners, progress bars, shimmers, and pulses) with composable builders and group orchestration. |
|
bar
Package bar provides bar animation styles and presets for clog.
|
Package bar provides bar animation styles and presets for clog. |
|
bar/widget
Package widget provides composable text widgets for progress bars.
|
Package widget provides composable text widgets for progress bars. |
|
pulse
Package pulse provides pulse animation rendering for clog.
|
Package pulse provides pulse animation rendering for clog. |
|
shimmer
Package shimmer provides shimmer animation rendering for clog.
|
Package shimmer provides shimmer animation rendering for clog. |
|
spinner
Package spinner provides spinner animation styles and presets for clog.
|
Package spinner provides spinner animation styles and presets for clog. |
|
internal
|
|
|
core
Package core provides shared value types used by both the root clog package and subpackages like fx/.
|
Package core provides shared value types used by both the root clog package and subpackages like fx/. |
|
env
Package env holds the process-wide environment-variable prefix shared by clog's packages, and the "custom prefix first, then CLOG" lookup built on it.
|
Package env holds the process-wide environment-variable prefix shared by clog's packages, and the "custom prefix first, then CLOG" lookup built on it. |
|
gradient
Package gradient provides color gradient interpolation shared by the style and fx packages.
|
Package gradient provides color gradient interpolation shared by the style and fx packages. |
|
numfmt
Package numfmt provides human-readable formatting for byte counts.
|
Package numfmt provides human-readable formatting for byte counts. |
|
Package level defines the Level type and built-in level constants for clog.
|
Package level defines the Level type and built-in level constants for clog. |
|
hcl
Package hcl provides HCL syntax highlighting for clog.
|
Package hcl provides HCL syntax highlighting for clog. |
|
json
Package json provides JSON syntax highlighting for clog.
|
Package json provides JSON syntax highlighting for clog. |
|
toml
Package toml provides TOML syntax highlighting for clog.
|
Package toml provides TOML syntax highlighting for clog. |
|
yaml
Package yaml provides YAML syntax highlighting for clog.
|
Package yaml provides YAML syntax highlighting for clog. |
|
Package sloghandler provides a slog.Handler adapter for clog.
|
Package sloghandler provides a slog.Handler adapter for clog. |
|
Package style provides styling types, color stops, and defaults for clog.
|
Package style provides styling types, color stops, and defaults for clog. |
|
Package theme provides color palettes for syntax highlighting.
|
Package theme provides color palettes for syntax highlighting. |