clog

package module
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 25 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 (
  "fmt"

  "github.com/gechr/clog"
)

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

Output:

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

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 (CLOG_LOG_LEVEL is checked automatically on init)
// export CLOG_LOG_LEVEL=debug

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

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
Any Any(key string, val any) Arbitrary value
Anys Anys(key string, vals []any) Arbitrary value slice
Base64 Base64(key string, val []byte) Byte slice as base64 string
Bool Bool(key string, val bool) Boolean field
Bools Bools(key string, vals []bool) Boolean slice field
Bytes Bytes(key string, val []byte) Byte slice as string
Column Column(key, path string, line, column int) Clickable file:line:column hyperlink
Dict Dict(key string, dict *Event) Nested fields with dot-notation keys
Duration Duration(key string, val time.Duration) Duration field
Durations Durations(key string, vals []time.Duration) Duration slice field
Err Err(err error) Attach error; Send uses it as message, Msg/Msgf add "error" field
Float64 Float64(key string, val float64) Float field
Floats64 Floats64(key string, vals []float64) Float slice field
Hex Hex(key string, val []byte) Byte slice as hex string
Int Int(key string, val int) Integer field
Int64 Int64(key string, val int64) 64-bit integer field
Ints Ints(key string, vals []int) Integer slice field
Ints64 Ints64(key string, vals []int64) 64-bit integer slice field
JSON JSON(key string, val any) Marshals val to JSON with syntax highlighting
Line Line(key, path string, line int) Clickable file:line hyperlink
Link Link(key, url, text string) Clickable URL hyperlink
Path Path(key, path string) Clickable file/directory hyperlink
Percent Percent(key string, val float64) Percentage with gradient colour
Quantities Quantities(key string, vals []string) Quantity slice field
Quantity Quantity(key, val string) Quantity field (e.g. "10GB")
RawJSON RawJSON(key string, val []byte) Pre-serialized JSON bytes, emitted verbatim with syntax highlighting
Str Str(key, val string) String field
Stringer Stringer(key string, val fmt.Stringer) Calls String() (nil-safe)
Stringers Stringers(key string, vals []fmt.Stringer) Slice of fmt.Stringer values
Strs Strs(key string, vals []string) String slice field
Time Time(key string, val time.Time) Time field
Uint Uint(key string, val uint) Unsigned integer field
Uint64 Uint64(key string, val uint64) 64-bit unsigned integer field
Uints Uints(key string, vals []uint) Unsigned integer slice field
Uints64 Uints64(key string, vals []uint64) 64-bit unsigned integer slice field
URL URL(key, url string) Clickable URL hyperlink (URL as text)

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
clog.Error().Err(err).Send()              // Log with error as message (no error= field)
clog.Error().Err(err).Msg("failed")       // Log with message + error= field

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
// 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).

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, per-logger, or globally:

// 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")

// Global (changes defaults for all levels)
clog.SetPrefixes(clog.LevelMap{
  clog.InfoLevel:  ">>",
  clog.WarnLevel:  "!!",
  clog.ErrorLevel: "XX",
})

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

Missing levels in SetPrefixes fall back to the defaults. Use DefaultPrefixes() to get a copy of the default prefix map.

Custom Labels

Override the default level labels with SetLevelLabels:

clog.SetLevelLabels(clog.LevelMap{
  clog.InfoLevel:  "INFO",
  clog.WarnLevel:  "WARNING",
  clog.ErrorLevel: "ERROR",
})

Missing levels fall back to the defaults. Use DefaultLabels() to get a copy of the default label map.

Level Alignment

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

// Alignment is visible when labels have different widths (e.g. via SetLevelLabels)
clog.SetLevelAlign(clog.AlignRight)   // default: "   INFO", "WARNING", "  ERROR"
clog.SetLevelAlign(clog.AlignLeft)    //          "INFO   ", "WARNING", "ERROR  "
clog.SetLevelAlign(clog.AlignCenter)  //          " INFO  ", "WARNING", " ERROR "
clog.SetLevelAlign(clog.AlignNone)    //          "INFO",    "WARNING", "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. This is the DefaultSpinner type, which is used when no custom Type is set.

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 error string
.Err() Logs at INF with spinner title as msg Logs at ERR with error string as msg
.Send() Logs at configured level Logs at configured level
.Silent() Returns error, no logging Returns error, no logging

.Err() is equivalent to calling .Send() with default settings (no OnSuccess/OnError overrides).

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

Custom Success/Error Behaviour

Use OnSuccessLevel, OnSuccessMessage, OnErrorLevel, and OnErrorMessage to customise how the result is logged, then call .Send():

// Fatal on error instead of the default error level
err := clog.Spinner("Connecting to database").
  Str("host", "db.internal").
  Wait(ctx, connectToDB).
  OnErrorLevel(clog.FatalLevel).
  Send()

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")

Available types from github.com/charmbracelet/bubbles/spinner: Line, Dot, MiniDot, Jump, Pulse, Globe, Points, Meter, Hamburger, Moon, Ellipsis.

The AnimationBuilder supports the same clickable hyperlink field methods as events:

clog.Spinner("Building").
  Path("dir", "src/").
  Line("config", "config.yaml", 42).
  Column("loc", "main.go", 10, 5).
  URL("docs", "https://example.com").
  Link("help", "https://example.com", "docs").
  Wait(ctx, action).
  Msg("Built")
Method Signature Description
Path Path(key, path string) Clickable file/directory hyperlink
Line Line(key, path string, line int) Clickable file:line hyperlink
Column Column(key, path string, line, column int) Clickable file:line:column hyperlink
URL URL(key, url string) Clickable URL hyperlink (URL as text)
Link Link(key, url, text string) Clickable URL hyperlink

Pulse Animation

Pulse creates an independent animation where all characters in the title fade uniformly between gradient colours.

// Default gradient (blue-gray to cyan)
clog.Pulse("Warming up").
  Wait(ctx, action).
  Msg("Ready")

