Documentation
¶
Overview ¶
Package logging provides structured logging configuration and management.
It wraps zerolog to provide:
- Configurable log levels (trace, debug, info, warn, error, fatal, panic) - File output with automatic rotation via lumberjack - Console output with pretty formatting when attached to a terminal - Configuration via Config structs and functional options
Basic Usage ¶
Configure logging from a config struct:
cfg := logging.Config{
Level: "debug",
File: "~/.app/logs/app.log",
MaxSize: 100, // MB
MaxBackups: 3, // number of backups
MaxAge: 7, // days
Compress: true,
}
logging.ConfigureCmdLogger(cfg)
Then use the global zerolog logger:
import "github.com/rs/zerolog/log"
log.Info().Msg("application started")
log.Debug().Str("user", "alice").Int("count", 42).Msg("event occurred")
log.Error().Err(err).Msg("operation failed")
Log Levels ¶
Supported log levels in order of severity:
- trace: most verbose, detailed tracing information
- debug: debug information for developers
- info: general informational messages
- warn: warning messages for potentially problematic situations
- error: error messages for failure conditions
- fatal: fatal errors that cause application shutdown
- panic: panic-level messages
Configuration ¶
Config struct fields:
type Config struct {
Level string // Log level: trace, debug, info, warn, error, fatal, panic
File string // File path for log output (empty = stdout only)
MaxSize int // Max size of log file in MB before rotation
MaxAge int // Max age of log file in days before deletion
MaxBackups int // Max number of old log files to keep
LocalTime bool // Use local time in rotated filename timestamps
Compress bool // Compress old log files
Mode string // Not currently used, reserved for future use
}
File Rotation ¶
When File is configured, logs are written to a file with automatic rotation based on:
- MaxSize: File is rotated when it exceeds this size
- MaxAge: Rotated files are deleted after this many days
- MaxBackups: Only this many old files are retained
- Compress: Old rotated files are gzip-compressed if true
Example configuration for production:
cfg := logging.Config{
Level: "info",
File: "/var/log/myapp/app.log",
MaxSize: 500, // Rotate every 500MB
MaxBackups: 10, // Keep 10 old files
MaxAge: 30, // Delete files older than 30 days
Compress: true, // Compress rotated files
}
logging.ConfigureCmdLogger(cfg)
Output Behavior ¶
The library intelligently selects output format:
- Console (TTY): Pretty-printed JSON with timestamps
- File/Pipe: Compact JSON for easy parsing
Functional Options ¶
Configure default log levels with options:
logging.ConfigureCmdLogger( cfg, logging.WithDefaultLogLevel(zerolog.DebugLevel), )
Path Expansion ¶
File paths support home directory expansion:
cfg.File = "~/logs/app.log" // Automatically expands to user's home dir
See Also ¶
Package rs/zerolog: structured JSON logging for Go - https://github.com/rs/zerolog Package lumberjack: log file rotation and management - https://gopkg.in/natefinch/lumberjack.v2
Index ¶
- Constants
- func ConfigureCmdLogger(c Config, opts ...Option)
- func ConfigureLogFileOutput(c Config) io.Writer
- func ConfigureLogLevel(levelString string, defaultLogLevel zerolog.Level)
- func ConfigureLogOutput(c Config)
- func FatalError(err error)
- func WithDefaultLogLevel(level zerolog.Level) func(*Config)
- type Config
- type Option
Examples ¶
Constants ¶
const ( // DefaultLogLevel is the default logging level when none is configured. DefaultLogLevel = zerolog.WarnLevel )
Variables ¶
This section is empty.
Functions ¶
func ConfigureCmdLogger ¶
ConfigureCmdLogger configures the global zerolog logger with the provided settings and options.
It applies all options, then sets up log level and output configuration. This is the main entry point for logging setup in CLI applications.
Example ¶
ExampleConfigureCmdLogger demonstrates configuring the command logger.
package main
import (
"fmt"
"github.com/dioad/cli/logging"
)
func main() {
cfg := logging.Config{
Level: "info",
MaxSize: 100,
MaxBackups: 3,
}
logging.ConfigureCmdLogger(cfg)
fmt.Println("Command logger configured")
}
Output: Command logger configured
func ConfigureLogFileOutput ¶
ConfigureLogFileOutput creates and returns a rotated file writer using lumberjack.
The provided Config struct must specify the File path and optional rotation settings. File paths support home directory expansion (e.g., "~/.app/logs/app.log").
func ConfigureLogLevel ¶
ConfigureLogLevel sets the global log level for zerolog.
If levelString is empty or invalid, defaultLogLevel is used. Valid levels: trace, debug, info, warn, error, fatal, panic.
Example ¶
ExampleConfigureLogLevel demonstrates setting the log level.
package main
import (
"fmt"
"github.com/dioad/cli/logging"
"github.com/rs/zerolog"
)
func main() {
logging.ConfigureLogLevel("info", zerolog.WarnLevel)
fmt.Println("Log level configured to info")
}
Output: Log level configured to info
func ConfigureLogOutput ¶
func ConfigureLogOutput(c Config)
ConfigureLogOutput sets up the global zerolog logger output.
If stdout is a TTY (terminal), output is formatted as pretty-printed JSON. If a log file is configured, output is directed to the file with rotation. Otherwise, output is directed to stdout as compact JSON.
Example ¶
ExampleConfigureLogOutput demonstrates configuring log output.
package main
import (
"fmt"
"github.com/dioad/cli/logging"
)
func main() {
cfg := logging.Config{
Level: "debug",
}
logging.ConfigureLogOutput(cfg)
fmt.Println("Log output configured")
}
Output: Log output configured
func FatalError ¶
func FatalError(err error)
FatalError logs an error with fatal level and exits the program.
func WithDefaultLogLevel ¶
WithDefaultLogLevel returns an Option that sets a default log level if one isn't already configured.
This option is useful for providing application-level defaults that won't override explicit configuration from config files or environment variables.
Example ¶
ExampleWithDefaultLogLevel demonstrates using a default log level option.
package main
import (
"fmt"
"github.com/dioad/cli/logging"
"github.com/rs/zerolog"
)
func main() {
cfg := logging.Config{
Level: "",
}
opt := logging.WithDefaultLogLevel(zerolog.DebugLevel)
opt(&cfg)
fmt.Printf("Default level applied: %s\n", cfg.Level)
}
Output: Default level applied: debug
Types ¶
type Config ¶
type Config struct {
// Level specifies the logging level: trace, debug, info, warn, error, fatal, panic.
// Empty string defaults to application-configured level or zerolog.WarnLevel.
Level string `mapstructure:"level"`
// File specifies the path to the log file. Supports home directory expansion (~).
// Empty string disables file logging (logs to stdout only).
File string `mapstructure:"file"`
// MaxSize is the maximum size of the log file in MB before rotation occurs.
// Default is 100 MB.
MaxSize int `mapstructure:"max-size"`
// MaxAge is the maximum number of days to keep old log files.
// Default is 0 (no limit).
MaxAge int `mapstructure:"max-age"`
// MaxBackups is the maximum number of old log files to retain.
// Default is 0 (keep all).
MaxBackups int `mapstructure:"max-backups"`
// LocalTime determines if rotated filenames use local time instead of UTC.
// Default is false.
LocalTime bool `mapstructure:"use-local-time"`
// Compress determines if old log files are gzip-compressed after rotation.
// Default is false.
Compress bool `mapstructure:"compress"`
// Mode is reserved for future use.
Mode string `mapstructure:"mode"`
}
Config contains all configuration options for logging behavior.
Fields support struct tags for configuration file unmarshaling:
type MyConfig struct {
Logging Config `mapstructure:"log"`
}
YAML Example:
log: level: debug file: "~/.app/logs/app.log" max-size: 100 max-backups: 3 max-age: 7 use-local-time: false compress: true
Example ¶
ExampleConfig demonstrates creating a logging configuration.
package main
import (
"fmt"
"github.com/dioad/cli/logging"
)
func main() {
cfg := logging.Config{
Level: "debug",
File: "~/.app/logs/app.log",
MaxSize: 100,
MaxBackups: 3,
MaxAge: 7,
Compress: true,
}
fmt.Printf("Logging level: %s\n", cfg.Level)
fmt.Printf("Max file size: %d MB\n", cfg.MaxSize)
}
Output: Logging level: debug Max file size: 100 MB