clog

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 19 Imported by: 2

README

clog

Structured CLI logging for Go with terminal-aware colours, hyperlinks, and spinners. A zerolog-style fluent API designed for command-line tools.

Demo

clog demo

Installation

go get github.com/gechr/clog

Quick Start

package main

import "github.com/gechr/clog"

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

Output:

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

Levels

Level Label Prefix Description
Trace TRC 🔬 Finest-grained output, hidden by default
Debug DBG 🔍 Verbose output, hidden by default
Info INF ℹ️ General operational messages (default minimum level)
Dry DRY 🚧 Dry-run indicators
Warn WRN ⚠️ Warnings that don't prevent operation
Error ERR Errors that need attention
Fatal FTL ‼️ Fatal errors — calls os.Exit(1) after logging

Setting the Level

// Programmatically
clog.SetLevel(clog.DebugLevel)

// From environment variable (checked automatically on init)
// export CLOG_LEVEL=debug
clog.SetLevelFromEnv("CLOG_LEVEL")

Recognised CLOG_LEVEL values: trace, debug, info, dry, warn, warning, error, fatal.

Setting trace or debug also enables timestamps.

Structured Fields

Events and contexts support typed field methods. All methods are safe to call on a nil receiver (disabled events are no-ops).

Event Fields

Method Signature Description
Str Str(key, val string) String field
Strs Strs(key string, vals []string) String slice field
Int Int(key string, val int) Integer field
Ints Ints(key string, vals []int) Integer slice field
Uint64 Uint64(key string, val uint64) Unsigned integer field
Uints64 Uints64(key string, vals []uint64) Unsigned integer slice field
Float64 Float64(key string, val float64) Float field
Floats64 Floats64(key string, vals []float64) Float slice field
Bool Bool(key string, val bool) Boolean field
Bools Bools(key string, vals []bool) Boolean slice field
Dur Dur(key string, val time.Duration) Duration field
Err Err(err error) Error field (key "error", nil-safe)
Any Any(key string, val any) Arbitrary value
Anys Anys(key string, vals []any) Arbitrary value slice
Dict Dict(key string, dict *Event) Nested fields with dot-notation keys
Path Path(key, path string) Clickable file/directory hyperlink
Line Line(key, path string, lineNumber int) Clickable file:line hyperlink
Column Column(key, path string, line, column int) Clickable file:line:column hyperlink
Link Link(key, url, text string) Clickable URL hyperlink
Stringer Stringer(key string, val fmt.Stringer) Calls String() (nil-safe)
Stringers Stringers(key string, vals []fmt.Stringer) Slice of fmt.Stringer values

Finalising Events

clog.Info().Str("k", "v").Msg("message")  // Log with message
clog.Info().Str("k", "v").Msgf("n=%d", 5) // Log with formatted message
clog.Info().Str("k", "v").Send()          // Log with empty message

Omitting Empty / Zero Fields

Suppress fields with empty or zero values to reduce noise in log output.

OmitEmpty omits fields that are semantically "nothing": nil, empty strings "", and nil or empty slices and maps.

clog.SetOmitEmpty(true)
clog.Info().
    Str("name", "alice").
    Str("nickname", "").   // omitted
    Any("role", nil).      // omitted
    Int("age", 0).         // kept (zero but not empty)
    Bool("admin", false).  // kept (zero but not empty)
    Msg("User")
// INF ℹ️ User name=alice age=0 admin=false

OmitZero is a superset of OmitEmpty — it additionally omits 0, false, 0.0, zero durations, and any other typed zero value.

clog.SetOmitZero(true)
clog.Info().
    Str("name", "alice").
    Str("nickname", "").   // omitted
    Any("role", nil).      // omitted
    Int("age", 0).         // omitted
    Bool("admin", false).  // omitted
    Msg("User")
// INF ℹ️ User name=alice

Both settings are inherited by sub-loggers created with With(). When both are enabled, OmitZero takes precedence.

Quoting

By default, field values containing spaces or special characters are wrapped in Go-style double quotes ("hello world"). This behaviour can be customised with SetQuoteMode.

Quote Modes