// Custom gradient
clog.Pulse("Replicating",
  clog.ColorStop{Position: 0, Color: colorful.Color{R: 1, G: 0.2, B: 0.2}},
  clog.ColorStop{Position: 0.5, Color: colorful.Color{R: 1, G: 1, B: 0.3}},
  clog.ColorStop{Position: 1, Color: colorful.Color{R: 1, G: 0.2, B: 0.2}},
).
  Wait(ctx, action).
  Msg("Replicated")

Use DefaultPulseGradient() to get the default gradient stops.

Shimmer Animation

Shimmer creates an independent animation where each character is coloured based on its position in a sweeping gradient wave.

// Default gradient
clog.Shimmer("Indexing documents").
  Wait(ctx, action).
  Msg("Indexed")

// Custom gradient with direction
clog.Shimmer("Synchronizing",
  clog.ColorStop{Position: 0, Color: colorful.Color{R: 0.3, G: 0.3, B: 0.8}},
  clog.ColorStop{Position: 0.5, Color: colorful.Color{R: 1, G: 1, B: 1}},
  clog.ColorStop{Position: 1, Color: colorful.Color{R: 0.3, G: 0.3, B: 0.8}},
).
  ShimmerDirection(clog.DirectionMiddleIn).
  Wait(ctx, action).
  Msg("Synchronized")

Use DefaultShimmerGradient() to get the default gradient stops.

Shimmer Directions
Constant Description
DirectionRight Left to right (default)
DirectionLeft Right to left
DirectionMiddleIn Inward from both edges
DirectionMiddleOut Outward from the center

Both pulse and shimmer use ColorStop for gradient definitions:

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

All three animations gracefully degrade: when colours are disabled (CI, piped output), a static status line with an ⏳ prefix is printed instead.

The icon displayed during Pulse and Shimmer animations defaults to ⏳ and can be changed with .Prefix() on the builder:

clog.Pulse("Warming up").
  Prefix("🔄").
  Wait(ctx, action).
  Msg("Ready")

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().URL("docs", "https://example.com/docs").Msg("See docs")
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 DirFormat -> PathFormat -> file://{path}
File (no line) FileFormat -> PathFormat -> file://{path}
File + line LineFormat -> file://{path}
File + column ColumnFormat -> LineFormat -> file://{path}

These can also be set via environment variables:

export CLOG_HYPERLINK_FORMAT="vscode"                      # named preset (sets all slots)
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}"

CLOG_HYPERLINK_FORMAT accepts a preset name and configures all slots at once. Individual format vars override the preset for their specific slot.

Named Presets

Use SetHyperlinkPreset or CLOG_HYPERLINK_FORMAT to configure all hyperlink format slots at once:

clog.SetHyperlinkPreset("vscode")
export CLOG_HYPERLINK_FORMAT=vscode
Preset Scheme
cursor cursor://
kitty file:// with #line
macvim mvim://
subl subl://
textmate txmt://
vscode vscode://
vscode-insiders vscode-insiders://
vscodium vscodium://

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:  clog.Stderr(clog.ColorAuto),     // custom output
  Styles:  customStyles,                    // custom visual styles
})

// Toggle verbose mode
clog.SetVerbose(true)

Output

Each Logger writes to an *Output, which bundles an io.Writer with its terminal capabilities (TTY detection, width, color profile):

// Standard constructors
out := clog.Stdout(clog.ColorAuto)                  // os.Stdout with auto-detection
out := clog.Stderr(clog.ColorAlways)                // os.Stderr with forced colours
out := clog.NewOutput(w, clog.ColorNever)           // arbitrary writer, colours disabled
out := clog.TestOutput(&buf)                        // shorthand for NewOutput(w, ColorNever)

Output methods:

Method Description
Writer() Returns the underlying io.Writer
IsTTY() True if the writer is connected to a terminal
ColorsDisabled() True if colours are suppressed for this output
Width() Terminal width (0 for non-TTY, lazily cached)
RefreshWidth() Re-detect terminal width on next Width() call
Renderer() Returns the lipgloss renderer

Custom Logger

logger := clog.New(clog.Stderr(clog.ColorAuto))
logger.SetLevel(clog.DebugLevel)
logger.SetReportTimestamp(true)
logger.SetTimeFormat("15:04:05.000")
logger.SetFieldTimeFormat(time.Kitchen)    // format for .Time() fields (default: time.RFC3339)
logger.SetTimeLocation(time.UTC)           // timezone for timestamps (default: time.Local)
logger.SetFieldStyleLevel(clog.TraceLevel) // min level for field value styling (default: InfoLevel)
logger.SetHandler(myHandler)

For simple cases where you just need a writer with default color detection:

logger := clog.NewWriter(os.Stderr) // equivalent to New(NewOutput(os.Stderr, ColorAuto))

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 Default output is a terminal
clog.ColorsDisabled()            // true if colours are disabled on the Default logger
clog.SetOutput(out)              // change the output (accepts *Output)
clog.SetOutputWriter(w)          // change the output writer (with ColorAuto)
clog.SetExitFunc(fn)             // override os.Exit for Fatal (useful in tests)
clog.SetHyperlinksEnabled(false) // disable all hyperlink rendering
logger.Output()                  // returns the Logger's *Output

Environment Variables

All env vars follow the pattern {PREFIX}_{SUFFIX}. The default prefix is CLOG.

Suffix Default env var
LOG_LEVEL CLOG_LOG_LEVEL
HYPERLINK_FORMAT CLOG_HYPERLINK_FORMAT
HYPERLINK_PATH_FORMAT CLOG_HYPERLINK_PATH_FORMAT
HYPERLINK_FILE_FORMAT CLOG_HYPERLINK_FILE_FORMAT
HYPERLINK_DIR_FORMAT CLOG_HYPERLINK_DIR_FORMAT
HYPERLINK_LINE_FORMAT CLOG_HYPERLINK_LINE_FORMAT
HYPERLINK_COLUMN_FORMAT CLOG_HYPERLINK_COLUMN_FORMAT

CLOG_LOG_LEVEL is checked automatically at init.

CLOG_LOG_LEVEL=debug ./some-app  # enables debug logging + timestamps
CLOG_LOG_LEVEL=warn ./some-app   # suppresses info messages

Custom Env Prefix

Use SetEnvPrefix to whitelabel the env var names for your application. The custom prefix is checked first, with CLOG_ as a fallback.

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

