Documentation
¶
Overview ¶
Package log provides a high-performance, structured logging facility for Go applications.
This package is built on top of the zap logging library (go.uber.org/zap) and provides enhanced usability features with a simplified interface. It supports various log levels, structured logging with key-value pairs, and different output formats.
Features:
- Multiple log levels: Debug, Info, Warn, Error, Panic, Fatal
- Structured logging with key-value pairs
- Printf-style logging with format strings
- Println-style logging
- JSON and console output formats
- Configurable console output (can be disabled independently of file logging)
- Configurable time layout
- Log file rotation by date
- Separate error log files
- Optional caller information and stack traces
- Environment presets for development, production, and testing
- Builder pattern for fluent configuration
- Multi-format configuration support (YAML, JSON, TOML) via Viper
- HTTP middleware for request/response logging
- Performance optimizations (buffering, sampling)
Quick Start:
// Zero-configuration quick start
logger := log.Quick()
logger.Info("Hello, World!")
// Use environment presets
devLogger := log.WithPreset(log.DevelopmentPreset())
prodLogger := log.WithPreset(log.ProductionPreset())
// Builder pattern for custom configuration
logger := log.NewBuilder().
Level("debug").
Format("json").
Directory("./logs").
ConsoleOutput(false). // Disable console output
Build()
Structured Logging:
// Structured logging with key-value pairs
logger.Infow("User logged in", "user_id", 123, "ip", "192.168.1.1")
logger.Errorw("Database connection failed", "error", err, "retry", true)
// Format string logging
logger.Debugf("Processing item %d of %d", i, total)
logger.Errorf("Failed to connect to %s: %v", host, err)
Configuration: The logger can be configured through multiple methods and formats:
// Multi-format configuration (powered by Viper)
logger, err := log.FromConfigFile("config.yaml") // YAML format
logger, err := log.FromConfigFile("config.json") // JSON format
logger, err := log.FromConfigFile("config.toml") // TOML format
// Direct options loading
opts, err := log.LoadFromFile("config.yaml")
logger := log.NewLog(opts)
// Traditional options
logger := log.NewLog(log.NewOptions().
WithLevel("debug").
WithFormat("json").
WithDirectory("./logs").
WithConsoleOutput(false)) // Disable console output
HTTP Middleware:
middleware := log.HTTPMiddleware(logger)
http.Handle("/api", middleware(handler))
Utility Functions:
import "github.com/kydenul/log/logutil" // Error handling logutil.LogError(logger, err, "Operation failed") logutil.FatalOnError(logger, err, "Critical error") // Performance timing defer logutil.Timer(logger, "operation_name")() // Conditional logging logutil.InfoIf(logger, condition, "Message", "key", "value")
Package log is a log package.
Index ¶
- Constants
- Variables
- func Debug(args ...any)
- func Debugf(template string, args ...any)
- func Debugln(args ...any)
- func Debugw(msg string, keysAndValues ...any)
- func Error(args ...any)
- func Errorf(template string, args ...any)
- func Errorln(args ...any)
- func Errorw(msg string, keysAndValues ...any)
- func Fatal(args ...any)
- func Fatalf(template string, args ...any)
- func Fatalln(args ...any)
- func Fatalw(msg string, keysAndValues ...any)
- func HTTPMiddleware(logger Logger) func(http.Handler) http.Handler
- func Info(args ...any)
- func Infof(template string, args ...any)
- func Infoln(args ...any)
- func Infow(msg string, keysAndValues ...any)
- func IsConfigError(err error) bool
- func Panic(args ...any)
- func Panicf(template string, args ...any)
- func Panicln(args ...any)
- func Panicw(msg string, keysAndValues ...any)
- func ReplaceLogger(l *Log)
- func Sync() error
- func Warn(args ...any)
- func Warnf(template string, args ...any)
- func Warnln(args ...any)
- func Warnw(msg string, keysAndValues ...any)
- type Builder
- func (b *Builder) Build() *Log
- func (b *Builder) Compress(compress bool) *Builder
- func (b *Builder) ConsoleOutput(enable bool) *Builder
- func (b *Builder) Development() *Builder
- func (b *Builder) Directory(dir string) *Builder
- func (b *Builder) DisableCaller(disable bool) *Builder
- func (b *Builder) DisableSplitError(disable bool) *Builder
- func (b *Builder) DisableStacktrace(disable bool) *Builder
- func (b *Builder) Filename(filename string) *Builder
- func (b *Builder) Format(format string) *Builder
- func (b *Builder) Level(level string) *Builder
- func (b *Builder) MaxBackups(backups int) *Builder
- func (b *Builder) MaxSize(size int) *Builder
- func (b *Builder) Prefix(prefix string) *Builder
- func (b *Builder) Production() *Builder
- func (b *Builder) Sampling(enable bool, initial, thereafter int) *Builder
- func (b *Builder) Testing() *Builder
- func (b *Builder) TimeLayout(layout string) *Builder
- type ConfigError
- type Log
- func (l *Log) Debug(args ...any)
- func (l *Log) Debugf(template string, args ...any)
- func (l *Log) Debugln(args ...any)
- func (l *Log) Debugw(msg string, keysAndValues ...any)
- func (l *Log) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)
- func (l *Log) Error(args ...any)
- func (l *Log) Errorf(template string, args ...any)
- func (l *Log) Errorln(args ...any)
- func (l *Log) Errorw(msg string, keysAndValues ...any)
- func (l *Log) Fatal(args ...any)
- func (l *Log) Fatalf(template string, args ...any)
- func (l *Log) Fatalln(args ...any)
- func (l *Log) Fatalw(msg string, keysAndValues ...any)
- func (l *Log) Info(args ...any)
- func (l *Log) Infof(template string, args ...any)
- func (l *Log) Infoln(args ...any)
- func (l *Log) Infow(msg string, keysAndValues ...any)
- func (l *Log) Panic(args ...any)
- func (l *Log) Panicf(template string, args ...any)
- func (l *Log) Panicln(args ...any)
- func (l *Log) Panicw(msg string, keysAndValues ...any)
- func (l *Log) Sync() error
- func (l *Log) Warn(args ...any)
- func (l *Log) Warnf(template string, args ...any)
- func (l *Log) Warnln(args ...any)
- func (l *Log) Warnw(msg string, keysAndValues ...any)
- type Logger
- type Options
- func LoadFromFile(configPath string) (*Options, error)
- func LoadFromJSON(jsonPath string) (*Options, error)
- func LoadFromTOML(tomlPath string) (*Options, error)
- func LoadFromYAML(yamlPath string) (*Options, error)
- func NewOptions() *Options
- func RecoverFromConfigError(err error) *Options
- func ValidateAndFixOptions(opts *Options) *Options
- func ValidateOptions(opts *Options) (*Options, error)
- func (opt *Options) Validate() error
- func (opt *Options) WithCompress(compress bool) *Options
- func (opt *Options) WithConsoleOutput(enable bool) *Options
- func (opt *Options) WithDirectory(dir string) *Options
- func (opt *Options) WithDisableCaller(disableCaller bool) *Options
- func (opt *Options) WithDisableSplitError(disableSplitError bool) *Options
- func (opt *Options) WithDisableStacktrace(disableStacktrace bool) *Options
- func (opt *Options) WithFilename(filename string) *Options
- func (opt *Options) WithFormat(format string) *Options
- func (opt *Options) WithLevel(level string) *Options
- func (opt *Options) WithMaxBackups(maxBackups int) *Options
- func (opt *Options) WithMaxSize(maxSize int) *Options
- func (opt *Options) WithPrefix(prefix string) *Options
- func (opt *Options) WithSampling(enable bool, initial, thereafter int) *Options
- func (opt *Options) WithTimeLayout(timeLayout string) *Options
- type Preset
Examples ¶
Constants ¶
const ( MaxRetries = 3 // Maximum retries for file write operations BriefDelay = time.Millisecond * 10 // Brief delay before retry )
const ( DefaultPrefix = "ZIWI_" DefaultLevel = zapcore.InfoLevel DefaultTimeLayout = "2006-01-02 15:04:05.000" DefaultFormat = "console" // console style DefaultFilename = "" // Default filename prefix DefaultDisableCaller = false DefaultDisableStacktrace = false DefaultDisableSplitError = true DefaultMaxSize = 100 // 100MB DefaultMaxBackups = 3 // Keep 3 old log files DefaultCompress = false // Not compress rotated log files // Defaults for sampling functionality DefaultEnableSampling = false // Sampling disabled by default DefaultSampleInitial = 100 // Initial sample count DefaultSampleThereafter = 100 // Subsequent sample count // Console output control DefaultConsoleOutput = true // Console output enabled by default FormatConsole = "console" FormatJSON = "json" LevelDebug = "debug" LevelInfo = "info" )
const ConfigKey = "KLOG"
ConfigKey is the optional top-level key for nested configuration. When present in the config file, options will be read from under this key. Both formats are supported:
Format 1 - Direct configuration (no top-level key):
prefix: "ZIWI_" level: "info"
Format 2 - Nested configuration (with KLOG key):
KLOG: prefix: "ZIWI_" level: "info"
Variables ¶
var ( ErrInvalidLevel = errors.New("无效的日志级别") ErrInvalidFormat = errors.New("无效的日志格式") ErrInvalidDirectory = errors.New("无效的日志目录") ErrInvalidFilename = errors.New("无效的文件名") ErrPermissionDenied = errors.New("权限被拒绝") ErrInvalidTimeLayout = errors.New("无效的时间格式") ErrInvalidMaxSize = errors.New("无效的最大文件大小") ErrInvalidMaxBackups = errors.New("无效的最大备份数量") ErrInvalidSampling = errors.New("无效的采样配置") )
Predefined error variables for common configuration errors
var DefaultDirectory = func() string { home, err := os.UserHomeDir() if err != nil { return filepath.Join(os.TempDir(), "logs") } return filepath.Join(home, "logs") }()
DefaultDirectory returns the default log directory, which is typically the user's home directory joined with "logs". Falls back to temp directory if home directory cannot be determined.
Functions ¶
func Debugw ¶
Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func Errorw ¶
Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func Fatalw ¶
Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.
func HTTPMiddleware ¶ added in v1.4.0
HTTPMiddleware creates an HTTP middleware that logs request and response information. It logs the start of each request and completion with timing information.
Parameters:
- logger: The Logger instance to use for logging
Returns:
- func(http.Handler) http.Handler: A middleware function that can be used with standard HTTP handlers
Usage:
logger := log.NewLog(log.NewOptions())
middleware := log.HTTPMiddleware(logger)
http.Handle("/", middleware(yourHandler))
Example (Usage) ¶
ExampleHTTPMiddleware_usage shows how to use the HTTP middleware with a real HTTP server
// Create logger
logger := NewLog(NewOptions())
// Create your handlers
helloHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello!"))
})
apiHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "API response"}`))
})
// Create middleware
middleware := HTTPMiddleware(logger)
// Set up routes with middleware
mux := http.NewServeMux()
mux.Handle("/hello", middleware(helloHandler))
mux.Handle("/api/", middleware(apiHandler))
// In a real application, you would start the server like this:
// log.Fatal(http.ListenAndServe(":8080", mux))
fmt.Println("Server configured with logging middleware")
Output: Server configured with logging middleware
func Infow ¶
Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func IsConfigError ¶ added in v1.4.0
IsConfigError checks if an error is a ConfigError
func Panicw ¶
Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.
func ReplaceLogger ¶ added in v1.1.0
func ReplaceLogger(l *Log)
ReplaceLogger replaces the default logger with a new instance
func Sync ¶
func Sync() error
Sync flushes any buffered log entries. Applications should take care to call Sync before exiting. Returns an error if any sync or close operation fails.
Types ¶
type Builder ¶ added in v1.4.0
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent interface for configuring and creating Log instances It wraps the existing Options struct and provides chainable methods for configuration
Example ¶
ExampleBuilder demonstrates basic usage of the Builder pattern
// Create a logger using the builder pattern with method chaining
logger := NewBuilder().
Level("debug").
Format("console").
Directory("./logs").
Filename("myapp").
Prefix("APP_").
Build()
logger.Info("Application started")
logger.Debug("Debug information")
logger.Sync()
Example (CustomConfiguration) ¶
ExampleBuilder_customConfiguration demonstrates advanced configuration
// Create a temporary directory for this example
tempDir := filepath.Join(os.TempDir(), "example_logs")
defer os.RemoveAll(tempDir)
// Custom logger with advanced settings
logger := NewBuilder().
Level("info").
Format("json").
Directory(tempDir).
Filename("custom").
Prefix("CUSTOM_").
MaxSize(50). // 50MB max file size
MaxBackups(3). // Keep 3 backup files
Compress(true). // Compress rotated files
Sampling(true, 100, 1000). // Enable sampling
DisableCaller(false). // Show caller info
Build()
logger.Info("Custom configured logger message")
logger.Warn("Warning message")
logger.Error("Error message")
logger.Sync()
Example (PresetWithOverrides) ¶
ExampleBuilder_presetWithOverrides demonstrates combining presets with custom settings
// Start with production preset and override specific settings
logger := NewBuilder().
Production(). // Start with production defaults
Level("debug"). // Override to debug level
Directory("./custom"). // Override directory
DisableCaller(false). // Enable caller info (overriding production default)
Build()
logger.Debug("Debug message with caller info in production-like setup")
logger.Info("Info message")
logger.Sync()
Example (Presets) ¶
ExampleBuilder_presets demonstrates using presets with the builder
// Development environment logger
devLogger := NewBuilder().
Development().
Directory("./dev_logs").
Build()
devLogger.Debug("Development log message")
// Production environment logger
prodLogger := NewBuilder().
Production().
Directory("./prod_logs").
Filename("production").
Build()
prodLogger.Info("Production log message")
// Testing environment logger
testLogger := NewBuilder().
Testing().
Directory("./logs/test_logs").
Build()
testLogger.Debug("Test log message")
// Sync all loggers
devLogger.Sync()
prodLogger.Sync()
testLogger.Sync()
func NewBuilder ¶ added in v1.4.0
func NewBuilder() *Builder
NewBuilder creates a new Builder instance with default options Returns a Builder that can be used to configure a logger through method chaining
func (*Builder) Build ¶ added in v1.4.0
Build creates and returns a new Log instance with the configured options This method calls the existing NewLog() function with the built options
func (*Builder) Compress ¶ added in v1.4.0
Compress sets whether to compress rotated log files Returns the Builder for method chaining
func (*Builder) ConsoleOutput ¶ added in v1.5.0
ConsoleOutput sets whether to output logs to console When disabled, logs are only written to files Returns the Builder for method chaining
func (*Builder) Development ¶ added in v1.4.0
Development applies the development preset configuration This configures the logger for development environment with debug level, console output, caller info enabled, and fast flush Returns the Builder for method chaining
func (*Builder) Directory ¶ added in v1.4.0
Directory sets the log file directory Returns the Builder for method chaining
func (*Builder) DisableCaller ¶ added in v1.4.0
DisableCaller sets whether to disable caller information Returns the Builder for method chaining
func (*Builder) DisableSplitError ¶ added in v1.4.0
DisableSplitError sets whether to disable separate error log files Returns the Builder for method chaining
func (*Builder) DisableStacktrace ¶ added in v1.4.0
DisableStacktrace sets whether to disable stack traces Returns the Builder for method chaining
func (*Builder) Filename ¶ added in v1.4.0
Filename sets the log filename prefix Returns the Builder for method chaining
func (*Builder) Format ¶ added in v1.4.0
Format sets the log format (console or json) Returns the Builder for method chaining
func (*Builder) Level ¶ added in v1.4.0
Level sets the log level (debug, info, warn, error, dpanic, panic, fatal) Returns the Builder for method chaining
func (*Builder) MaxBackups ¶ added in v1.4.0
MaxBackups sets the maximum number of old log files to retain Returns the Builder for method chaining
func (*Builder) MaxSize ¶ added in v1.4.0
MaxSize sets the maximum size of log files in megabytes before rotation Returns the Builder for method chaining
func (*Builder) Prefix ¶ added in v1.4.0
Prefix sets the log prefix Returns the Builder for method chaining
func (*Builder) Production ¶ added in v1.4.0
Production applies the production preset configuration This configures the logger for production environment with info level, JSON format, optimized for performance and storage Returns the Builder for method chaining
func (*Builder) Sampling ¶ added in v1.4.0
Sampling configures log sampling settings Returns the Builder for method chaining
func (*Builder) Testing ¶ added in v1.4.0
Testing applies the testing preset configuration This configures the logger for testing environment with debug level, simplified output, and minimal file operations Returns the Builder for method chaining
func (*Builder) TimeLayout ¶ added in v1.4.0
TimeLayout sets the time layout format Returns the Builder for method chaining
type ConfigError ¶ added in v1.4.0
type ConfigError struct {
Field string // The configuration field that has an error
Value any // The invalid value
Reason string // Human-readable reason for the error
Wrapped error // The underlying error, if any
}
ConfigError represents a configuration error with detailed information
func GetConfigErrors ¶ added in v1.4.0
func GetConfigErrors(err error) []*ConfigError
GetConfigErrors extracts all ConfigError instances from an error chain
func NewConfigError ¶ added in v1.4.0
func NewConfigError(field string, value any, reason string, wrapped error) *ConfigError
NewConfigError creates a new ConfigError with the specified details
func (*ConfigError) Error ¶ added in v1.4.0
func (e *ConfigError) Error() string
Error implements the error interface
func (*ConfigError) Unwrap ¶ added in v1.4.0
func (e *ConfigError) Unwrap() error
Unwrap returns the wrapped error for error chain support
type Log ¶ added in v1.3.0
Log is the implement of Logger interface. It wraps zap.Logger.
func DefaultLogger ¶ added in v1.1.0
func DefaultLogger() *Log
DefaultLogger returns the default global logger instance
func FromConfigFile ¶ added in v1.4.0
FromConfigFile creates a logger by loading configuration from a YAML file. This is the most convenient way to create a logger with custom configuration. It combines YAML configuration loading and logger creation in one step.
Parameters:
- configPath: Path to the YAML configuration file
Returns:
- *Log: Logger instance configured from the YAML file
- error: Error if file loading, parsing, or logger creation fails
YAML Configuration Guide:
Create a YAML file with your desired configuration options. All Options struct fields are supported via YAML tags. See LoadFromYAML documentation for YAML format examples.
Example Usage:
logger, err := log.FromConfigFile("config.yaml")
if err != nil {
log.Fatal("Failed to load config:", err)
}
logger.Info("Logger loaded from YAML config file")
func NewLog ¶ added in v1.3.0
NewLog creates a new logger instance and sets it as the global default logger. This allows both instance-based calls (logger.Info()) and global calls (log.Info()).
Returns:
- *Log: The new logger instance.
func Quick ¶ added in v1.4.0
func Quick() *Log
Quick creates a logger with default configuration for quick setup. This is the fastest way to get a working logger with sensible defaults.
Returns:
- *Log: Logger instance with default configuration
Example:
logger := log.Quick()
logger.Info("Hello, World!")
func WithPreset ¶ added in v1.4.0
WithPreset creates a logger using a predefined preset configuration. Presets provide optimized settings for common use cases.
Parameters:
- preset: The preset configuration to use
Returns:
- *Log: Logger instance configured with the preset
Example:
devLogger := log.WithPreset(log.DevelopmentPreset()) prodLogger := log.WithPreset(log.ProductionPreset())
func (*Log) Debugf ¶ added in v1.3.0
Debugf formats the message according to the format specifier and logs it.
func (*Log) Debugw ¶ added in v1.3.0
Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*Log) EncodeEntry ¶ added in v1.3.0
EncodeEntry encodes the entry and fields into a buffer.
func (*Log) Errorf ¶ added in v1.3.0
Errorf formats the message according to the format specifier and logs it.
func (*Log) Errorw ¶ added in v1.3.0
Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*Log) Fatalf ¶ added in v1.3.0
Fatalf formats the message according to the format specifier and calls os.Exit.
func (*Log) Fatalw ¶ added in v1.3.0
Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.
func (*Log) Infof ¶ added in v1.3.0
Infof formats the message according to the format specifier and logs it.
func (*Log) Infow ¶ added in v1.3.0
Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*Log) Panicf ¶ added in v1.3.0
Panicf formats the message according to the format specifier and panics.
func (*Log) Panicw ¶ added in v1.3.0
Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.
func (*Log) Sync ¶ added in v1.3.0
Sync flushes any buffered log entries. Applications should take care to call Sync before exiting. Returns an error if any sync or close operation fails.
type Logger ¶
type Logger interface {
Sync() error
Debug(args ...any)
Debugf(template string, args ...any)
Debugw(msg string, keysAndValues ...any)
Debugln(args ...any)
Info(args ...any)
Infof(template string, args ...any)
Infow(msg string, keysAndValues ...any)
Infoln(args ...any)
Warn(args ...any)
Warnf(template string, args ...any)
Warnw(msg string, keysAndValues ...any)
Warnln(args ...any)
Error(args ...any)
Errorf(template string, args ...any)
Errorw(msg string, keysAndValues ...any)
Errorln(args ...any)
Panic(args ...any)
Panicf(template string, args ...any)
Panicw(msg string, keysAndValues ...any)
Panicln(args ...any)
Fatal(args ...any)
Fatalf(template string, args ...any)
Fatalw(msg string, keysAndValues ...any)
Fatalln(args ...any)
}
Logger defines the interface, includes the supported logging methods. For each log level, it exposes four methods:
- methods named after the log level for log.Print-style logging
- methods ending in "w" for loosely-typed structured logging (read as "info with")
- methods ending in "f" for log.Printf-style logging
- methods ending in "ln" for log.Println-style logging
type Options ¶
type Options struct {
Prefix string `mapstructure:"prefix"` // Log Prefix
Directory string `mapstructure:"directory"` // Log File Directory
Filename string `mapstructure:"filename"` // Log filename prefix
Level string `mapstructure:"level"` // Log Level
TimeLayout string `mapstructure:"time_layout"` // Time Layout
Format string `mapstructure:"format"` // Log Format
DisableCaller bool `mapstructure:"disable_caller"`
DisableStacktrace bool `mapstructure:"disable_stacktrace"`
DisableSplitError bool `mapstructure:"disable_split_error"`
MaxSize int `mapstructure:"max_size"` // Maximum size of log files in megabytes
MaxBackups int `mapstructure:"max_backups"` // Maximum number of old log files
Compress bool `mapstructure:"compress"` // Whether to compress rotated log files
EnableSampling bool `mapstructure:"enable_sampling"`
SampleInitial int `mapstructure:"sample_initial"`
SampleThereafter int `mapstructure:"sample_thereafter"`
ConsoleOutput bool `mapstructure:"console_output"` // Whether to output logs to console
}
Options for logger
func LoadFromFile ¶ added in v1.4.0
LoadFromFile loads configuration from multiple file formats using Viper. This function automatically detects the file format based on the file extension and supports YAML, JSON, TOML, and other formats supported by Viper.
The function supports two configuration formats:
Format 1 - Direct configuration (fields at root level):
prefix: "ZIWI_" level: "info" directory: "/var/log/myapp"
Format 2 - Nested configuration (fields under KLOG key):
KLOG: prefix: "ZIWI_" level: "info" directory: "/var/log/myapp"
Parameters:
- configPath: Path to the configuration file
Returns:
- *Options: Configuration options loaded from the configuration file
- error: Error if file loading, format detection, or parsing fails
Supported file formats:
- .yaml, .yml (YAML format)
- .json (JSON format)
- .toml (TOML format)
- Other formats supported by Viper
Example Usage:
// Load YAML configuration
opts, err := log.LoadFromFile("config.yaml")
if err != nil {
log.Fatal("Failed to load config:", err)
}
logger := log.NewLog(opts)
// Load JSON configuration
opts, err = log.LoadFromFile("config.json")
if err != nil {
log.Fatal("Failed to load config:", err)
}
logger = log.NewLog(opts)
// Load TOML configuration
opts, err = log.LoadFromFile("config.toml")
if err != nil {
log.Fatal("Failed to load config:", err)
}
logger = log.NewLog(opts)
func LoadFromJSON ¶ added in v1.4.0
LoadFromJSON loads configuration from a JSON file using Viper. This function provides a convenient wrapper for JSON configuration files while leveraging Viper's powerful configuration management capabilities.
Parameters:
- jsonPath: Path to the JSON configuration file
Returns:
- *Options: Configuration options loaded from JSON file
- error: Error if file loading, parsing, or validation fails
JSON Configuration Example:
{
"level": "info",
"format": "json",
"directory": "/var/log/myapp",
"filename": "application",
"max_size": 100,
"max_backups": 5,
"compress": true
}
Example Usage:
opts, err := log.LoadFromJSON("config.json")
if err != nil {
log.Fatal("Failed to load JSON config:", err)
}
logger := log.NewLog(opts)
Note: This function uses LoadFromFile internally for improved configuration parsing and validation. For multi-format support, use LoadFromFile directly.
func LoadFromTOML ¶ added in v1.4.0
LoadFromTOML loads configuration from a TOML file using Viper. This function provides a convenient wrapper for TOML configuration files while leveraging Viper's powerful configuration management capabilities.
Parameters:
- tomlPath: Path to the TOML configuration file
Returns:
- *Options: Configuration options loaded from TOML file
- error: Error if file loading, parsing, or validation fails
TOML Configuration Example:
level = "info" format = "json" directory = "/var/log/myapp" filename = "application" max_size = 100 max_backups = 5 compress = true
Example Usage:
opts, err := log.LoadFromTOML("config.toml")
if err != nil {
log.Fatal("Failed to load TOML config:", err)
}
logger := log.NewLog(opts)
Note: This function uses LoadFromFile internally for improved configuration parsing and validation. For multi-format support, use LoadFromFile directly.
func LoadFromYAML ¶ added in v1.4.0
LoadFromYAML loads configuration from a YAML file using Viper. This function provides backward compatibility while leveraging Viper's powerful configuration management capabilities for enhanced parsing and validation.
Parameters:
- yamlPath: Path to the YAML configuration file
Returns:
- *Options: Configuration options loaded from YAML file
- error: Error if file loading, parsing, or validation fails
YAML Configuration Example:
level: "info" format: "json" directory: "/var/log/myapp" filename: "application" max_size: 100 max_backups: 5 compress: true
Example Usage:
opts, err := log.LoadFromYAML("config.yaml")
if err != nil {
log.Fatal("Failed to load YAML config:", err)
}
logger := log.NewLog(opts)
Note: This function now uses LoadFromFile internally for improved configuration parsing and validation. For multi-format support, use LoadFromFile directly.
func NewOptions ¶
func NewOptions() *Options
NewOptions return the default Options.
Default:
Prefix: "ZIWI_", Directory: "$HOME/logs", Level: "info", TimeLayout: "2006-01-02 15:04:05.000", Format: "console", DisableCaller: false, DisableStacktrace: false, DisableSplitError: false, // Default log rotation settings MaxSize: 100, // 100MB MaxBackups: 3, // Keep 3 old log files Compress: false, // Sampling settings EnableSampling: false, // Sampling disabled by default SampleInitial: 100, // Initial sample count SampleThereafter: 100, // Subsequent sample count // Console output settings ConsoleOutput: true, // Console output enabled by default
func RecoverFromConfigError ¶ added in v1.4.0
RecoverFromConfigError attempts to recover from configuration errors by providing safe fallback values and logging the issues
func ValidateAndFixOptions ¶ added in v1.4.0
ValidateAndFixOptions is a convenience function that validates options and automatically recovers from errors by returning fixed options
func ValidateOptions ¶ added in v1.4.0
ValidateOptions validates configuration options and returns a fixed configuration along with any validation errors encountered. This function provides automatic error recovery by using safe default values when invalid configurations are detected.
func (*Options) WithCompress ¶
func (*Options) WithConsoleOutput ¶ added in v1.5.0
func (*Options) WithDirectory ¶
func (*Options) WithDisableCaller ¶
func (*Options) WithDisableSplitError ¶
func (*Options) WithDisableStacktrace ¶
func (*Options) WithFilename ¶ added in v1.3.0
func (*Options) WithFormat ¶
func (*Options) WithMaxBackups ¶
func (*Options) WithMaxSize ¶
func (*Options) WithPrefix ¶
func (*Options) WithSampling ¶ added in v1.4.0
func (*Options) WithTimeLayout ¶
type Preset ¶ added in v1.4.0
type Preset struct {
// contains filtered or unexported fields
}
Preset represents a predefined configuration set for different environments
func DevelopmentPreset ¶ added in v1.4.0
func DevelopmentPreset() *Preset
DevelopmentPreset returns a preset optimized for development environment Features: debug level, console output, caller info enabled, fast flush
func ProductionPreset ¶ added in v1.4.0
func ProductionPreset() *Preset
ProductionPreset returns a preset optimized for production environment Features: info level, JSON format, optimized for performance and storage
func TestingPreset ¶ added in v1.4.0
func TestingPreset() *Preset
TestingPreset returns a preset optimized for testing environment Features: debug level, simplified output, minimal file operations
func (Preset) Description ¶ added in v1.4.0
Description returns the preset description