Mode Description
QuoteAuto Quote only when needed — spaces, unprintable chars, embedded quotes (default)
QuoteAlways Always quote string, error, and default-kind values
QuoteNever Never quote (same as the deprecated SetOmitQuotes(true))
// Default: only quote when needed
clog.Info().Str("reason", "timeout").Str("msg", "hello world").Msg("test")
// INF ℹ️ test reason=timeout msg="hello world"

// Always quote string values
clog.SetQuoteMode(clog.QuoteAlways)
clog.Info().Str("reason", "timeout").Msg("test")
// INF ℹ️ test reason="timeout"

// Never quote
clog.SetQuoteMode(clog.QuoteNever)
clog.Info().Str("msg", "hello world").Msg("test")
// INF ℹ️ test msg=hello world

Custom Quote Character

Use a different character for both sides:

clog.SetQuoteChar('\'')
clog.Info().Str("msg", "hello world").Msg("test")
// INF ℹ️ test msg='hello world'

Asymmetric Quote Characters

Use different opening and closing characters:

clog.SetQuoteChars('«', '»')
clog.Info().Str("msg", "hello world").Msg("test")
// INF ℹ️ test msg=«hello world»

clog.SetQuoteChars('[', ']')
clog.Info().Str("msg", "hello world").Msg("test")
// INF ℹ️ test msg=[hello world]

Quoting applies to individual field values and to elements within string and []any slices. All quoting settings are inherited by sub-loggers. Pass 0 to reset to the default (strconv.Quote).

Deprecated: SetOmitQuotes(true/false) still works but delegates to SetQuoteMode(QuoteNever) / SetQuoteMode(QuoteAuto). Prefer SetQuoteMode for new code.

Sub-loggers

Create sub-loggers with preset fields using the With() context builder:

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

Context fields support the same typed methods as events.

Dict (Nested Fields)

Group related fields under a common key prefix using dot notation:

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

Works with sub-loggers too:

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

Custom Prefix

Override the default emoji prefix per-event or per-logger:

// Per-event
clog.Info().Prefix("📦").Str("pkg", "clog").Msg("Installed")

// Per-logger (via sub-logger)
logger := clog.With().Prefix("🔒").Str("component", "auth").Logger()
logger.Info().Msg("Ready")

Prefix resolution order: event override > logger preset > default emoji for level.

Level Alignment

Control how level labels are aligned when they have different widths:

clog.SetLevelAlign(clog.AlignRight)   // default: "  INF", " WARN", "ERROR"
clog.SetLevelAlign(clog.AlignLeft)    //          "INF  ", "WARN ", "ERROR"
clog.SetLevelAlign(clog.AlignCenter)  //          " INF ", "WARN ", "ERROR"
clog.SetLevelAlign(clog.AlignNone)    //          "INF",   "WARN",  "ERROR"

Part Order

Control which parts appear in log output and in what order. The default order is: timestamp, level, prefix, message, fields.

// Reorder: show message before level
clog.SetParts(clog.PartMessage, clog.PartLevel, clog.PartPrefix, clog.PartFields)

// Hide parts by omitting them
clog.SetParts(clog.PartLevel, clog.PartMessage, clog.PartFields) // no prefix or timestamp

// Fields before message
clog.SetParts(clog.PartLevel, clog.PartFields, clog.PartMessage)

Available parts: PartTimestamp, PartLevel, PartPrefix, PartMessage, PartFields.

Use DefaultParts() to get the default ordering. Parts omitted from the list are hidden.

Spinners

Display animated spinners during long-running operations:

err := clog.Spinner("Downloading").
    Str("url", fileURL).
    Wait(ctx, func(ctx context.Context) error {
        return download(ctx, fileURL)
    }).
    Msg("Downloaded")

The spinner animates with moon phase emojis (🌔🌓🌒🌑🌘🌗🌖🌕) while the action runs, then logs the result.

Dynamic Status Updates

Use Progress to update the spinner title and fields during execution:

err := clog.Spinner("Processing").
    Progress(ctx, func(ctx context.Context, update *clog.ProgressUpdate) error {
        for i, item := range items {
            update.Title("Processing").Str("progress", fmt.Sprintf("%d/%d", i+1, len(items))).Send()
            if err := process(ctx, item); err != nil {
                return err
            }
        }
        return nil
    }).
    Msg("Processed all items")

WaitResult Finalisers