This means CLOG_LOG_LEVEL=debug always works as a universal escape hatch, even when the application uses a custom prefix.

NO_COLOR is never prefixed — it follows the no-color.org standard independently.

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.

Colour Control

Colour behaviour is set per-Output via ColorMode:

// Package-level (recreates Default logger's Output)
clog.SetColorMode(clog.ColorAlways) // force colours (overrides NO_COLOR)
clog.SetColorMode(clog.ColorNever)  // disable all colours and hyperlinks
clog.SetColorMode(clog.ColorAuto)   // detect terminal capabilities (default)

// Per-logger via Output
logger := clog.New(clog.NewOutput(os.Stdout, clog.ColorAlways))

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

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

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

JSON / RawJSON

JSON marshals any Go value to JSON; RawJSON accepts pre-serialized bytes. Both emit the result with syntax highlighting.

// Marshal a Go value
clog.Info().JSON("user", userStruct).Msg("ok")
clog.Info().JSON("config", map[string]any{"port": 8080, "debug": true}).Msg("started")

// Pre-serialized bytes (no marshal overhead)
clog.Error().
  Str("batch", "1/1").
  RawJSON("error", []byte(`{"status":"unprocessable_entity","detail":"validation failed","code":null}`)).
  Msg("Batch failed")
// ERR ❌ Batch failed batch=1/1 error={"status":"unprocessable_entity","detail":"validation failed","code":null}

Use JSON when you have a Go value to log; use RawJSON when you already have bytes (HTTP response bodies, json.RawMessage, database JSON columns) to avoid an unnecessary marshal/unmarshal round-trip. JSON logs the error string as the field value if marshalling fails.

Pretty-printed JSON is automatically flattened to a single line. Highlighting uses a Dracula-inspired colour scheme by default (space after commas included). Disable or customise it via FieldJSON in Styles:

// Disable highlighting
styles := clog.DefaultStyles()
styles.FieldJSON = nil
clog.SetStyles(styles)

// Custom colours
custom := clog.DefaultJSONStyles()
custom.Key = new(lipgloss.NewStyle().Foreground(lipgloss.Color("#50fa7b")))
styles.FieldJSON = custom
clog.SetStyles(styles)

Number is the base fallback for all numeric tokens. Five sub-styles allow finer control and fall back to Number when nil:

Field Applies to
NumberPositive Positive numbers (with or without explicit +)
NumberNegative Negative numbers
NumberZero Zero (falls back to NumberPositive, then Number)
NumberFloat Floating-point values
NumberInteger Integer values
custom := clog.DefaultJSONStyles()
custom.NumberNegative = new(lipgloss.NewStyle().Foreground(lipgloss.Color("1"))) // red
custom.NumberZero = new(lipgloss.NewStyle().Foreground(lipgloss.Color("8")))     // grey
styles.FieldJSON = custom
clog.SetStyles(styles)

Rendering Modes

Set JSONStyles.Mode to control how JSON structure is rendered:

Mode Description Example
JSONModeJSON Standard JSON (default) {"status":"ok","count":42}
JSONModeHuman Unquote keys and simple string values {status:ok, count:42}
JSONModeFlat Flatten nested object keys with dot notation; arrays kept intact {status:ok, meta.region:us-east-1}

JSONModeHuman — keys are unquoted unless they contain ,{}[]\s:#"' or start with ////*. String values are unquoted unless they start with a forbidden character, end with whitespace, are ambiguous as a JSON keyword (true, false, null), or look like a number. Empty strings always render as "".

styles.FieldJSON = clog.DefaultJSONStyles()
styles.FieldJSON.Mode = clog.JSONModeHuman

clog.Info().
  RawJSON("response", []byte(`{"status":"ok","count":42,"active":true,"deleted_at":null}`)).
  Msg("Fetched")
// INF ℹ️ Fetched response={status:ok, count:42, active:true, deleted_at:null}

JSONModeFlat — nested objects are recursed into and their keys joined with .; arrays are kept intact as values:

styles.FieldJSON.Mode = clog.JSONModeFlat

clog.Info().
  RawJSON("resp", []byte(`{"user":{"name":"alice","role":"admin"},"tags":["a","b"]}`)).
  Msg("Auth")
// INF ℹ️ Auth resp={user.name:alice, user.role:admin, tags:[a, b]}

Spacing

JSONStyles.Spacing is a bitmask controlling where spaces are inserted. The default (DefaultJSONStyles) adds a space after commas.

