Documentation
¶
Overview ¶
Package log provides a unified logging interface for all Kubernaut services.
Authority: DD-005 v2.0 (Observability Standards - Unified Logging Interface)
This package provides: - logr.Logger as the unified interface across all services - zap as the high-performance backend via zapr adapter - Consistent configuration for production and development - Helper functions for common logging patterns
Usage:
Stateless HTTP Services (Gateway, Data Storage, Context API):
logger := log.NewLogger(log.Options{
Development: false,
Level: 0, // INFO
})
defer log.Sync(logger)
// Pass to components
server := NewServer(cfg, logger.WithName("server"))
handler := NewHandler(logger.WithName("handler"))
CRD Controllers:
// Use native logr from controller-runtime
logger := ctrl.Log.WithName("notification-controller")
// Pass to shared libraries (compatible interface)
auditStore := audit.NewBufferedStore(client, config, "notification", logger.WithName("audit"))
Shared Libraries (pkg/*):
// Accept logr.Logger - works with both stateless services and CRD controllers
func NewComponent(logger logr.Logger) *Component {
return &Component{logger: logger.WithName("component")}
}
Index ¶
Constants ¶
const ( // Request tracing fields KeyRequestID = "request_id" KeyTraceID = "trace_id" KeySpanID = "span_id" // Service identification KeyService = "service" KeyComponent = "component" KeyEnvironment = "environment" KeyVersion = "version" KeyGitCommit = "git_commit" KeyBuildDate = "build_date" // Kubernetes context KeyNamespace = "namespace" KeyPodName = "pod_name" KeyNodeName = "node_name" KeyCluster = "cluster" KeyController = "controller" // HTTP request fields KeyMethod = "method" KeyEndpoint = "endpoint" KeyPath = "path" KeyStatusCode = "status_code" KeySourceIP = "source_ip" KeyUserAgent = "user_agent" // Performance metrics KeyDurationMS = "duration_ms" KeyDurationSeconds = "duration_seconds" KeyBytesProcessed = "bytes_processed" KeyRetryCount = "retry_count" // Business domain fields KeySignalName = "signal_name" KeyFingerprint = "fingerprint" KeySeverity = "severity" KeyWorkflowID = "workflow_id" KeyWorkflowName = "workflow_name" KeyWorkflowVersion = "workflow_version" KeyIncidentType = "incident_type" KeyRemediationID = "remediation_id" KeyCorrelationID = "correlation_id" KeyAlertFingerprint = "alert_fingerprint" // Database fields KeyDatabase = "database" KeyTable = "table" KeyQuery = "query" KeyRowCount = "row_count" KeyOperation = "operation" // Error fields KeyError = "error" KeyErrorCode = "error_code" KeyErrorType = "error_type" KeyStackTrace = "stack_trace" // Audit fields KeyEventType = "event_type" KeyOutcome = "outcome" KeyActor = "actor" KeyResource = "resource" KeyAction = "action" // Graceful shutdown fields (DD-007) KeyPhase = "phase" KeyStatus = "status" )
Standard field keys for structured logging.
DD-005: Use these constants to ensure consistent field names across all services. This enables effective log aggregation and querying in production.
Example:
logger.Info("Request processed",
log.KeyRequestID, requestID,
log.KeyDurationMS, durationMs,
log.KeyStatusCode, statusCode,
)
const ( // Outcomes OutcomeSuccess = "success" OutcomeFailure = "failure" OutcomeSkipped = "skipped" // Phases (DD-007 graceful shutdown) PhaseStartup = "startup" PhaseRunning = "running" PhaseShutdown = "shutdown" PhaseEndpointRemoval = "endpoint_removal" PhaseDrainingConns = "draining_connections" PhaseClosingResources = "closing_resources" PhaseShutdownComplete = "shutdown_complete" // Statuses StatusHealthy = "healthy" StatusUnhealthy = "unhealthy" StatusDegraded = "degraded" StatusReady = "ready" StatusNotReady = "not_ready" )
Standard field values for common scenarios.
Variables ¶
This section is empty.
Functions ¶
func GetZapLogger ¶
GetZapLogger extracts the underlying *zap.Logger from a logr.Logger.
This is useful for interoperability with libraries that require *zap.Logger. Returns nil if the logger is not backed by zap.
DD-005: Migration helper - use sparingly, prefer logr.Logger interface
Example:
logger := log.NewLogger(opts)
zapLogger := log.GetZapLogger(logger)
if zapLogger != nil {
// Use with legacy code that requires *zap.Logger
legacyComponent := NewLegacyComponent(zapLogger)
}
func NewLogger ¶
NewLogger creates a new logr.Logger with the specified options.
DD-005 v2.0: This is the primary way to create loggers for stateless services. CRD controllers should use ctrl.Log from controller-runtime instead.
Example:
logger := log.NewLogger(log.Options{
Development: false,
Level: 0,
ServiceName: "data-storage",
})
defer log.Sync(logger)
func NewLoggerFromEnvironment ¶
NewLoggerFromEnvironment creates a logger configured from environment variables.
Environment variables: - LOG_LEVEL: "debug", "info", "warn", "error" (default: "info") - LOG_FORMAT: "json", "console" (default: "json") - SERVICE_NAME: Service identifier for logs
DD-005: Environment-driven configuration for Kubernetes deployments
Types ¶
type Options ¶
type Options struct {
// Development enables development mode with human-readable output.
// Default: false (production mode with JSON output)
Development bool
// Level sets the minimum logging level.
// DD-005 verbosity levels:
// - 0 = INFO (default, always shown)
// - 1 = DEBUG (shown when verbosity >= 1)
// - 2 = TRACE (shown when verbosity >= 2)
//
// In production, use 0. In development, use 1 or 2.
Level int
// ServiceName is added to all log entries for identification.
// Example: "gateway", "data-storage", "notification-controller"
ServiceName string
// DisableCaller disables caller information in log entries.
// Default: false (caller info enabled)
DisableCaller bool
// DisableStacktrace disables stack traces for error-level logs.
// Default: false (stack traces enabled for errors)
DisableStacktrace bool
}
Options configures the logger behavior.
DD-005: Standard configuration options for all services
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions returns production-ready default options.
DD-005: Production defaults - JSON output format - INFO level (V=0) - Caller info enabled - Stack traces enabled for errors
func DevelopmentOptions ¶
func DevelopmentOptions() Options
DevelopmentOptions returns development-friendly options.
DD-005: Development defaults - Human-readable console output - DEBUG level (V=1) - Caller info enabled - Stack traces enabled for errors