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:
logger := logging.NewStructuredLogger("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:
stdLogger := logging.NewLogLogger(slog.LevelInfo, false)
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
- func NewCLILogger(level string) *slog.Logger
- func NewLogLogger(module, version, level string) *log.Logger
- func NewStructuredLogger(module, version, level string) *slog.Logger
- func NewTextLogger(module, version, level string) *slog.Logger
- func ParseLogLevel(level string) slog.Level
- func SetDefaultCLILogger(level string)
- func SetDefaultLogger(module, version string)
- func SetDefaultLoggerWithLevel(module, version, level string)
- func SetDefaultStructuredLogger(module, version string)
- func SetDefaultStructuredLoggerWithLevel(module, version, level string)
- type CLIHandler
Constants ¶
const (
// EnvVarLogLevel is the environment variable name for setting the log level.
EnvVarLogLevel = "LOG_LEVEL"
)
const LogPrefixEnvVar = "AICR_LOG_PREFIX"
LogPrefixEnvVar is the environment variable name for customizing the log prefix.
Variables ¶
This section is empty.
Functions ¶
func NewCLILogger ¶
NewCLILogger creates a new logger with CLI-friendly output format. This logger outputs minimal, user-friendly messages: - Normal messages: just the message text - Error messages: message text in red color Parameters:
- level: The log level as a string (e.g., "debug", "info", "warn", "error").
Returns:
- *slog.Logger: A pointer to the configured slog.Logger instance with CLI handler.
func NewLogLogger ¶
NewLogLogger creates a new standard library log.Logger that writes logs using the slog package with the specified log level. Parameters:
- level: The log level as a slog.Level.
Returns:
- *log.Logger: A pointer to the configured log.Logger instance.
func NewStructuredLogger ¶
NewStructuredLogger creates a new structured logger with the specified log level Defined module name and version are included in the logger's context. AddSource is enabled for debug level logging only. 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").
Returns:
- *slog.Logger: A pointer to the configured slog.Logger instance.
func NewTextLogger ¶
NewTextLogger creates a new text logger with the specified log level Defined module name and version are included in the logger's context. AddSource is enabled for debug level logging only. 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").
Returns:
- *slog.Logger: A pointer to the configured slog.Logger instance with text handler.
func ParseLogLevel ¶
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 SetDefaultLogger ¶
func SetDefaultLogger(module, version string)
SetDefaultLogger initializes the text 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 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 ¶
Enabled returns true if the handler handles records at the given level.