Flag Effect Example
JSONSpacingAfterColon Space after : {"key": "value"}
JSONSpacingAfterComma Space after , {"a":1, "b":2}
JSONSpacingBeforeObject Space before a nested { {"key": {"n":1}}
JSONSpacingBeforeArray Space before a nested [ {"tags": ["a","b"]}
JSONSpacingAll All of the above {"key": {"n": 1}, "tags": ["a"]}
// Fluent builder
styles.FieldJSON = clog.DefaultJSONStyles().WithSpacing(clog.JSONSpacingAll)

// Direct assignment
styles.FieldJSON.Spacing = clog.JSONSpacingAfterComma | clog.JSONSpacingBeforeObject

JSONSpacingAfterColon and JSONSpacingBeforeObject/JSONSpacingBeforeArray are independent — combining them produces two spaces before a nested value.

Omitting Commas

Set OmitCommas: true to drop the , separator. Combine with JSONSpacingAfterComma to keep a space in its place:

styles.FieldJSON.OmitCommas = true
styles.FieldJSON.Spacing |= clog.JSONSpacingAfterComma

clog.Info().
  RawJSON("r", []byte(`{"a":1,"b":2,"c":true}`)).
  Msg("ok")
// INF ℹ️ ok r={a:1 b:2 c:true}

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.KeyDefault = new(
  lipgloss.NewStyle().Bold(true).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 a typed key (bool true != string "true")
  3. Type styles - style values by their Go type
styles := clog.DefaultStyles()

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

// 2. Value styles: typed key matches (bool `true` != string "true")
styles.Values["PASS"] = new(
  lipgloss.NewStyle().
  Foreground(lipgloss.Color("2")), // green
)

styles.Values["FAIL"] = new(lipgloss.NewStyle().
  Foreground(lipgloss.Color("1")), // red
)

// 3. Type styles: string values -> white, numeric values -> magenta, errors -> red by default
styles.FieldString = new(lipgloss.NewStyle().Foreground(lipgloss.Color("15")))
styles.FieldNumber = new(lipgloss.NewStyle().Foreground(lipgloss.Color("5")))
styles.FieldError  = new(lipgloss.NewStyle().Foreground(lipgloss.Color("1")))
styles.FieldString = nil  // set to nil to disable
styles.FieldNumber = nil  // set to nil to disable

clog.SetStyles(styles)

Styles Reference

Field Type Alias Default
DurationThresholds map[string][]Threshold ThresholdMap {}
DurationUnits map[string]Style StyleMap {}
FieldDurationNumber Style magenta
FieldDurationUnit Style magenta faint
FieldError Style red
FieldJSON *JSONStyles DefaultJSONStyles()
FieldNumber Style magenta
FieldPercent Style nil
FieldQuantityNumber Style magenta
FieldQuantityUnit Style magenta faint
FieldString Style white
FieldTime Style magenta
KeyDefault Style blue
Keys map[string]Style StyleMap {}
Levels map[Level]Style LevelStyleMap per-level bold colours
Messages map[Level]Style LevelStyleMap DefaultMessageStyles()
PercentGradient []ColorStop red → yellow → green
PercentPrecision int 0
QuantityThresholds map[string][]Threshold ThresholdMap {}
QuantityUnits map[string]Style StyleMap {}
QuantityUnitsIgnoreCase bool true
Separator Style faint
SeparatorText string "="
Timestamp Style faint
Values map[any]Style ValueStyleMap DefaultValueStyles()
Field Description
DurationThresholds Duration unit -> magnitude-based style thresholds
DurationUnits Duration unit string -> style override
FieldDurationNumber Style for numeric segments of duration values (e.g. "1" in "1m30s"), nil to disable
FieldDurationUnit Style for unit segments of duration values (e.g. "m" in "1m30s"), nil to disable
FieldError Style for error field values, nil to disable
FieldJSON Per-token styles for JSON syntax highlighting; nil disables highlighting
FieldNumber Style for int/float field values, nil to disable
FieldPercent Base style for Percent fields (foreground overridden by gradient), nil to disable
FieldQuantityNumber Style for numeric part of quantity values (e.g. "5" in "5km"), nil to disable
FieldQuantityUnit Style for unit part of quantity values (e.g. "km" in "5km"), nil to disable
FieldString Style for string field values, nil to disable
FieldTime Style for time.Time field values, nil to disable
KeyDefault Style for field key names without a per-key override, nil to disable
Keys Field key name -> value style override
Levels Per-level label style (e.g. "INF", "ERR"), nil to disable
Messages Per-level message text style, nil to disable
PercentGradient Gradient colour stops for Percent fields
PercentPrecision Decimal places for Percent display (0 = "75%", 1 = "75.0%")
QuantityThresholds Quantity unit -> magnitude-based style thresholds
QuantityUnits Quantity unit string -> style override
QuantityUnitsIgnoreCase Whether quantity unit matching is case-insensitive
Separator Style for the separator between key and value
SeparatorText Key/value separator string
Timestamp Style for the timestamp prefix, nil to disable
Values Typed value -> style (uses Go equality, so bool true != string "true")

Each Threshold pairs a minimum value with style overrides:

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

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

Thresholds are evaluated in descending order — the first match wins:

styles.QuantityThresholds["ms"] = clog.Thresholds{
  {Value: 5000, Style: clog.ThresholdStyle{Number: redStyle, Unit: redStyle}},
  {Value: 1000, Style: clog.ThresholdStyle{Number: yellowStyle, Unit: yellowStyle}},
}

Value styles only apply at Info level and above by default. Use SetFieldStyleLevel to change the threshold.

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

Use DefaultValueStyles() to get the default value styles (true=green, false=red, nil=grey, ""=grey).

Use DefaultPercentGradient() to get the default red → yellow → green gradient stops used for Percent fields.

Documentation

Overview

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

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

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

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

Index

Constants

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

DefaultEnvPrefix is the default environment variable prefix.

View Source
const ErrorKey = "error"

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

View Source
const Nil = "<nil>"

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

Variables

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

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 are disabled on the Default logger.

func Configure

func Configure(cfg *Config)

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

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

func Hyperlink(url, text string) string

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

func IsTerminal

func IsTerminal() bool

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

func IsVerbose

func IsVerbose() bool

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

func PathLink(path string, line int) string

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

func SetColorMode

func SetColorMode(mode ColorMode)

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

func SetEnvPrefix added in v0.3.0

func SetEnvPrefix(prefix string)

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

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

func SetExitFunc

func SetExitFunc(fn func(int))

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

func SetFieldStyleLevel added in v0.1.2

func SetFieldStyleLevel(level Level)

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

func SetFieldTimeFormat added in v0.1.1

func SetFieldTimeFormat(format string)

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

func SetHandler

func SetHandler(h Handler)

SetHandler sets the log handler on the Default logger.

func SetHyperlinkColumnFormat

func SetHyperlinkColumnFormat(format string)

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

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

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

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

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

func SetHyperlinkDirFormat

func SetHyperlinkDirFormat(format string)

SetHyperlinkDirFormat configures the URL format for directory hyperlinks.

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

Falls back to SetHyperlinkPathFormat if not set.

Use {path} as placeholder.

func SetHyperlinkFileFormat

func SetHyperlinkFileFormat(format string)

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

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

Falls back to SetHyperlinkPathFormat if not set.

Use {path} as placeholder.

func SetHyperlinkLineFormat

func SetHyperlinkLineFormat(format string)

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

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

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

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

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

func SetHyperlinkPathFormat

func SetHyperlinkPathFormat(format string)

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

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

Use {path} as placeholder. Examples:

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

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

func SetHyperlinkPreset added in v0.4.5

func SetHyperlinkPreset(name string) error

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

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

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

func SetHyperlinksEnabled

func SetHyperlinksEnabled(enabled bool)

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

func SetLevel

func SetLevel(level Level)

SetLevel sets the minimum log level on the Default logger.

func SetLevelAlign

func SetLevelAlign(align LevelAlign)

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

func SetLevelLabels

func SetLevelLabels(labels LevelMap)

SetLevelLabels sets the level labels on the Default logger.

func SetOmitEmpty

func SetOmitEmpty(omit bool)

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

func SetOmitZero

func SetOmitZero(omit bool)

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

func SetOutput

func SetOutput(out *Output)

SetOutput sets the output on the Default logger.

func SetOutputWriter added in v0.3.1

func SetOutputWriter(w io.Writer)

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

func SetParts

func SetParts(order ...Part)

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

func SetPrefixes

func SetPrefixes(prefixes LevelMap)

SetPrefixes sets the level prefixes on the Default logger.

func SetQuoteChar

func SetQuoteChar(char rune)

SetQuoteChar sets the quote character on the Default logger.

func SetQuoteChars

func SetQuoteChars(openChar, closeChar rune)

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

func SetQuoteMode

func SetQuoteMode(mode QuoteMode)

SetQuoteMode sets the quoting behaviour on the Default logger.

func SetReportTimestamp

func SetReportTimestamp(report bool)

SetReportTimestamp enables or disables timestamps on the Default logger.

func SetStyles

func SetStyles(styles *Styles)

SetStyles sets the display styles on the Default logger.

func SetTimeFormat

func SetTimeFormat(format string)

SetTimeFormat sets the timestamp format on the Default logger.

func SetTimeLocation

func SetTimeLocation(loc *time.Location)

SetTimeLocation sets the timestamp timezone on the Default logger.

func SetVerbose added in v0.3.0

func SetVerbose(verbose bool)

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

Types

type AnimationBuilder added in v0.4.2

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

AnimationBuilder configures an animation before execution. Create one with Spinner, Pulse, or Shimmer.

func Pulse added in v0.4.2

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

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

func Shimmer added in v0.4.2

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

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

func Spinner

func Spinner(title string) *AnimationBuilder

Spinner creates a new AnimationBuilder with a rotating spinner animation.

func (*AnimationBuilder) Any added in v0.4.2

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

Any adds a field with an arbitrary value.

func (*AnimationBuilder) Anys added in v0.4.2

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

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

func (*AnimationBuilder) Base64 added in v0.4.8

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

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

func (*AnimationBuilder) Bool added in v0.4.2

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

Bool adds a bool field.

func (*AnimationBuilder) Bools added in v0.4.2

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

Bools adds a bool slice field.

func (*AnimationBuilder) Bytes added in v0.4.7

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

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

func (*AnimationBuilder) Column added in v0.4.2

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

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

func (*AnimationBuilder) Duration added in v0.4.2

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

Duration adds a time.Duration field.

func (*AnimationBuilder) Durations added in v0.4.2

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

Durations adds a time.Duration slice field.

func (*AnimationBuilder) Err added in v0.4.4

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

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

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

func (*AnimationBuilder) Float64 added in v0.4.2

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

Float64 adds a float64 field.

func (*AnimationBuilder) Floats64 added in v0.4.2

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

Floats64 adds a float64 slice field.

func (*AnimationBuilder) Hex added in v0.4.8

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

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

func (*AnimationBuilder) Int added in v0.4.2

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

Int adds an int field.

func (*AnimationBuilder) Int64 added in v0.4.2

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

Int64 adds an int64 field.

func (*AnimationBuilder) Ints added in v0.4.2

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

Ints adds an int slice field.

func (*AnimationBuilder) Ints64 added in v0.4.4

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

Ints64 adds an int64 slice field.

func (*AnimationBuilder) JSON added in v0.4.4

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

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

func (*AnimationBuilder) Line added in v0.4.2

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

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

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

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

func (*AnimationBuilder) Path added in v0.4.2

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

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

func (*AnimationBuilder) Percent added in v0.4.2

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

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

func (*AnimationBuilder) Prefix added in v0.4.2

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

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

func (*AnimationBuilder) Progress added in v0.4.2

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

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

func (*AnimationBuilder) Quantities added in v0.4.2

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

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

func (*AnimationBuilder) Quantity added in v0.4.2

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

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

func (*AnimationBuilder) RawJSON added in v0.4.4

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

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

func (*AnimationBuilder) ShimmerDirection added in v0.4.2

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

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

func (*AnimationBuilder) Str added in v0.4.2

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

Str adds a string field.

func (*AnimationBuilder) Stringer added in v0.4.4

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

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

func (*AnimationBuilder) Stringers added in v0.4.4

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

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

func (*AnimationBuilder) Strs added in v0.4.2

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

Strs adds a string slice field.

func (*AnimationBuilder) Time added in v0.4.2

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

Time adds a time.Time field.

func (*AnimationBuilder) Type added in v0.4.2

Type sets the spinner animation type. Only meaningful when the builder was created with Spinner.

func (*AnimationBuilder) URL added in v0.4.2

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

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

func (*AnimationBuilder) Uint added in v0.4.2

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

Uint adds a uint field.

func (*AnimationBuilder) Uint64 added in v0.4.2

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

Uint64 adds a uint64 field.

func (*AnimationBuilder) Uints added in v0.4.4

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

Uints adds a uint slice field.

func (*AnimationBuilder) Uints64 added in v0.4.2

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

Uints64 adds a uint64 slice field.

func (*AnimationBuilder) Wait added in v0.4.2

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

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

type ColorMode

type ColorMode int

ColorMode controls how a Logger determines colour and hyperlink output.

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

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

func (ColorMode) MarshalText added in v0.3.0

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

MarshalText implements encoding.TextMarshaler.

func (ColorMode) String added in v0.3.0

func (i ColorMode) String() string

func (*ColorMode) UnmarshalText added in v0.3.0

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

UnmarshalText implements encoding.TextUnmarshaler.

type ColorStop added in v0.3.0

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

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

func DefaultPercentGradient added in v0.3.0

func DefaultPercentGradient() []ColorStop

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

func DefaultPulseGradient added in v0.4.0

func DefaultPulseGradient() []ColorStop

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

func DefaultShimmerGradient added in v0.4.0

func DefaultShimmerGradient() []ColorStop

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

type Config

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

Config holds configuration options for the Default logger.

type Context

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

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

func With

func With() *Context

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

func (*Context) Any

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

Any adds a field with an arbitrary value.

func (*Context) Anys

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

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

func (*Context) Base64 added in v0.4.8

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

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

func (*Context) Bool

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

Bool adds a bool field.

func (*Context) Bools

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

Bools adds a bool slice field.

func (*Context) Bytes added in v0.4.7

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

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

func (*Context) Column

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

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

func (*Context) Dict

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

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

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

func (*Context) Duration added in v0.2.2

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

Duration adds a time.Duration field.

func (*Context) Durations added in v0.2.2

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

Durations adds a time.Duration slice field.

func (*Context) Err

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

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

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

func (*Context) Float64

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

Float64 adds a float64 field.

func (*Context) Floats64

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

Floats64 adds a float64 slice field.

func (*Context) Hex added in v0.4.8

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

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

func (*Context) Int

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

Int adds an int field.

func (*Context) Int64 added in v0.4.1

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

Int64 adds an int64 field.

func (*Context) Ints

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

Ints adds an int slice field.

func (*Context) Ints64 added in v0.4.4

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

Ints64 adds an int64 slice field.

func (*Context) JSON added in v0.4.4

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

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

func (*Context) Line

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

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

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

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

func (*Context) Logger

func (c *Context) Logger() *Logger

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

func (*Context) Path

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

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

func (*Context) Percent added in v0.3.0

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

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

func (*Context) Prefix

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

Prefix sets a custom prefix for the sub-logger.

func (*Context) Quantities added in v0.2.2

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

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

func (*Context) Quantity added in v0.2.2

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

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

func (*Context) RawJSON added in v0.4.4

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

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

func (*Context) Str

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

Str adds a string field.

func (*Context) Stringer

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

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

func (*Context) Stringers

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

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

func (*Context) Strs

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

Strs adds a string slice field.

func (*Context) Time added in v0.1.1

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

Time adds a time.Time field.

func (*Context) URL added in v0.2.1

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

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

func (*Context) Uint added in v0.4.1

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

Uint adds a uint field.

func (*Context) Uint64

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

Uint64 adds a uint64 field.

func (*Context) Uints added in v0.4.4

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

Uints adds a uint slice field.

func (*Context) Uints64

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

Uints64 adds a uint64 slice field.

type Direction added in v0.4.0

type Direction int

Direction controls which way an animation travels.

const (
	// DirectionRight moves the shimmer wave from left to right (default).
	DirectionRight Direction = iota
	// DirectionLeft moves the shimmer wave from right to left.
	DirectionLeft
	// DirectionMiddleIn sends the shimmer wave inward from both edges.
	DirectionMiddleIn
	// DirectionMiddleOut sends the shimmer wave outward from the center.
	DirectionMiddleOut
)

type Entry

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

Entry represents a completed log entry passed to a Handler.

type Event

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

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

func Debug

func Debug() *Event

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

func Dict

func Dict() *Event

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

func Dry

func Dry() *Event

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

func Error

func Error() *Event

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

func Fatal

func Fatal() *Event

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

func Info

func Info() *Event

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

func Trace

func Trace() *Event

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

func Warn

func Warn() *Event

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

func (*Event) Any

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

Any adds a field with an arbitrary value.

func (*Event) Anys

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

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

func (*Event) Base64 added in v0.4.8

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

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

func (*Event) Bool

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

Bool adds a bool field.

func (*Event) Bools

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

Bools adds a bool slice field.

func (*Event) Bytes added in v0.4.7

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

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

func (*Event) Column

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

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

func (*Event) Dict

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

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

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

func (*Event) Duration added in v0.2.2

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

Duration adds a time.Duration field.

func (*Event) Durations added in v0.2.2

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

Durations adds a time.Duration slice field.

func (*Event) Err

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

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

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

func (*Event) 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) Hex added in v0.4.8

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

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

func (*Event) Int

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

Int adds an int field.

func (*Event) Int64 added in v0.4.1

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

Int64 adds an int64 field.

func (*Event) Ints

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

Ints adds an int slice field.

func (*Event) Ints64 added in v0.4.4

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

Ints64 adds an int64 slice field.

func (*Event) JSON added in v0.4.4

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

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

func (*Event) Line

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

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

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

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

func (*Event) Msg

func (e *Event) Msg(msg string)

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

func (*Event) Msgf

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

Msgf finalises the event with a formatted message.

func (*Event) Path

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

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

func (*Event) Percent added in v0.3.0

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

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

func (*Event) Prefix

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

Prefix overrides the default emoji prefix for this entry.

func (*Event) Quantities added in v0.2.2

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

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

func (*Event) Quantity added in v0.2.2

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

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

func (*Event) RawJSON added in v0.4.4

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

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

func (*Event) Send

func (e *Event) Send()

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

func (*Event) Str

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

Str adds a string field.

func (*Event) Stringer

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

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

func (*Event) Stringers

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

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

func (*Event) Strs

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

Strs adds a string slice field.

func (*Event) Time added in v0.1.1

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

Time adds a time.Time field.

func (*Event) Times added in v0.4.4

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

Times adds a time.Time slice field.

func (*Event) URL added in v0.2.1

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

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

func (*Event) Uint added in v0.4.1

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

Uint adds a uint field.

func (*Event) Uint64

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

Uint64 adds a uint64 field.

func (*Event) Uints added in v0.4.4

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

Uints adds a uint slice field.

func (*Event) Uints64

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

Uints64 adds a uint64 slice field.

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 JSONMode added in v0.4.4

type JSONMode int

JSONMode controls how JSON is rendered.

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

type JSONSpacing added in v0.4.4

type JSONSpacing uint

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

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

type JSONStyles added in v0.4.4

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

	Key            Style // Object keys
	String         Style // String values
	Number         Style // Numeric values — base fallback for all number sub-styles
	NumberPositive Style // Positive numbers (with or without explicit sign); falls back to Number
	NumberNegative Style // Negative numbers; falls back to Number
	NumberZero     Style // Zero; falls back to NumberPositive, then Number
	NumberFloat    Style // Floating-point values; falls back to Number
	NumberInteger  Style // Integer values; falls back to Number
	True           Style // true
	False          Style // false
	Null           Style // null
	Brace          Style // { } (nested)
	RootBrace      Style // { } (outermost object; falls back to Brace if nil)
	Bracket        Style // [ ] (nested)
	RootBracket    Style // [ ] (outermost array; falls back to Bracket if nil)
	Colon          Style // :
	Comma          Style // ,
}

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

Use DefaultJSONStyles as a starting point for customization.

func DefaultJSONStyles added in v0.4.4

func DefaultJSONStyles() *JSONStyles

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

func (*JSONStyles) WithSpacing added in v0.4.4

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

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

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

type 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 LevelStyleMap added in v0.3.0

type LevelStyleMap = map[Level]Style

LevelStyleMap maps log levels to lipgloss styles.

func DefaultMessageStyles

func DefaultMessageStyles() LevelStyleMap

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

type Logger

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

Logger is the main structured logger.

func New

func New(output *Output) *Logger

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

func NewWriter added in v0.3.1

func NewWriter(w io.Writer) *Logger

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

func (*Logger) 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) Output added in v0.3.1