Method Success behaviour Failure behaviour
.Msg(s) Logs at INF with message Logs at ERR with spinner title
.Debug(s) Logs at DBG with message Logs at ERR with spinner title
.Err() Logs at INF with title Logs at ERR with title + error
.Silent() Returns error, no logging Returns error, no logging

All finalisers return the error from the action. You can chain any field method (.Str(), .Int(), .Bool(), .Dur(), etc.) and .Prefix() on a WaitResult before finalising.

Spinners gracefully degrade: when colours are disabled (CI, piped output), the animation is skipped and a static status line is printed instead.

Custom Spinner Type

clog.Spinner("Loading").
    Type(spinner.Dot).
    Wait(ctx, action).
    Msg("Done")

Render clickable terminal hyperlinks using OSC 8 escape sequences:

// Typed field methods (recommended)
clog.Info().Path("dir", "src/").Msg("Directory")
clog.Info().Line("file", "config.yaml", 42).Msg("File with line")
clog.Info().Column("loc", "main.go", 42, 10).Msg("File with line and column")
clog.Info().Link("docs", "https://example.com", "docs").Msg("URL")

// Standalone functions (for use with Str)
link := clog.PathLink("config.yaml", 42)               // file path with line number
link := clog.PathLink("src/", 0)                       // directory (no line number)
link := clog.Hyperlink("https://example.com", "docs")  // arbitrary URL

IDE Integration

Configure hyperlinks to open files directly in your editor:

// Generic fallback for any path (file or directory)
clog.SetHyperlinkPathFormat("vscode://file{path}")

// File-specific (overrides path format for files)
clog.SetHyperlinkFileFormat("vscode://file{path}")

// Directory-specific (overrides path format for directories)
clog.SetHyperlinkDirFormat("finder://{path}")

// File+line hyperlinks (Line, PathLink with line > 0)
clog.SetHyperlinkLineFormat("vscode://file{path}:{line}")
clog.SetHyperlinkLineFormat("idea://open?file={path}&line={line}")

// File+line+column hyperlinks (Column)
clog.SetHyperlinkColumnFormat("vscode://file{path}:{line}:{column}")

Use {path}, {line}, and {column} (or {col}) as placeholders. Default format is file://{path}.

Format resolution order:

Context Fallback chain
Directory DirFormatPathFormatfile://{path}
File (no line) FileFormatPathFormatfile://{path}
File + line LineFormatfile://{path}
File + column ColumnFormatLineFormatfile://{path}

These can also be set via environment variables:

export CLOG_HYPERLINK_PATH_FORMAT="vscode://{path}"     # generic fallback
export CLOG_HYPERLINK_FILE_FORMAT="vscode://file{path}"  # files only
export CLOG_HYPERLINK_DIR_FORMAT="finder://{path}"       # directories only
export CLOG_HYPERLINK_LINE_FORMAT="vscode://{path}:{line}"
export CLOG_HYPERLINK_COLUMN_FORMAT="vscode://{path}:{line}:{column}"

Hyperlinks are automatically disabled when colours are disabled.

Handlers

Implement the Handler interface for custom output formats:

type Handler interface {
    Log(Entry)
}

The Entry struct provides Level, Time, Message, Prefix, and Fields. The logger handles level filtering, field accumulation, timestamps, and locking — the handler only formats and writes.

// Using HandlerFunc adapter
clog.SetHandler(clog.HandlerFunc(func(e clog.Entry) {
    data, _ := json.Marshal(e)
    fmt.Println(string(data))
}))

Configuration

Default Logger

The package-level functions (Info(), Warn(), etc.) use the Default logger which writes to os.Stdout at InfoLevel.

// Full configuration
clog.Configure(&clog.Config{
    Verbose: true,           // enables debug level + timestamps
    Output:  os.Stderr,      // custom writer
    Styles:  customStyles,   // custom visual styles
})

// Toggle verbose mode
clog.ConfigureVerbose(true)

Custom Logger

logger := clog.New(os.Stderr)
logger.SetLevel(clog.DebugLevel)
logger.SetReportTimestamp(true)
logger.SetTimeFormat("15:04:05.000")
logger.SetHandler(myHandler)

Utility Functions

clog.GetLevel()                  // returns the current level of the Default logger
clog.IsVerbose()                 // true if level is Debug or Trace
clog.IsTerminal()                // true if stdout is a terminal
clog.ColorsDisabled()            // true if colours are globally disabled
clog.SetExitFunc(fn)             // override os.Exit for Fatal (useful in tests)
clog.SetHyperlinksEnabled(false) // disable all hyperlink rendering

