logging

package
v5.44.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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/v5/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

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

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

DebugWithAttrs logs a debug message with additional structured attributes.

func DebugWithAttrsCtx

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

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 FormatGroup

func FormatGroup(name string, v slog.Value) string

FormatGroup renders a slog group value as "name{key=value key=value}" so a type can implement fmt.Stringer on top of its slog.LogValuer. Types that carry credentials use it so that %v and structured attrs agree on the redacted view instead of fmt falling back to the raw struct layout.

func Info

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

Info logs an informational message.

func InfoCtx

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

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

InfoWithAttrs logs an informational message with additional structured attributes.

func InfoWithAttrsCtx

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 KeyNames

func KeyNames[V any](m map[string]V) string

KeyNames renders the keys of a map, sorted and comma-separated, for log lines that must say which fields were present without printing what they held. Tool arguments and results are user data and can carry credentials (a token passed as a workflow input, a secret returned by a step), so a debug line names the keys and leaves the values out. An empty or nil map renders as "none".

func RedactSecret

func RedactSecret(text, secret string) string

RedactSecret replaces every occurrence of secret in text with a length-only marker. Use it on error strings produced by code that embeds the key it looked up -- a token store reporting "token not found: <bearer>" -- before they reach a log line. An empty secret leaves text unchanged.

func Shape

func Shape(v any) string

Shape describes a decoded JSON value for log lines without printing its contents: objects list their sorted keys, arrays and strings their length, everything else its Go type. Use it where a debug line used to dump user data with %v.

func TransportSessionID

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

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

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

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

WarnWithAttrs logs a warning message with additional structured attributes.

func WarnWithAttrsCtx

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

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

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.

In OTLP mode records are also written as JSON to os.Stderr, so kubectl logs keeps working and a collector outage loses nothing locally, unless output is io.Discard (silent mode).

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