func (l *Logger) Output() *Output

Output returns the logger's Output.

func (*Logger) SetExitFunc

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

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

func (*Logger) SetFieldStyleLevel added in v0.1.2

func (l *Logger) SetFieldStyleLevel(level Level)

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

func (*Logger) SetFieldTimeFormat added in v0.1.1

func (l *Logger) SetFieldTimeFormat(format string)

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

func (*Logger) SetHandler

func (l *Logger) SetHandler(h Handler)

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

func (*Logger) 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) SetLevelLabels added in v0.2.2

func (l *Logger) SetLevelLabels(labels LevelMap)

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

func (*Logger) SetOmitEmpty

func (l *Logger) SetOmitEmpty(omit bool)

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

func (*Logger) SetOmitZero

func (l *Logger) SetOmitZero(omit bool)

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

func (*Logger) SetOutput

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

SetOutput sets the output.

func (*Logger) SetOutputWriter added in v0.3.1

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

SetOutputWriter sets the output writer with ColorAuto.

func (*Logger) SetParts

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

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

func (*Logger) 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. If styles is nil, DefaultStyles is used.

func (*Logger) SetTimeFormat

func (l *Logger) SetTimeFormat(format string)

SetTimeFormat sets the timestamp format string.

func (*Logger) SetTimeLocation

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

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