Environment Variables

CLOG_LEVEL and CLOG_SEPARATOR are checked automatically at init.

CLOG_LEVEL=debug ./myapp    # enables debug logging + timestamps
CLOG_LEVEL=warn ./myapp     # suppresses info messages
CLOG_SEPARATOR=": " ./myapp # use ": " instead of "=" between keys and values

NO_COLOR

clog respects the NO_COLOR convention. When the NO_COLOR environment variable is set (any value, including empty), all colours and hyperlinks are disabled.

Global Colour Control

clog.ConfigureColorOutput("auto")   // detect terminal capabilities (default)
clog.ConfigureColorOutput("always") // force colours (overrides NO_COLOR)
clog.ConfigureColorOutput("never")  // disable all colours and hyperlinks

Per-Logger Colour Mode

Each logger can override the global colour detection with SetColorMode:

logger := clog.New(os.Stdout)
logger.SetColorMode(clog.ColorAlways) // force colours for this logger
logger.SetColorMode(clog.ColorNever)  // disable colours for this logger
logger.SetColorMode(clog.ColorAuto)   // use global detection (default)

// Package-level (sets Default logger)
clog.SetColorMode(clog.ColorAlways)

This is useful in tests to verify hyperlink output without mutating global state:

l := clog.New(&buf)
l.SetColorMode(clog.ColorAlways)
l.Info().Line("file", "main.go", 42).Msg("Loaded")
// buf contains OSC 8 hyperlink escape sequences

Styles

Customise the visual appearance using lipgloss styles:

styles := clog.DefaultStyles()

// Customise level colours
styles.Levels[clog.ErrorLevel] = new(lipgloss.NewStyle().
    Bold(true).
    Foreground(lipgloss.Color("9")))  // bright red

// Customise field key appearance
styles.Key = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("12"))) // bright blue

clog.SetStyles(styles)

Value Colouring

Values are styled with a three-tier priority system:

  1. Key styles — style all values of a specific field key
  2. Value styles — style values matching an exact string
  3. Type styles — style values by their Go type
styles := clog.DefaultStyles()

// 1. Key styles: all values of the "status" field are green
styles.KeyStyles["status"] = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("2")))

// 2. Value styles: exact string matches (sensible defaults included)
//    "true" → green, "false" → red, "<nil>" / "" → grey
styles.ValueStyles["PASS"] = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("2")))  // green
styles.ValueStyles["FAIL"] = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("1")))  // red

// 3. Type styles: string values → white, numeric values → magenta, errors → red by default
styles.String = new(lipgloss.NewStyle().Foreground(lipgloss.Color("15")))
styles.Number = new(lipgloss.NewStyle().Foreground(lipgloss.Color("5")))
styles.Error  = new(lipgloss.NewStyle().Foreground(lipgloss.Color("1")))
styles.String = nil  // set to nil to disable
styles.Number = nil  // set to nil to disable

clog.SetStyles(styles)

Styles Reference

Field Type Description
Levels map[Level]*lipgloss.Style Per-level label style (nil to disable)
Messages map[Level]*lipgloss.Style Per-level message style (nil to disable)
Key *lipgloss.Style Field key style (nil to disable)
Separator *lipgloss.Style Style for the separator between key and value
SeparatorText string Key/value separator (default "=")
Timestamp *lipgloss.Style Timestamp style (nil to disable)
String *lipgloss.Style String value style (nil to disable)
Number *lipgloss.Style Numeric value style (nil to disable)
Error *lipgloss.Style Error value style (nil to disable)
KeyStyles map[string]*lipgloss.Style Field key name → value style
ValueStyles map[string]*lipgloss.Style Formatted value string → style

Value styles only apply at Info level and above (not Trace or Debug).

Per-Level Message Styles

Style the log message text differently for each level:

styles := clog.DefaultStyles()
styles.Messages[clog.ErrorLevel] = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("1"))) // red
styles.Messages[clog.WarnLevel] = new(lipgloss.NewStyle().
    Foreground(lipgloss.Color("3"))) // yellow
clog.SetStyles(styles)

