logging

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package logging provides structured logging utilities for AICR components.

Overview

This package wraps the standard library slog package with AICR-specific defaults and conventions for consistent logging across all components. It supports three logging modes: structured JSON (machine-readable), text with metadata (debugging), and CLI (user-friendly minimal output).

Features

  • Three logging modes: JSON, Text, CLI
  • CLI mode: Minimal output with ANSI color support (red for errors)
  • Structured JSON logging to stderr
  • Text logging with full metadata for debugging
  • Environment-based log level configuration (LOG_LEVEL)
  • Automatic module and version context
  • Source location tracking for debug logs
  • Flexible log level parsing
  • Integration with standard library log package

Log Levels

Supported log levels (case-insensitive):

  • DEBUG: Detailed diagnostic information with source location
  • INFO: General informational messages (default)
  • WARN/WARNING: Warning messages for potentially problematic situations
  • ERROR: Error messages for failures requiring attention

Usage

Logging Modes

The package provides three logging modes:

1. **CLI Mode (default for CLI applications)**: Minimal user-friendly output

logging.SetDefaultCLILogger(slog.LevelInfo)
slog.Info("Snapshot captured successfully")  // Output: Snapshot captured successfully
slog.Error("Failed to connect")              // Output: Failed to connect (in red)

2. **Text Mode (--debug flag)**: Human-readable with metadata

logging.SetDefaultLoggerWithLevel("aicr", "v1.0.0", "debug")
// Output: time=2025-01-06T10:30:00.123Z level=INFO module=aicr version=v1.0.0 msg="server started"

3. **JSON Mode (--log-json flag)**: Machine-readable structured logs

logging.SetDefaultStructuredLogger("aicr", "v1.0.0")
// Output: {"time":"2025-01-06T10:30:00.123Z","level":"INFO","module":"aicr","version":"v1.0.0","msg":"server started"}

Setting the default logger (CLI mode for user-facing tools):

func main() {
    logging.SetDefaultCLILogger(slog.LevelInfo)
    slog.Info("application started")

    // Errors display in red
    if err != nil {
        slog.Error("operation failed")
    }
}

Creating a custom structured logger for API servers:

logging.SetDefaultStructuredLoggerWithLevel("api-server", "v2.0.0", "debug")
logger.Debug("server starting", "port", 8080)

Setting explicit log level:

logging.SetDefaultStructuredLoggerWithLevel("cli", "v1.0.0", "warn")

Converting standard library logger:

logging.SetDefaultLoggerWithLevel("myapp", "v1.0.0", "info")
stdLogger.Println("legacy log message")

Environment Configuration

The LOG_LEVEL environment variable controls logging verbosity:

LOG_LEVEL=debug aicr snapshot
LOG_LEVEL=error aicrd

If LOG_LEVEL is not set, defaults to INFO level.

Output Format

Output format depends on the logging mode:

**CLI Mode (default)**: Minimal output, just message text

Snapshot captured successfully
Failed to connect  (in red ANSI color)

**Text Mode (--debug)**: Key=value format with metadata

time=2025-01-06T10:30:00.123Z level=INFO module=aicr version=v1.0.0 msg="server started" port=8080

**JSON Mode (--log-json)**: Structured JSON to stderr

{
    "time": "2025-01-06T10:30:00.123Z",
    "level": "INFO",
    "msg": "server started",
    "module": "api-server",
    "version": "v1.0.0",
    "port": 8080
}

Debug logs in JSON mode include source location:

{
    "time": "2025-01-06T10:30:00.123Z",
    "level": "DEBUG",
    "source": {
        "function": "main.processRequest",
        "file": "server.go",
        "line": 45
    },
    "msg": "processing request",
    "module": "api-server",
    "version": "v1.0.0"
}

Best Practices

1. Set default logger early in main() based on application type:

// CLI applications: Use CLI logger for user-friendly output
func main() {
    logging.SetDefaultCLILogger(slog.LevelInfo)
    slog.Info("application started")
    // ...
}

// API servers: Use structured JSON logger
func main() {
    logging.SetDefaultStructuredLogger("myapp", version)
    slog.Info("application started")
    // ...
}