func (*Logger) 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 Output added in v0.3.1

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

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

func NewOutput added in v0.3.1

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

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

func Stderr added in v0.3.1

func Stderr(mode ColorMode) *Output

Stderr returns a new Output for os.Stderr.

func Stdout added in v0.3.1

func Stdout(mode ColorMode) *Output

Stdout returns a new Output for os.Stdout.

func TestOutput added in v0.3.1

func TestOutput(w io.Writer) *Output

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

func (*Output) ColorsDisabled added in v0.3.1

func (o *Output) ColorsDisabled() bool

ColorsDisabled returns true if this output should suppress colors.

func (*Output) IsTTY added in v0.3.1

func (o *Output) IsTTY() bool

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

func (*Output) RefreshWidth added in v0.3.1

func (o *Output) RefreshWidth()

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

func (*Output) Renderer added in v0.3.1

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

Renderer returns the lipgloss.Renderer configured for this output.

func (*Output) Width added in v0.3.1

func (o *Output) Width() int

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

func (*Output) Writer added in v0.3.1

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

Writer returns the underlying io.Writer.

type Part

type Part int

Part identifies a component of a formatted log line.

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

func DefaultParts

func DefaultParts() []Part

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

type ProgressTask

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

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

type ProgressUpdate

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

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

func (*ProgressUpdate) Any

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

