cli

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package cli provides a Transport tuned for command-line application output rather than diagnostic logging.

What makes it different from the other terminal-shaped transports (go.loglayer.dev/transports/console, go.loglayer.dev/transports/pretty):

  • No timestamp, no log-id, no level label embedded in info/debug output. The message string is printed as-is.
  • Warn / error / fatal messages get a short cargo / eslint-style prefix ("warning: ", "error: ", "fatal: ") so the urgency is unambiguous when a CLI run mixes levels.
  • Info / debug write to stdout; warn / error / fatal write to stderr, matching long-standing CLI convention.
  • ANSI color is gated by TTY detection on stdout. Pipe to a file and the color disappears automatically. Override via [Config.Color].
  • Fields and metadata are dropped by default. CLI users don't want `key=value` noise on user-facing output. Set [Config.ShowFields] to append them when running with `-vv` / debug verbosity.

What this transport is NOT:

Recommended plugin pairings:

  • go.loglayer.dev/plugins/fmtlog for fmt.Sprintf-style format strings (`log.Info("Applied %d release(s) at %s:", n, sha)`). CLI output almost always wants format-string semantics.
  • go.loglayer.dev/plugins/redact when log values may include tokens or other secrets that shouldn't reach stdout / stderr.

See https://go.loglayer.dev for usage guides and the full API reference.

Example

The package-level Example shows the canonical wiring: a CLI app's status messages emit unadorned to stdout, warnings and errors get short prefixes and route to stderr.

Color is forced off so the example output is byte-stable; a real CLI would leave cli.Config.Color at its zero value (ColorAuto) to get TTY-detected color.

t := clitr.New(clitr.Config{
	Stdout: os.Stdout,
	Stderr: os.Stdout, // merged for demo determinism
	Color:  clitr.ColorNever,
})
log := loglayer.New(loglayer.Config{
	Transport:        t,
	DisableFatalExit: true,
})

log.Info("Applied 1 release(s) at f5f6a9a:")
log.Warn("running on stale credentials")
log.Error("connection refused")
Output:
Applied 1 release(s) at f5f6a9a:
warning: running on stale credentials
error: connection refused
Example (Table)

Example_table demonstrates the table rendering mode: when metadata is a slice of maps, the transport renders an aligned table after the message. Same call site emits a proper JSON array when paired with the structured transport.

t := clitr.New(clitr.Config{
	Stdout: os.Stdout,
	Color:  clitr.ColorNever,
})
log := loglayer.New(loglayer.Config{Transport: t})

log.WithMetadata([]loglayer.Metadata{
	{"package": "transports/foo", "from": "v1.5.0", "to": "v1.6.0"},
	{"package": "transports/bar", "from": "v0.2.0", "to": "v1.0.0"},
}).Info("Plan:")
Output:
Plan:
FROM    PACKAGE         TO
v1.5.0  transports/foo  v1.6.0
v0.2.0  transports/bar  v1.0.0

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColorMode

type ColorMode int

ColorMode controls ANSI color output.

const (
	// ColorAuto emits color when the configured stdout is a TTY.
	// Zero value; the typical CLI default.
	ColorAuto ColorMode = iota

	// ColorAlways emits color regardless of the output target.
	// Use for `--color=always` flags or when piping into a paginator
	// that handles ANSI.
	ColorAlways

	// ColorNever disables ANSI escapes entirely. Use for
	// `--color=never` and when writing to a log file.
	ColorNever
)

type Config

type Config struct {
	transport.BaseConfig

	// Stdout overrides os.Stdout. Info / debug entries write here.
	Stdout io.Writer

	// Stderr overrides os.Stderr. Warn / error / fatal entries
	// write here.
	Stderr io.Writer

	// Color controls ANSI color output. Zero value is [ColorAuto].
	Color ColorMode

	// ShowFields, when true, appends fields and metadata after the
	// message in `key=value` form (logfmt). Default false: CLI
	// users don't want structured noise on user-facing output.
	// Useful when wiring `-vv` / `--debug` to a verbose mode that
	// includes diagnostic context.
	ShowFields bool

	// LevelPrefix overrides the default per-level prefix map.
	// Missing entries fall back to the defaults:
	//
	//   Trace: ""
	//   Debug: "debug: "
	//   Info:  ""
	//   Warn:  "warning: "
	//   Error: "error: "
	//   Fatal: "fatal: "
	//   Panic: "panic: "
	//
	// Set an entry to "" to suppress the default prefix for that
	// level. Use a non-default string to localize or rebrand
	// (e.g. "WARN: "). Override only the levels you want to
	// change; the remaining levels keep their defaults.
	//
	// To suppress every prefix at once, set DisableLevelPrefix
	// instead of populating an empty map for every level.
	LevelPrefix map[loglayer.LogLevel]string

	// DisableLevelPrefix, when true, suppresses every per-level
	// prefix unconditionally. Set this when the host CLI already
	// renders its own urgency markers (e.g. an icon column) and
	// the transport's prefixes would be redundant.
	DisableLevelPrefix bool

	// LevelColor overrides the default per-level color map.
	// Missing entries fall back to the defaults:
	//
	//   Trace, Debug:  dim grey  (color.FgHiBlack)
	//   Info:          no color
	//   Warn:          yellow
	//   Error:         red
	//   Fatal, Panic:  bold red
	//
	// Set an entry to nil to render that level without color while
	// keeping all other defaults. Use a custom *color.Color (from
	// fatih/color) to rebrand: e.g. cyan for warn, magenta for
	// fatal. color.New is the only fatih/color symbol you need;
	// the transport shallow-copies each entry and handles the
	// per-instance flag toggling that bypasses fatih/color's
	// process-global NoColor, so a *color.Color passed here can
	// be shared safely across multiple transports.
	//
	// Color is then resolved through Config.Color (Auto / Always /
	// Never), so an override here doesn't force ANSI on a piped
	// stdout unless you also set Color: ColorAlways.
	LevelColor map[loglayer.LogLevel]*color.Color
}

Config holds configuration options for Transport.

type Transport

type Transport struct {
	transport.BaseTransport
	// contains filtered or unexported fields
}

Transport renders log entries as plain CLI output.

func New

func New(cfg Config) *Transport

New constructs a Transport from cfg. The TTY detection for ColorAuto runs once here against cfg.Stdout (or os.Stdout when cfg.Stdout is nil); subsequent writes don't re-check.

Example

ExampleNew shows the minimal constructor: zero-value Config gives stdout / stderr routing, TTY-detected color, no level label on info, and short prefixes on warn / error.

t := clitr.New(clitr.Config{
	Stdout: os.Stdout,
	Color:  clitr.ColorNever, // deterministic example output
})
log := loglayer.New(loglayer.Config{Transport: t})
log.Info("hello")
Output:
hello

func (*Transport) GetLoggerInstance

func (t *Transport) GetLoggerInstance() any

GetLoggerInstance returns nil; the cli transport has no underlying logger library.

func (*Transport) SendToLogger

func (t *Transport) SendToLogger(params loglayer.TransportParams)

SendToLogger implements [loglayer.Transport].

Jump to

Keyboard shortcuts

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