logging

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package logging provides a Nabat extension that installs a styled *slog.Logger into the App, plus optional --verbose and --log-level flag wiring. Use ParseLevel to parse the same level names (debug, info, warn, error) elsewhere in your CLI.

import (
    "log/slog"
    "nabat.dev/nabat"
    "nabat.dev/logging"
)

app := nabat.MustNew("myctl",
    nabat.WithExtension(logging.New(
        logging.WithLevel(slog.LevelInfo),
        logging.WithVerboseFlag("verbose"),
    )),
)

To bring your own logger instead, use nabat.WithLogger at construction time and skip this extension.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilOption is returned when a nil [Option] is passed to [New].
	ErrNilOption = errors.New("nabat/logging: option is nil")
	// ErrNilHandler is returned when [WithHandler] receives a nil handler.
	ErrNilHandler = errors.New("nabat/logging: handler is nil")
	// ErrUnknownLevel is returned when [ParseLevel] does not recognize
	// the input string.
	ErrUnknownLevel = errors.New("nabat/logging: unknown log level")
)

Sentinel errors for errors.Is checks.

Functions

func New

func New(opts ...Option) (nabat.Extension, error)

New returns a nabat.Extension that installs an opinionated logger.

Example
package main

import (
	"context"
	"fmt"
	"strings"

	"nabat.dev/logging"
	"nabat.dev/nabat"
	"nabat.dev/nabattest"
)

func main() {
	io, _, _, stderr := nabattest.NewIO()
	app := nabat.MustNew("myctl",
		nabat.WithIO(io),
		nabat.WithExtension(logging.New(logging.WithVerboseFlag("verbose"))),
	)
	app.MustCommand("hello", nabat.WithRun(func(c *nabat.Context) error {
		c.Logger().Info("ready")
		return nil
	}))
	if err := app.RunArgs(context.Background(), "hello"); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Print(strings.TrimSpace(stderr.String()))
}
Output:
INFO ready

func ParseLevel

func ParseLevel(s string) (slog.Level, error)

ParseLevel parses a log level name (case-insensitive): debug, info, warn, error. On failure, the error wraps ErrUnknownLevel.

Types

type Handler

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

Handler is a styled slog.Handler that writes human-readable log lines using lipgloss styles derived from a Styles value (typically produced by FromTheme).

Output format: LEVL message and optional structured key=value pairs.

func NewHandler

func NewHandler(w io.Writer, opts HandlerOptions) *Handler

NewHandler returns a Handler that writes styled log output to w.

func (*Handler) Enabled

func (h *Handler) Enabled(_ context.Context, level slog.Level) bool

func (*Handler) Handle

func (h *Handler) Handle(_ context.Context, r slog.Record) error

func (*Handler) SetStyles

func (h *Handler) SetStyles(s Styles)

SetStyles updates the handler's styles. Safe to call concurrently with log writes.

func (*Handler) WithAttrs

func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*Handler) WithGroup

func (h *Handler) WithGroup(name string) slog.Handler

type HandlerOptions

type HandlerOptions struct {
	Level     *slog.LevelVar
	Styles    Styles
	Timestamp bool
}

HandlerOptions configures a Handler.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures the logging extension.

func WithHandler

func WithHandler(h slog.Handler) Option

WithHandler installs a custom slog handler. The extension wraps it in a dynamic-level adjuster so verbose/level flag changes still apply.

Returns an error if h is nil.

func WithLevel

func WithLevel(l slog.Level) Option

WithLevel sets the base log level (default slog.LevelInfo).

func WithLevelFlag

func WithLevelFlag(name string) Option

WithLevelFlag wires a string flag (debug|info|warn|error) parsed to set the per-invocation level. The flag must be declared by the user via nabat.WithFlag.

func WithSetDefault

func WithSetDefault() Option

WithSetDefault installs the extension's logger as the process-wide slog.Default via slog.SetDefault.

func WithTimestamp

func WithTimestamp() Option

WithTimestamp enables timestamps on the default styled handler. Has no effect when WithHandler supplies a custom handler.

func WithVerboseFlag

func WithVerboseFlag(name string) Option

WithVerboseFlag wires a bool flag whose presence flips the level to slog.LevelDebug for the invocation. The flag must be declared by the user via nabat.WithFlag (typically on the root command with nabat.WithPersistent).

type Styles

type Styles struct {
	// Debug styles the "DEBU" level badge for debug records.
	Debug lipgloss.Style

	// Info styles the "INFO" level badge for informational records.
	Info lipgloss.Style

	// Warn styles the "WARN" level badge for warning records.
	Warn lipgloss.Style

	// Error styles the "ERRO" level badge for error records.
	Error lipgloss.Style

	// Key styles structured-log attribute keys (the left side of `key=value`).
	Key lipgloss.Style

	// Value styles structured-log attribute values (the right side of `key=value`).
	Value lipgloss.Style
}

Styles holds lipgloss styles used by the logging extension to color level badges and key/value pairs in structured log output.

Construct one from a theme.ResolvedTheme via FromTheme (the default), or build one by hand for custom handlers that want different visuals. Once built, Styles is immutable and safe to share across goroutines.

func FromTheme

func FromTheme(rt theme.ResolvedTheme) Styles

FromTheme derives the logging extension's level-badge and key/value styles from a theme.ResolvedTheme using the well-known semantic tokens — theme.StatusInfo, theme.StatusWarning, theme.StatusError for level badges and theme.AccentPrimary, theme.TextPrimary for the key=value pairs. Each badge is a fixed-width "DEBU" / "INFO" / "WARN" / "ERRO" label rendered bold.

FromTheme keeps theme derivation a logging-package concern so the nabat root package does not have to know about logger concepts; the nabat/logging extension owns its own visual contract end to end.

Callers that want a different shape (different badge text, different width, extra fields) can build a Styles value directly instead of going through FromTheme.

Jump to

Keyboard shortcuts

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