Any adds a field with an arbitrary value.

func (*ProgressUpdate) Anys

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

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

func (*ProgressUpdate) Base64 added in v0.4.8

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

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

func (*ProgressUpdate) Bool

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

Bool adds a bool field.

func (*ProgressUpdate) Bools

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

Bools adds a bool slice field.

func (*ProgressUpdate) Bytes added in v0.4.7

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

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

func (*ProgressUpdate) Duration added in v0.2.2

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

Duration adds a time.Duration field.

func (*ProgressUpdate) Durations added in v0.2.2

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

Durations adds a time.Duration slice field.

func (*ProgressUpdate) Err added in v0.4.1

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

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

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

func (*ProgressUpdate) Float64

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

Float64 adds a float64 field.

func (*ProgressUpdate) Floats64

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

Floats64 adds a float64 slice field.

func (*ProgressUpdate) Hex added in v0.4.8

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

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

func (*ProgressUpdate) Int

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

Int adds an int field.

func (*ProgressUpdate) Int64 added in v0.4.1

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

Int64 adds an int64 field.

func (*ProgressUpdate) Ints

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

Ints adds an int slice field.

func (*ProgressUpdate) Ints64 added in v0.4.4

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

Ints64 adds an int64 slice field.

func (*ProgressUpdate) JSON added in v0.4.4

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

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

func (*ProgressUpdate) Percent added in v0.3.0

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

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

func (*ProgressUpdate) Quantities added in v0.2.2

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

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

func (*ProgressUpdate) Quantity added in v0.2.2

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

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

func (*ProgressUpdate) RawJSON added in v0.4.4

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

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

func (*ProgressUpdate) Send

func (u *ProgressUpdate) Send()

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

func (*ProgressUpdate) Str

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

Str adds a string field.

func (*ProgressUpdate) Stringer added in v0.4.1

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

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

func (*ProgressUpdate) Stringers added in v0.4.1

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

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

func (*ProgressUpdate) Strs

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

Strs adds a string slice field.

func (*ProgressUpdate) Time added in v0.1.1

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

Time adds a time.Time field.

func (*ProgressUpdate) Title

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

Title sets the animation's displayed title.

func (*ProgressUpdate) Uint added in v0.4.1

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

Uint adds a uint field.

func (*ProgressUpdate) Uint64

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