Use DefaultMessageStyles() to get the defaults (unstyled for all levels). DefaultValueStyles() returns the default value string styles ("true" → green, "false" → red, "<nil>" / "" → grey).

Documentation

Overview

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

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

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

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

Index

Constants

View Source
const (
	// DefaultEnvLogLevel is the default environment variable checked for the log level.
	DefaultEnvLogLevel = "CLOG_LEVEL"

	// DefaultEnvSeparator is the environment variable checked for the key-value separator.
	DefaultEnvSeparator = "CLOG_SEPARATOR"
)
View Source
const (
	// LevelTrace is the "trace" level string for [SetLevelFromEnv].
	LevelTrace = "trace"
	// LevelDebug is the "debug" level string for [SetLevelFromEnv].
	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"
	// LevelWarning is the "warning" level string (alias for warn).
	LevelWarning = "warning"
	// LevelError is the "error" level string.
	LevelError = "error"
	// LevelFatal is the "fatal" level string.
	LevelFatal = "fatal"
)
View Source
const ErrorKey = "error"

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

Variables

View Source
var Default = New(os.Stdout)

Default is the default logger instance.

View Source
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 should be disabled. This is true when NO_COLOR is set, ConfigureColorOutput("never") was called, or stdout is not a terminal — unless colours were forced via ConfigureColorOutput("always").

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 CLOG_LEVEL environment variable — it won't reset the level if CLOG_LEVEL was set and cfg.Verbose is false.

func ConfigureColorOutput

func ConfigureColorOutput(mode string)

ConfigureColorOutput sets the colour output mode.

  • "auto" — detect terminal capabilities (default behaviour).
  • "always" — force colours even when output is not a TTY (overrides NO_COLOR).
  • "never" — disable all colours and hyperlinks.

Call this early in your application, before creating custom Styles.

func ConfigureVerbose

func ConfigureVerbose(verbose bool)

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

func DefaultMessageStyles

func DefaultMessageStyles() map[Level]*lipgloss.Style

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

func DefaultValueStyles

func DefaultValueStyles() map[string]*lipgloss.Style

DefaultValueStyles returns sensible default styles for common value strings.

func Hyperlink(url, text string) string

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

func IsTerminal

func IsTerminal() bool

IsTerminal returns true if stdout 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(path string, lineNumber int) string

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

func SetColorMode

func SetColorMode(mode ColorMode)

func SetExitFunc

func SetExitFunc(fn func(int))

func SetHandler

func SetHandler(h Handler)

func SetHyperlinkColumnFormat

func SetHyperlinkColumnFormat(format string)

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

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.

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 lineNumber 0, when the path is not a directory).

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 lineNumber > 0).

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.

Use {path} as placeholder. Examples:

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

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

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)

func SetLevelAlign

func SetLevelAlign(align LevelAlign)

func SetLevelFromEnv

func SetLevelFromEnv(envVar string)

SetLevelFromEnv reads the named environment variable and sets the level on the Default logger. Recognised values: trace, debug, info, dry, warn, warning, error, fatal.

func SetLevelLabels

func SetLevelLabels(labels LevelMap)

func SetOmitEmpty

func SetOmitEmpty(omit bool)

func SetOmitQuotes

func SetOmitQuotes(omit bool)

func SetOmitZero

func SetOmitZero(omit bool)

func SetOutput

func SetOutput(out io.Writer)

func SetParts

func SetParts(order ...Part)

func SetPrefixes

func SetPrefixes(prefixes LevelMap)

func SetQuoteChar

func SetQuoteChar(char rune)

func SetQuoteChars

func SetQuoteChars(openChar, closeChar rune)

func SetQuoteMode

func SetQuoteMode(mode QuoteMode)

func SetReportTimestamp

func SetReportTimestamp(report bool)

func SetSeparatorFromEnv

func SetSeparatorFromEnv(envVar string)

SetSeparatorFromEnv reads the named environment variable and sets the key-value separator on the Default logger's styles.

func SetStyles

func SetStyles(styles *Styles)

func SetTimeFormat

func SetTimeFormat(format string)

func SetTimeLocation

func SetTimeLocation(loc *time.Location)

Types

type ColorMode

type ColorMode int

ColorMode controls how a Logger determines colour and hyperlink output.

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

type Config

