log

package
v0.0.0-...-e67fd50 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

README

Logging Package

This package is the repository-standard logging entry point. Application code should use internal/shell/logging instead of ad-hoc fmt, log, or direct slog calls.

Purpose

The package centralizes:

  • console logging for user-facing CLI output
  • file logging for detailed diagnostics
  • structured context fields
  • progress-aware logging behavior

Repository-wide guidance lives in:

Maintainer Guidance

  • initialize logging once near process startup
  • use this package directly from handlers, services, and infrastructure code
  • prefer structured fields for machine-relevant details
  • keep end-user console output readable; avoid dumping raw internals at info
  • use typed errors plus contextual logging instead of stringly-typed error chains

Common Usage

import log "gitlab.git.nrw/divekit/divekit-cli/internal/shell/logging"

log.InitDefault()
_ = log.DefineLoggingLevel("info")

log.Info("Distribution initialized")
log.WithError(err).WithField("origin_id", originID).Error("Failed to refresh origin")

logger := log.NewContextLogger("gui")
logger.WithField("workspace_id", workspaceID).Info("Workspace switched")

Runtime Behavior

  • console output is intentionally cleaner than file output
  • debug logging includes more metadata for local diagnosis
  • file logs are written under ~/.divekit/logs/
  • progress-aware handlers coordinate with interactive terminal rendering

Key Files

  • log.go: main API, context logger, error logger
  • log_init.go: initialization and level setup
  • log_handlers.go: console/file/multi-handler behavior
  • progress_aware.go: coordination with progress rendering
  • error.go: package-local error types

Verification

Run:

go test ./internal/shell/logging

Documentation

Overview

Package log provides application-wide logging utilities and typed errors for consistent log level parsing and reporting.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CurrentLogDir

func CurrentLogDir() (string, error)

CurrentLogDir returns the effective file-log directory for the current process.

func Debug

func Debug(msg string)

Debug logs a debug message.

func Debugf

func Debugf(format string, args ...any)

Debugf logs a formatted debug message.

func DefineLoggingLevel

func DefineLoggingLevel(logLevelString string) error

DefineLoggingLevel configures the logging system based on the provided log level string. It sets up both console and file logging with appropriate handlers and levels. The function supports various log level strings and provides fallback behavior for invalid inputs.

func Error

func Error(msg string)

Error logs an error message.

func Errorf

func Errorf(format string, args ...any)

Errorf logs a formatted error message.

func Fatal

func Fatal(msg string)

Fatal logs a fatal message and exits.

func GetLogLevel

func GetLogLevel() slog.Level

GetLogLevel returns the current global logging level used by the CLI. Access is atomic to avoid races in parallel tests and goroutines.

func GetSlogLogger

func GetSlogLogger() *slog.Logger

GetSlogLogger returns the global slog logger instance

func Info

func Info(msg string)

Info logs an informational message.

func Infof

func Infof(format string, args ...any)

Infof logs a formatted informational message.

func InitDefault

func InitDefault()

InitDefault initializes the logging system with a minimal console handler at info level. It sets up basic logging for early application startup before command-line flags are parsed. The function is safe to call multiple times and becomes a no-op after the first successful initialization. The final log level and handlers are configured later by DefineLoggingLevel based on user-provided flags.

func IsProgressBarActive

func IsProgressBarActive() bool

IsProgressBarActive returns whether progress bars are currently active

func IsProgressSuppressed

func IsProgressSuppressed() bool

IsProgressSuppressed returns whether progress output is globally suppressed

func IsTestMode

func IsTestMode() bool

IsTestMode returns true if running under go test. Uses multiple detection methods for reliability.

func LevelAsString

func LevelAsString() string

LevelAsString returns the string representation of the current global LogLevel. This is primarily used for displaying the current log level in help text or status messages.

func ProgressAwareLog

func ProgressAwareLog(level string, message string)

ProgressAwareLog logs a message, handling progress bar coordination

func SetLogLevel

func SetLogLevel(level slog.Level)

SetLogLevel sets the current global logging level used by the CLI. Access is atomic to avoid races in parallel tests and goroutines.

func SetProgressBarActive

func SetProgressBarActive(active bool)

SetProgressBarActive marks that progress bars are currently being used

func SetProgressSuppressed

func SetProgressSuppressed(suppress bool)

SetProgressSuppressed globally suppresses all progress output (used when footer UI is active)

func SetSlogLogger

func SetSlogLogger(logger *slog.Logger)

SetSlogLogger sets the global slog logger instance

func ShouldSuppressProgress

func ShouldSuppressProgress() bool

