logging

package
v0.7.2 Latest Latest
Warning

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

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

Documentation

Overview

Package logging provides a structured logging system for muster with unified log handling and flexible output formatting.

This package implements a logging system built on Go's standard slog package, providing consistent logging behavior with structured output and level filtering.

Architecture

The logging system is built around these core concepts:

## Log Levels

  • **Debug**: Detailed information for debugging and development
  • **Info**: General informational messages about application operation
  • **Warn**: Warning messages that indicate potential issues
  • **Error**: Error messages for failures and exceptional conditions

## Structured Logging All log entries include:

  • Timestamp with nanosecond precision
  • Log level (Debug, Info, Warn, Error)
  • Subsystem identifier for categorization
  • Message content with optional formatting
  • Optional error information

Usage Examples

## Initialization

import "github.com/giantswarm/muster/pkg/logging"

// Initialize with Info level logging to stdout
logging.InitForCLI(logging.LevelInfo, os.Stdout)

// Log messages
logging.Info("Bootstrap", "Application starting up")
logging.Debug("Config", "Loaded configuration from %s", configPath)
logging.Warn("Service", "Service dependency not available")
logging.Error("Database", err, "Failed to connect to database")

## Custom Output Writer

// CLI mode with custom writer
logFile, _ := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
logging.InitForCLI(logging.LevelDebug, logFile)

Subsystem Organization

Logs are organized by subsystem to enable filtering and categorization:

  • **Bootstrap**: Application initialization and startup
  • **Config**: Configuration loading and validation
  • **Orchestrator**: Service lifecycle management
  • **Aggregator**: MCP tool aggregation and management
  • **Workflow**: Workflow execution and management
  • **Agent**: MCP agent and client operations
  • **API**: API layer operations and handler management

Integration with slog

The logging system integrates with Go's standard slog package:

  • Uses slog.Handler implementations for output formatting
  • Converts custom LogLevel to slog.Level for compatibility
  • Provides fallback to global slog logger when needed

Controller-Runtime Integration

The logging system automatically initializes the controller-runtime logger when InitForCLI is called. This ensures that Kubernetes controller-runtime operations (informers, caches, etc.) log through the muster logging infrastructure without warnings about uninitialized loggers.

Performance Characteristics

  • Direct write to output with minimal overhead
  • Level filtering at handler level for efficiency
  • No memory allocation for filtered-out messages

Thread Safety

The logging system is fully thread-safe:

  • Safe concurrent logging from multiple goroutines
  • Protected access to shared logging state
  • No data races in configuration

Audit Logging

The package provides specialized audit logging for security-sensitive operations:

logging.Audit(logging.AuditEvent{
    Action:    "token_exchange",
    Outcome:   "success",
    Subject:   logging.TruncateIdentifier(sub),
    Target:    "mcp-kubernetes",
})

Audit events are logged at INFO level with an [AUDIT] prefix for easy filtering by log aggregation systems.

The logging package provides a robust foundation for muster's diagnostic and monitoring capabilities.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Audit

func Audit(event AuditEvent)

Audit logs a structured audit event for security-sensitive operations. Audit events are always logged at INFO level and include a special [AUDIT] prefix to make them easily filterable by log aggregation systems.

Example output: [AUDIT] action=token_exchange outcome=success subject=abc12345... user=xyz789... target=mcp-kubernetes

func Debug

func Debug(subsystem string, messageFmt string, args ...interface{})

Debug logs a debug message.

func DebugCtx added in v0.1.165

func DebugCtx(ctx context.Context, subsystem string, messageFmt string, args ...interface{})

DebugCtx is like Debug but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func DebugWithAttrs added in v0.1.77

func DebugWithAttrs(subsystem string, msg string, attrs ...slog.Attr)

DebugWithAttrs logs a debug message with additional structured attributes.

func DebugWithAttrsCtx added in v0.1.165

func DebugWithAttrsCtx(ctx context.Context, subsystem string, msg string, attrs ...slog.Attr)

DebugWithAttrsCtx is like DebugWithAttrs but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func Error

func Error(subsystem string, err error, messageFmt string, args ...interface{})

Error logs an error message.

func ErrorCtx added in v0.1.165

func ErrorCtx(ctx context.Context, subsystem string, err error, messageFmt string, args ...interface{})

ErrorCtx is like Error but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func Info

func Info(subsystem string, messageFmt string, args ...interface{})

Info logs an informational message.

func InfoCtx added in v0.1.165

func InfoCtx(ctx context.Context, subsystem string, messageFmt string, args ...interface{})