type Config struct {
	// Verbose enables debug level logging and timestamps.
	Verbose bool
	// Output is the writer to use (defaults to [os.Stdout]).
	Output io.Writer
	// 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

func (*Context) Any

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

Any adds a field with an arbitrary value.

func (*Context) Anys

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

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

func (*Context) Bool

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

Bool adds a bool field.

func (*Context) Bools

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

Bools adds a bool slice field.

func (*Context) Column

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

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

func (*Context) Dict

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

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

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

func (*Context) Dur

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

Dur adds a time.Duration field.

func (*Context) Err

func (c *Context) Err(err error) *Context

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

func (*Context) Float64

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

Float64 adds a float64 field.

func (*Context) Floats64

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

Floats64 adds a float64 slice field.

func (*Context) Int

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

Int adds an int field.

func (*Context) Ints

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

Ints adds an int slice field.

func (*Context) Line

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

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

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

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

func (*Context) Logger

func (c *Context) Logger() *Logger

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

func (*Context) Path

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

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

func (*Context) Prefix

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

Prefix sets a custom prefix for the sub-logger.

func (*Context) Str

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

Str adds a string field.

func (*Context) Stringer

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

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

func (*Context) Stringers

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

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

func (*Context) Strs

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

Strs adds a string slice field.

func (*Context) Uint64

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

Uint64 adds a uint64 field.

func (*Context) Uints64

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

Uints64 adds a uint64 slice field.

type Entry

type Entry struct {
	Level   Level
	Time    time.Time // Zero value if timestamps are disabled.
	Message string
	Prefix  string
	Fields  []Field
}

Entry represents a completed log entry passed to a Handler.

type Event

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

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

func Debug

func Debug() *Event

func Dict

func Dict() *Event

func Dry

func Dry() *Event

func Error

func Error() *Event

func Fatal

func Fatal() *Event

func Info

func Info() *Event

func Trace

func Trace() *Event

func Warn

func Warn() *Event

func (*Event) Any

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

Any adds a field with an arbitrary value.

func (*Event) Anys

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

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

func (*Event) Bool

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

Bool adds a bool field.

func (*Event) Bools

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

Bools adds a bool slice field.

func (*Event) Column

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

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

func (*Event) Dict

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

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

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

func (*Event) Dur

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

Dur adds a time.Duration field.

func (*Event) Err

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

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

func (*Event) Float64

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

Float64 adds a float64 field.

func (*Event) Floats64

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

Floats64 adds a float64 slice field.

func (*Event) Int

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

Int adds an int field.

func (*Event) Ints

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

Ints adds an int slice field.

func (*Event) Line

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

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

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

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

func (*Event) Msg

func (e *Event) Msg(msg string)

Msg finalises the event and writes the log entry. For FatalLevel events, Msg calls os.Exit(1) after writing.

func (*Event) Msgf

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

Msgf finalises the event with a formatted message.

func (*Event) Path

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

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

func (*Event) Prefix

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

Prefix overrides the default emoji prefix for this entry.

func (*Event) Send

func (e *Event) Send()

Send finalises the event with an empty message.

func (*Event) Str

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

Str adds a string field.

func (*Event) Stringer

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

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

func (*Event) Stringers

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

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

func (*Event) Strs

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

Strs adds a string slice field.

func (*Event) Uint64

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

Uint64 adds a uint64 field.

func (*Event) Uints64

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

Uints64 adds a uint64 slice field.

type Field

type Field struct {
	Key   string
	Value any
}

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

type Handler

type Handler interface {
	Log(Entry)
}

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

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

type HandlerFunc

type HandlerFunc func(Entry)

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

func (HandlerFunc) Log

func (f HandlerFunc) Log(e Entry)

Log calls f(e).

type Level

type Level int

Level represents a log level.

const (
	TraceLevel Level = iota
	DebugLevel
	InfoLevel
	DryLevel
	WarnLevel
	ErrorLevel
	FatalLevel
)

func GetLevel

func GetLevel() Level

GetLevel returns the current log level of the Default logger.

func (Level) String

func (l Level) String() string

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

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

type LevelMap map[Level]string

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

func DefaultLabels

func DefaultLabels() LevelMap

DefaultLabels returns a copy of the default level labels.

func DefaultPrefixes

func DefaultPrefixes() LevelMap

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

type Logger

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

Logger is the main structured logger.

func New

func New(out io.Writer) *Logger

New creates a new Logger that writes to out.

func (*Logger) Debug

func (l *Logger) Debug() *Event

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

func (*Logger) Dry

func (l *Logger) Dry() *Event

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

func (*Logger) Error

func (l *Logger) Error() *Event

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

func (*Logger) Fatal

func (l *Logger) Fatal() *Event

Fatal returns a new Event at fatal level.

func (*Logger) Info

func (l *Logger) Info() *Event

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

func (*Logger) SetColorMode

func (l *Logger) SetColorMode(mode ColorMode)

SetColorMode sets the colour mode for this logger. ColorAuto (default) uses global detection; ColorAlways forces colours and hyperlinks; ColorNever disables them.

func (*Logger) SetExitFunc

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

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

func (*Logger) SetHandler

func (l *Logger) SetHandler(h Handler)

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

func (*Logger) SetLabels

func (l *Logger) SetLabels(labels LevelMap)

SetLabels 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) SetLevel