ShouldSuppressProgress returns true if progress bars should be completely disabled. This checks multiple conditions to ensure we don't write escape sequences when inappropriate.

func Spacing

func Spacing(count int)

Spacing outputs the specified number of blank lines for visual spacing. Similar to SizedBox in Flutter, this provides controlled vertical spacing. If count is 0 or negative, no blank lines are output.

func StringAsSlogLevel

func StringAsSlogLevel(levelStr string) (slog.Level, error)

StringAsSlogLevel converts a string representation of a log level to the corresponding slog Level. It supports common aliases and case-insensitive matching. Returns an error for invalid level strings.

func Warn

func Warn(msg string)

Warn logs a warning message.

func Warnf

func Warnf(format string, args ...any)

Warnf logs a formatted warning message.

Types

type Chattyness

type Chattyness int

Chattyness represents different levels of verbosity for logging output. It controls how much detail is included in log messages.

const (
	// Silent suppresses all non-error output
	Silent Chattyness = iota
	// Verbose includes additional informational messages
	Verbose
	// VeryVerbose includes detailed debug information
	VeryVerbose
)

type ContextLogger

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

ContextLogger provides structured logging with contextual information. It allows adding context strings and key-value fields to log entries for better traceability and debugging.

func NewContextLogger

func NewContextLogger(context string) *ContextLogger

NewContextLogger creates a new ContextLogger with the specified context string. The context is included in all log messages produced by this logger instance.

func (*ContextLogger) Debug

func (cl *ContextLogger) Debug(msg string)

Debug logs a debug message with the logger's context and fields.

func (*ContextLogger) Debugf

func (cl *ContextLogger) Debugf(format string, args ...any)

Debugf logs a formatted debug message with the logger's context and fields.

func (*ContextLogger) Error

func (cl *ContextLogger) Error(msg string)

Error logs an error message with the logger's context and fields.

func (*ContextLogger) Errorf

func (cl *ContextLogger) Errorf(format string, args ...any)

Errorf logs a formatted error message with the logger's context and fields.

func (*ContextLogger) Fatal

func (cl *ContextLogger) Fatal(msg string)

Fatal logs a fatal message with the logger's context and fields, then exits.

func (*ContextLogger) Info

func (cl *ContextLogger) Info(msg string)

Info logs an informational message with the logger's context and fields.

func (*ContextLogger) Infof

func (cl *ContextLogger) Infof(format string, args ...any)

Infof logs a formatted informational message with the logger's context and fields.

func (*ContextLogger) Warn

func (cl *ContextLogger) Warn(msg string)

Warn logs a warning message with the logger's context and fields.

func (*ContextLogger) Warnf

func (cl *ContextLogger) Warnf(format string, args ...any)

Warnf logs a formatted warning message with the logger's context and fields.

func (*ContextLogger) WithField

func (cl *ContextLogger) WithField(key string, value any) Logger

WithField adds a single key-value field to the logger's context. The field will be included in all subsequent log messages from this logger. Returns a new Logger instance for method chaining (actual type: *ContextLogger).

func (*ContextLogger) WithFields

func (cl *ContextLogger) WithFields(fields map[string]any) Logger

WithFields adds multiple key-value fields to the logger's context. All provided fields will be included in subsequent log messages from this logger. Returns a new Logger instance for method chaining (actual type: *ContextLogger).

type ErrorLogger

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

ErrorLogger wraps a logger with error context and provides convenience methods.

func WithError

func WithError(err error) *ErrorLogger

WithError returns a logger with error context. This maintains API compatibility with code that uses WithError().Info() patterns.

func (*ErrorLogger) Debug

func (el *ErrorLogger) Debug(msg string)

Debug logs a debug message with error context

func (*ErrorLogger) Debugf

func (el *ErrorLogger) Debugf(format string, args ...any)

Debugf logs a formatted debug message with error context

func (*ErrorLogger) Error

func (el *ErrorLogger) Error(msg string)

Error logs an error message with error context

func (*ErrorLogger) Errorf

func (el *ErrorLogger) Errorf(format string, args ...any)

Errorf logs a formatted error message with error context

func (*ErrorLogger) Info

func (el *ErrorLogger) Info(msg string)

Info logs an info message with error context

func (*ErrorLogger) Infof

func (el *ErrorLogger) Infof(format string, args ...any)

Infof logs a formatted info message with error context

func (*ErrorLogger) Warn

func (el *ErrorLogger) Warn(msg string)

Warn logs a warning message with error context

func (*ErrorLogger) Warnf

func (el *ErrorLogger) Warnf(format string, args ...any)