2. Include context in log messages:

slog.Debug("request processed",
    "method", "GET",
    "path", "/api/v1/resources",
    "duration_ms", 125,
)

3. Use appropriate log levels:

slog.Debug("cache hit", "key", key)  // Development/troubleshooting
slog.Debug("server started")          // Normal operations
slog.Warn("retry attempt 3")         // Potential issues
slog.Error("db connection failed")   // Errors requiring action

4. Log errors with context:

slog.Error("failed to process request",
    "error", err,
    "request_id", requestID,
    "retry_count", retries,
)

Integration

This package is used by:

  • pkg/api - API server logging
  • pkg/cli - CLI command logging
  • pkg/collector - Data collection logging
  • pkg/snapshotter - Snapshot operation logging
  • pkg/recipe - Recipe generation logging

All components share consistent logging format and configuration.

Index

Constants

View Source
const (
	// EnvVarLogLevel is the environment variable name for setting the log level.
	EnvVarLogLevel = "LOG_LEVEL"
)
View Source
const LogPrefixEnvVar = "AICR_LOG_PREFIX"

LogPrefixEnvVar is the environment variable name for customizing the log prefix.

Variables

This section is empty.

Functions

func ParseLogLevel

func ParseLogLevel(level string) slog.Level

ParseLogLevel converts a string representation of a log level into a slog.Level. Parameters:

  • level: The log level as a string (e.g., "debug", "info", "warn", "error").

Returns:

  • slog.Level corresponding to the input string. Defaults to slog.LevelInfo for unrecognized strings.

func SetDefaultCLILogger

func SetDefaultCLILogger(level string)

SetDefaultCLILogger initializes the CLI logger with the appropriate log level and sets it as the default logger. Parameters:

  • level: The log level as a string (e.g., "debug", "info", "warn", "error").

func SetDefaultLoggerWithLevel

func SetDefaultLoggerWithLevel(module, version, level string)

SetDefaultLoggerWithLevel initializes the text logger with the specified log level and sets it as the default logger. Defined module name and version are included in the logger's context. Parameters:

  • module: The name of the module/application using the logger.
  • version: The version of the module/application (e.g., "v1.0.0").
  • level: The log level as a string (e.g., "debug", "info", "warn", "error").

func SetDefaultStructuredLogger

func SetDefaultStructuredLogger(module, version string)

SetDefaultStructuredLogger initializes the structured logger with the appropriate log level and sets it as the default logger. Defined module name and version are included in the logger's context. Parameters:

  • module: The name of the module/application using the logger.
  • version: The version of the module/application (e.g., "v1.0.0").

Derives log level from the LOG_LEVEL environment variable.

func SetDefaultStructuredLoggerWithLevel

func SetDefaultStructuredLoggerWithLevel(module, version, level string)

SetDefaultStructuredLoggerWithLevel initializes the structured logger with the specified log level Defined module name and version are included in the logger's context. Parameters:

  • module: The name of the module/application using the logger.
  • version: The version of the module/application (e.g., "v1.0.0").
  • level: The log level as a string (e.g., "debug", "info", "warn", "error").

Types

type CLIHandler

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

CLIHandler is a custom slog.Handler for CLI output. It formats log messages in a user-friendly way: - Non-error messages: just the message text - Error messages: message text in red

func NewCLIHandler

func NewCLIHandler(w io.Writer, level slog.Level) *CLIHandler

NewCLIHandler creates a new CLI handler that writes to the given writer.

func (*CLIHandler) Enabled

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

Enabled returns true if the handler handles records at the given level.

func (*CLIHandler) Handle

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

Handle formats and writes the log record with attributes.

func (*CLIHandler) WithAttrs

func (h *CLIHandler) WithAttrs(_ []slog.Attr) slog.Handler

WithAttrs returns a new handler with the given attributes. For CLI handler, we ignore attributes for simplicity.

func (*CLIHandler) WithGroup

func (h *CLIHandler) WithGroup(_ string) slog.Handler

WithGroup returns a new handler with the given group. For CLI handler, we ignore groups for simplicity.

Jump to

Keyboard shortcuts

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