func (l *Logger) SetLevel(level Level)

SetLevel sets the minimum log level.

func (*Logger) SetLevelAlign

func (l *Logger) SetLevelAlign(align LevelAlign)

SetLevelAlign sets the alignment mode for level labels.

func (*Logger) SetOmitEmpty

func (l *Logger) SetOmitEmpty(omit bool)

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

func (*Logger) SetOmitQuotes deprecated

func (l *Logger) SetOmitQuotes(omit bool)

SetOmitQuotes disables quoting of field values that contain spaces or special characters. By default, such values are wrapped in quotes for parseable output.

Deprecated: Use Logger.SetQuoteMode with QuoteNever or QuoteAuto instead.

func (*Logger) SetOmitZero

func (l *Logger) SetOmitZero(omit bool)

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

func (*Logger) SetOutput

func (l *Logger) SetOutput(out io.Writer)

SetOutput sets the output writer.

func (*Logger) SetParts

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

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

func (*Logger) SetPrefixes

func (l *Logger) SetPrefixes(prefixes LevelMap)

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

func (*Logger) SetQuoteChar

func (l *Logger) SetQuoteChar(char rune)

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

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

func (*Logger) SetQuoteChars

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

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

func (*Logger) SetQuoteMode

func (l *Logger) SetQuoteMode(mode QuoteMode)

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

func (*Logger) SetReportTimestamp

func (l *Logger) SetReportTimestamp(report bool)

SetReportTimestamp enables or disables timestamp reporting.

func (*Logger) SetStyles

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

SetStyles sets the display styles.

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(format string)

SetTimeFormat sets the timestamp format string.

func (*Logger) SetTimeLocation

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

SetTimeLocation sets the timezone for timestamps. Defaults to time.Local.

func (*Logger) Trace

func (l *Logger) Trace() *Event

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

func (*Logger) Warn

func (l *Logger) Warn() *Event

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

func (*Logger) With

func (l *Logger) With() *Context

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

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

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 SpinnerBuilder.Progress. The ProgressUpdate allows updating the spinner's title and fields.

type ProgressUpdate

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

ProgressUpdate is a fluent builder for updating a spinner'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) Any

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

Any adds a field with an arbitrary value.

func (*ProgressUpdate) Anys

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

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

func (*ProgressUpdate) Bool

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

Bool adds a bool field.

func (*ProgressUpdate) Bools

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

Bools adds a bool slice field.

func (*ProgressUpdate) Dur

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

Dur adds a time.Duration field.

func (*ProgressUpdate) Float64

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

Float64 adds a float64 field.

func (*ProgressUpdate) Floats64

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

Floats64 adds a float64 slice field.

func (*ProgressUpdate) Int

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

Int adds an int field.

func (*ProgressUpdate) Ints

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

Ints adds an int slice field.

func (*ProgressUpdate) Send

func (u *ProgressUpdate) Send()

Send applies the accumulated title and field changes to the spinner atomically.

func (*ProgressUpdate) Str

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

Str adds a string field.

func (*ProgressUpdate) Strs

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

Strs adds a string slice field.

func (*ProgressUpdate) Title

func (u *ProgressUpdate) Title(title string) *ProgressUpdate

Title sets the spinner's displayed title.

func (*ProgressUpdate) Uint64

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

Uint64 adds a uint64 field.