Warnf logs a formatted warning message with error context

func (*ErrorLogger) WithField

func (el *ErrorLogger) WithField(key string, value any) *ErrorLogger

WithField adds a field to the error logger

type ErrorType

type ErrorType int

ErrorType defines domain-based error categories for the log package.

const (
	// ErrValidation indicates validation errors.
	ErrValidation ErrorType = iota
)

type LogError

type LogError struct {
	ErrorType ErrorType
	Message   string
	Err       error
}

LogError represents a structured error originating in the log package.

func NewInvalidLogLevelError

func NewInvalidLogLevelError(level string) *LogError

NewInvalidLogLevelError creates an error for invalid log level.

func NewLogError

func NewLogError(errorType ErrorType, message string, err error) *LogError

NewLogError constructs a new LogError.

func (*LogError) Error

func (e *LogError) Error() string

Error implements the error interface for LogError.

type Logger

type Logger interface {
	// Info logs an informational message.
	Info(msg string)

	// Warn logs a warning message.
	Warn(msg string)

	// Error logs an error message.
	Error(msg string)

	// Debug logs a debug message.
	Debug(msg string)

	// Infof logs a formatted informational message.
	Infof(format string, args ...any)

	// Warnf logs a formatted warning message.
	Warnf(format string, args ...any)

	// Errorf logs a formatted error message.
	Errorf(format string, args ...any)

	// Debugf logs a formatted debug message.
	Debugf(format string, args ...any)

	// WithField adds a single key-value field to the logger's context.
	// Returns a new Logger instance with the field added.
	WithField(key string, value any) Logger

	// WithFields adds multiple key-value fields to the logger's context.
	// Returns a new Logger instance with the fields added.
	WithFields(fields map[string]any) Logger
}

Logger is an injectable interface for structured logging with contextual information. It allows adding context strings and key-value fields to log entries.

type ProgressAwareConfig

type ProgressAwareConfig struct {
	// SuppressProgressForLogging suppresses progress bars when verbose logging is enabled
	SuppressProgressForLogging bool
	// LogLevel threshold above which progress bars are disabled
	LogLevelThreshold string
}

ProgressAwareConfig controls how progress bars and logging interact

type SlogConsoleHandler

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

SlogConsoleHandler provides user-friendly console output for slog. It formats messages cleanly with optional colors and suppresses metadata for better readability.

func NewSlogConsoleHandler

func NewSlogConsoleHandler(w io.Writer, minLevel slog.Level) *SlogConsoleHandler

NewSlogConsoleHandler creates a console handler for slog that mimics the existing console output format.

func (*SlogConsoleHandler) Enabled

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

Enabled reports whether the handler handles records at the given level.

func (*SlogConsoleHandler) Handle

Handle processes a log record and writes it to the output.

func (*SlogConsoleHandler) WithAttrs

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

WithAttrs returns a new handler with the given attributes added.

func (*SlogConsoleHandler) WithGroup

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

WithGroup returns a new handler with the given group added.

type SlogFileHandler

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

SlogFileHandler provides structured file output for slog. It writes all log levels with full metadata for debugging.

func NewSlogFileHandler

func NewSlogFileHandler(w io.Writer, minLevel slog.Level) *SlogFileHandler

NewSlogFileHandler creates a file handler for slog that logs everything with full metadata.

func (*SlogFileHandler) Enabled

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

Enabled reports whether the handler handles records at the given level.

func (*SlogFileHandler) Handle

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

Handle processes a log record and writes it to the file.

func (*SlogFileHandler) WithAttrs

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

WithAttrs returns a new handler with the given attributes added.

func (*SlogFileHandler) WithGroup

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

WithGroup returns a new handler with the given group added.

type SlogMultiHandler

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

SlogMultiHandler forwards log records to multiple handlers.

func NewSlogMultiHandler

func NewSlogMultiHandler(handlers ...slog.Handler) *SlogMultiHandler

NewSlogMultiHandler creates a handler that writes to multiple handlers.

func (*SlogMultiHandler) Enabled

func (h *SlogMultiHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled reports whether any of the handlers would handle records at the given level.

func (*SlogMultiHandler) Handle

func (h *SlogMultiHandler) Handle(ctx context.Context, r slog.Record) error

Handle forwards the log record to all handlers.

func (*SlogMultiHandler) WithAttrs

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

WithAttrs returns a new handler with the given attributes added to all child handlers.

func (*SlogMultiHandler) WithGroup

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

WithGroup returns a new handler with the given group added to all child handlers.

Jump to

Keyboard shortcuts

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