InfoCtx is like Info but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func InfoWithAttrs added in v0.1.76

func InfoWithAttrs(subsystem string, msg string, attrs ...slog.Attr)

InfoWithAttrs logs an informational message with additional structured attributes.

func InfoWithAttrsCtx added in v0.1.163

func InfoWithAttrsCtx(ctx context.Context, subsystem string, msg string, attrs ...slog.Attr)

InfoWithAttrsCtx is like InfoWithAttrs but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func InitForCLI

func InitForCLI(filterLevel LogLevel, output io.Writer)

InitForCLI initializes the logging system for CLI mode with text output, no OpenTelemetry plumbing. Use Init from the serve composition root for OTLP-aware initialisation.

Args:

  • filterLevel: minimum log level to output (Debug, Info, Warn, Error)
  • output: writer for log output (typically os.Stdout or os.Stderr)

func TransportSessionID added in v0.1.76

func TransportSessionID(id string) slog.Attr

TransportSessionID returns a slog.Attr with key "transportSessionID" and a truncated MCP transport session ID. The last UUID group is replaced with "..." to preserve enough of the ID for log correlation while avoiding logging the full value. Format: "mcp-session-ffa8afa1-eb56-4692-98d2-d6dbc99d4a06" → "mcp-session-ffa8afa1-eb56-4692-98d2-..."

func TruncateIdentifier added in v0.1.50

func TruncateIdentifier(id string) string

TruncateIdentifier returns a truncated identifier (user subject, session ID, etc.) for secure logging. This prevents full identifiers from appearing in logs while still providing enough context for debugging correlation. Format: first 8 chars + "..." (e.g., "abc12345...")

func Warn

func Warn(subsystem string, messageFmt string, args ...interface{})

Warn logs a warning message.

func WarnCtx added in v0.1.165

func WarnCtx(ctx context.Context, subsystem string, messageFmt string, args ...interface{})

WarnCtx is like Warn but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

func WarnWithAttrs added in v0.1.76

func WarnWithAttrs(subsystem string, msg string, attrs ...slog.Attr)

WarnWithAttrs logs a warning message with additional structured attributes.

func WarnWithAttrsCtx added in v0.1.165

func WarnWithAttrsCtx(ctx context.Context, subsystem string, msg string, attrs ...slog.Attr)

WarnWithAttrsCtx is like WarnWithAttrs but threads ctx through the slog Handler so an active span's TraceID and SpanID are attached to the record in OTLP mode.

Types

type AuditEvent

type AuditEvent struct {
	// Action is the type of action being audited (e.g., "token_exchange", "auth_login")
	Action string
	// Outcome indicates whether the action succeeded or failed
	Outcome string // "success" or "failure"
	// Subject is the truncated user subject (sub claim from JWT)
	Subject string
	// UserID is the truncated user identifier (from JWT sub claim or extracted user ID)
	UserID string
	// Target is the target of the action (e.g., server name, endpoint)
	Target string
	// Details provides additional context-specific information
	Details string
	// Error contains the error message if Outcome is "failure"
	Error string
}

AuditEvent represents a structured audit log event for security-sensitive operations. These events can be collected by external audit systems for compliance monitoring.

type LogLevel

type LogLevel int

LogLevel defines the severity of the log entry.

const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError
)

func (LogLevel) SlogLevel

func (l LogLevel) SlogLevel() slog.Level

type Shutdown added in v0.1.165

type Shutdown func(ctx context.Context) error

Shutdown drains the underlying OpenTelemetry LoggerProvider on graceful exit. In non-OTLP modes it is a no-op closure. Safe to call more than once and from multiple goroutines.

func Init added in v0.1.165

func Init(ctx context.Context, filterLevel LogLevel, output io.Writer, serviceName, serviceVersion string) (Shutdown, error)

Init initialises the logging system in OpenTelemetry-aware mode and returns a Shutdown that drains the LoggerProvider on graceful exit.

When any of OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_ENDPOINT, or OTEL_LOGS_EXPORTER is set, log records flow through OTLP and carry the active span's TraceID and SpanID (the OTel SDK pulls SpanContext from the ctx passed into InfoCtx / InfoWithAttrsCtx / etc.). Otherwise the handler is JSON inside a Kubernetes pod (KUBERNETES_SERVICE_HOST set), text otherwise — and Shutdown is a no-op closure.

serviceName and serviceVersion become semconv.ServiceName / semconv.ServiceVersion on the OTel LoggerProvider's Resource; standard env overrides (OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES) take precedence.

Jump to

Keyboard shortcuts

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