Uint64 adds a uint64 field.

func (*ProgressUpdate) Uints added in v0.4.4

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

Uints adds a uint slice field.

func (*ProgressUpdate) Uints64

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

Uints64 adds a uint64 slice field.

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 Style added in v0.4.4

type Style = *lipgloss.Style

Style is a convenience alias for *lipgloss.Style.

type StyleMap added in v0.3.0

type StyleMap = map[string]Style

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

type Styles

type Styles struct {
	// Duration unit -> thresholds (evaluated high->low).
	DurationThresholds ThresholdMap
	// Duration unit -> style override (e.g. "s" -> yellow).
	DurationUnits StyleMap
	// Style for the numeric segments of duration values (e.g. "1" in "1m30s") [nil = plain text]
	FieldDurationNumber Style
	// Style for the unit segments of duration values (e.g. "m" in "1m30s") [nil = plain text]
	FieldDurationUnit Style
	// Style for error field values [nil = plain text]
	FieldError Style
	// Per-token styles for JSON syntax highlighting.
	// nil disables JSON highlighting; use [DefaultJSONStyles] to enable.
	FieldJSON *JSONStyles
	// Style for int/float field values [nil = plain text]
	FieldNumber Style
	// Base style for Percent fields (foreground overridden by gradient). nil = gradient color only.
	FieldPercent Style
	// Style for the numeric part of quantity values (e.g. "5" in "5km") [nil = plain text]
	FieldQuantityNumber Style
	// Style for the unit part of quantity values (e.g. "km" in "5km") [nil = plain text]
	FieldQuantityUnit Style
	// Style for string field values [nil = plain text]
	FieldString Style
	// Style for time.Time field values [nil = plain text]
	FieldTime Style
	// Style for field key names without a per-key override.
	KeyDefault Style
	// Field key name -> value style (e.g. "path" -> blue).
	Keys StyleMap
	// Level label style (e.g. "INF", "ERR").
	Levels LevelStyleMap
	// Message text style per level.
	Messages LevelStyleMap
	// Gradient stops for Percent fields (default: red → yellow → green).
	PercentGradient []ColorStop
	// Decimal places for Percent display (default 0 = "75%", 1 -> "75.0%", etc).
	PercentPrecision int
	// Quantity unit -> thresholds (evaluated high->low).
	QuantityThresholds ThresholdMap
	// Unit string -> style override (e.g. "km" -> green).
	QuantityUnits StyleMap
	// Case-insensitive quantity unit matching (default true).
	QuantityUnitsIgnoreCase bool
	// Style for key/value [SeparatorText].
	Separator Style
	// Separator between key and value (default "=").
	SeparatorText string
	// Style for the timestamp prefix.
	Timestamp Style
	// Values maps typed values to styles. Keys use Go equality
	// Allows diffentiating between e.g. `true` (bool) and "true" (string)
	Values ValueStyleMap
}

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

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 AnimationBuilder.Wait.

type Threshold added in v0.3.0

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

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

type ThresholdMap added in v0.3.0

type ThresholdMap = map[string]Thresholds

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

type ThresholdStyle added in v0.3.1

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

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

type Thresholds added in v0.3.0

type Thresholds = []Threshold

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

type ValueStyleMap added in v0.3.0

type ValueStyleMap = map[any]Style

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

func DefaultValueStyles

func DefaultValueStyles() ValueStyleMap

DefaultValueStyles returns sensible default styles for common value strings.

type WaitResult

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

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

func (*WaitResult) Any

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

Any adds a field with an arbitrary value.

func (*WaitResult) Anys

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

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

func (*WaitResult) Base64 added in v0.4.8

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

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

func (*WaitResult) Bool

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

Bool adds a bool field.

func (*WaitResult) Bools

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

Bools adds a bool slice field.

func (*WaitResult) Bytes added in v0.4.7

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

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

func (*WaitResult) Duration added in v0.2.2

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

Duration adds a time.Duration field.

func (*WaitResult) Durations added in v0.2.2

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

Durations adds a time.Duration slice field.

func (*WaitResult) Err

func (w *WaitResult) Err() error

Err returns the error, logging success at info level or failure at error level using the original animation 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) Hex added in v0.4.8

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

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

func (*WaitResult) Int

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

Int adds an int field.

func (*WaitResult) Int64 added in v0.4.1

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

Int64 adds an int64 field.

func (*WaitResult) Ints

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

Ints adds an int slice field.

func (*WaitResult) Ints64 added in v0.4.4

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

Ints64 adds an int64 slice field.

func (*WaitResult) JSON added in v0.4.4

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

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

func (*WaitResult) Msg

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

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

func (*WaitResult) OnErrorLevel added in v0.2.0

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

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

func (*WaitResult) OnErrorMessage added in v0.2.0

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

OnErrorMessage sets a custom message for the error case. Defaults to the error string.

func (*WaitResult) OnSuccessLevel added in v0.2.0

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

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

func (*WaitResult) OnSuccessMessage added in v0.2.0

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

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

func (*WaitResult) Percent added in v0.3.0

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

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

func (*WaitResult) Prefix

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

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

func (*WaitResult) Quantities added in v0.2.2

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

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

func (*WaitResult) Quantity added in v0.2.2

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

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

func (*WaitResult) RawJSON added in v0.4.4

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

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

func (*WaitResult) Send added in v0.2.0

func (w *WaitResult) Send() error

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

func (*WaitResult) Silent

func (w *WaitResult) Silent() error

Silent returns just the error without logging anything.

func (*WaitResult) Str

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

Str adds a string field.

func (*WaitResult) Stringer added in v0.4.4

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

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

func (*WaitResult) Stringers added in v0.4.4

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

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

func (*WaitResult) Strs

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

Strs adds a string slice field.

func (*WaitResult) Time added in v0.1.1

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

Time adds a time.Time field.

func (*WaitResult) Uint added in v0.4.1

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

Uint adds a uint field.

func (*WaitResult) Uint64

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

Uint64 adds a uint64 field.

func (*WaitResult) Uints added in v0.4.4

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

Uints adds a uint slice field.

func (*WaitResult) Uints64

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

Uints64 adds a uint64 slice field.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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