logger

package
v1.10.5 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package logger provides a unified logging interface for GTB applications.

It abstracts over multiple logging backends, allowing consumers to swap implementations without changing call sites. Two backends are provided:

  • NewCharm: backed by charmbracelet/log, providing coloured, styled CLI output. This is the default for interactive terminal applications.
  • NewSlog: backed by any slog.Handler, providing ecosystem interoperability with libraries like zap, zerolog, logrus, and OpenTelemetry.
  • NewNoop: discards all output, useful for tests.

The Logger interface exposes both structured (key-value) and printf-style logging methods, plus an unlevelled Print method for direct user output.

For interoperability with libraries that require *slog.Logger, use:

slogLogger := slog.New(logger.Handler())

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidLevel = errors.New("invalid level")

ErrInvalidLevel is returned when parsing an unrecognised level string.

Functions

func NewBuffer

func NewBuffer() *bufferLogger

NewBuffer returns a Logger that captures all log messages in memory. Use Messages(), Entries(), and Contains() to assert on captured output.

Example:

buf := logger.NewBuffer()
myFunc(buf)
if !buf.Contains("expected message") {
    t.Error("missing expected log message")
}
Example
package main

import (
	"github.com/phpboyscout/go-tool-base/pkg/logger"
)

func main() {
	// Create a buffer logger for testing log output.
	buf := logger.NewBuffer()

	buf.Info("test message", "key", "value")

	if buf.Contains("test message") {
		// Message was logged
	}
}

Types

type CharmOption

type CharmOption func(*log.Options)

CharmOption configures the charmbracelet backend.

func WithCaller

func WithCaller(enabled bool) CharmOption

WithCaller enables or disables caller location in log output.

func WithLevel

func WithLevel(level Level) CharmOption

WithLevel sets the initial log level.

func WithPrefix

func WithPrefix(prefix string) CharmOption

WithPrefix sets an initial prefix on the logger.

func WithTimestamp

func WithTimestamp(enabled bool) CharmOption

WithTimestamp enables or disables timestamps in log output.

type Entry

type Entry struct {
	Level   Level
	Message string
	Keyvals []any
}

Entry represents a single captured log message.

type Formatter

type Formatter int

Formatter represents a log output format.

const (
	// TextFormatter formats log messages as human-readable text.
	TextFormatter Formatter = iota
	// JSONFormatter formats log messages as JSON.
	JSONFormatter
	// LogfmtFormatter formats log messages as logfmt.
	LogfmtFormatter
)

type Level

type Level int

Level represents a logging severity level.

const (
	// DebugLevel is the most verbose level.
	DebugLevel Level = iota
	// InfoLevel is the default level.
	InfoLevel
	// WarnLevel is for potentially harmful situations.
	WarnLevel
	// ErrorLevel is for error conditions.
	ErrorLevel
	// FatalLevel is for fatal conditions that terminate the process.
	FatalLevel
)

func ParseLevel

func ParseLevel(s string) (Level, error)

ParseLevel converts a level string ("debug", "info", "warn", "error", "fatal") to a Level value.

func (Level) String

func (l Level) String() string

String returns the level name.

type Logger

type Logger interface {
	// Structured logging methods. keyvals are alternating key/value pairs.
	Debug(msg string, keyvals ...any)
	Info(msg string, keyvals ...any)
	Warn(msg string, keyvals ...any)
	Error(msg string, keyvals ...any)
	Fatal(msg string, keyvals ...any)

	// Printf-style logging methods.
	Debugf(format string, args ...any)
	Infof(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
	Fatalf(format string, args ...any)

	// Print writes an unlevelled message that is not filtered by log level.
	// Used for direct user-facing output (e.g., version info, release notes).
	Print(msg any, keyvals ...any)

	// With returns a new Logger with the given key-value pairs prepended
	// to every subsequent log call.
	With(keyvals ...any) Logger

	// WithPrefix returns a new Logger with the given prefix prepended to
	// every message.
	WithPrefix(prefix string) Logger

	// SetLevel changes the minimum log level dynamically.
	SetLevel(level Level)

	// GetLevel returns the current minimum log level.
	GetLevel() Level

	// SetFormatter changes the output format (text, json, logfmt).
	// Backends that do not support a given formatter silently ignore the call.
	SetFormatter(f Formatter)

	// Handler returns an slog.Handler for interoperability with libraries
	// that require *slog.Logger. Usage: slog.New(logger.Handler())
	Handler() slog.Handler
}

Logger is the unified logging interface for GTB. All packages accept this interface instead of a concrete logger type.

Logger is NOT safe for concurrent use unless the underlying backend documents otherwise. The charmbracelet and slog backends provided by this package are both safe for concurrent use.

func NewCharm

func NewCharm(w io.Writer, opts ...CharmOption) Logger

NewCharm returns a Logger backed by charmbracelet/log. This is the default backend for CLI applications, providing coloured, styled terminal output.

Example
package main

import (
	"os"

	"github.com/phpboyscout/go-tool-base/pkg/logger"
)

func main() {
	// Create a charmbracelet-based logger for CLI output.
	l := logger.NewCharm(os.Stderr,
		logger.WithTimestamp(true),
		logger.WithLevel(logger.InfoLevel),
	)

	l.Info("Application started", "version", "1.0.0")
	l.Debug("This won't appear at InfoLevel")
}

func NewNoop

func NewNoop() Logger

NewNoop returns a Logger that discards all output. Useful for tests where log output is irrelevant.

Example
package main

import (
	"github.com/phpboyscout/go-tool-base/pkg/logger"
)

func main() {
	// Create a silent logger for tests.
	l := logger.NewNoop()

	// All calls are no-ops — no output produced.
	l.Info("This produces no output")
	l.Error("Neither does this")
}

func NewSlog

func NewSlog(handler slog.Handler) Logger

NewSlog returns a Logger backed by an slog.Handler. Use this when you need ecosystem integration (OpenTelemetry, Datadog, custom handlers).

Any library that implements or bridges to slog.Handler works here:

Zap:     logger.NewSlog(zapslog.NewHandler(zapCore))
Zerolog: logger.NewSlog(slogzerolog.Option{Logger: &zl}.NewHandler())
OTEL:    logger.NewSlog(otelslog.NewHandler(exporter))

Jump to

Keyboard shortcuts

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