func (*ProgressUpdate) Uints64

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

Uints64 adds a uint64 slice field.

type QuoteMode

type QuoteMode int

QuoteMode controls how field values are quoted in log output.

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

type SpinnerBuilder

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

SpinnerBuilder configures a spinner before execution.

func Spinner

func Spinner(title string) *SpinnerBuilder

Spinner creates a new SpinnerBuilder with the given title.

func (*SpinnerBuilder) Any

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

Any adds a field with an arbitrary value.

func (*SpinnerBuilder) Anys

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

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

func (*SpinnerBuilder) Bool

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

Bool adds a bool field.

func (*SpinnerBuilder) Bools

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

Bools adds a bool slice field.

func (*SpinnerBuilder) Column

func (b *SpinnerBuilder) Column(key, path string, lineNumber, column int) *SpinnerBuilder

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

func (*SpinnerBuilder) Dur

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

Dur adds a time.Duration field.

func (*SpinnerBuilder) Float64

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

Float64 adds a float64 field.

func (*SpinnerBuilder) Floats64

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

Floats64 adds a float64 slice field.

func (*SpinnerBuilder) Int

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

Int adds an int field.

func (*SpinnerBuilder) Ints

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

Ints adds an int slice field.

func (*SpinnerBuilder) Line

func (b *SpinnerBuilder) Line(key, path string, lineNumber int) *SpinnerBuilder

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

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

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

func (*SpinnerBuilder) Path

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

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

func (*SpinnerBuilder) Progress

func (b *SpinnerBuilder) Progress(
	ctx context.Context,
	task ProgressTask,
) *WaitResult

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

func (*SpinnerBuilder) Str

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

Str adds a string field.

func (*SpinnerBuilder) Strs

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

Strs adds a string slice field.

func (*SpinnerBuilder) Type

Type sets the spinner animation type.

func (*SpinnerBuilder) Uint64

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

Uint64 adds a uint64 field.

func (*SpinnerBuilder) Uints64

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

Uints64 adds a uint64 slice field.

func (*SpinnerBuilder) Wait

func (b *SpinnerBuilder) Wait(ctx context.Context, task Task) *WaitResult

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

type Styles

type Styles struct {
	Levels        map[Level]*lipgloss.Style
	Messages      map[Level]*lipgloss.Style
	Key           *lipgloss.Style
	Separator     *lipgloss.Style
	SeparatorText string // Separator between key and value (default "=").
	Timestamp     *lipgloss.Style
	String        *lipgloss.Style            // Nil = no styling.
	Number        *lipgloss.Style            // Nil = no styling.
	Error         *lipgloss.Style            // Nil = no styling.
	KeyStyles     map[string]*lipgloss.Style // Field key name → value style (e.g. "path" → blue).
	ValueStyles   map[string]*lipgloss.Style // Formatted value → style (e.g. "true" → green).
}

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

func DefaultStyles

func DefaultStyles() *Styles

DefaultStyles returns the default colour styles.

type Task

type Task func(context.Context) error

Task is a function executed by SpinnerBuilder.Wait.

type WaitResult

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

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

func (*WaitResult) Any

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

Any adds a field with an arbitrary value.

func (*WaitResult) Anys

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

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

func (*WaitResult) Bool

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

Bool adds a bool field.

func (*WaitResult) Bools

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

Bools adds a bool slice field.

func (*WaitResult) Debug

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

Debug logs at debug level with the given message on success, or at error level on failure. Returns the error.

func (*WaitResult) Dur

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

Dur adds a time.Duration 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 spinner title.

func (*WaitResult) Float64

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

Float64 adds a float64 field.

func (*WaitResult) Floats64

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

Floats64 adds a float64 slice field.

func (*WaitResult) Int

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

Int adds an int field.

func (*WaitResult) Ints

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

Ints adds an int slice field.

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 spinner title on failure. Returns the error.

func (*WaitResult) Prefix

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

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

func (*WaitResult) Silent

func (w *WaitResult) Silent() error

Silent returns just the error without logging anything.

func (*WaitResult) Str

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

Str adds a string field.

func (*WaitResult) Strs

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

Strs adds a string slice field.

func (*WaitResult) Uint64

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

Uint64 adds a uint64 field.

func (*WaitResult) Uints64

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

Uints64 adds a uint64 slice field.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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