log

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: BSD-3-Clause Imports: 18 Imported by: 4

README

Log

A high-performance, structured logging package for Go applications, built on top of zap with enhanced usability features and simplified interface.

Features

Core 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 support
  • Flexible output formats (JSON and console)
  • Configurable time layout
  • Log file rotation by date
  • Separate error log files
  • Optional caller information and stack traces
  • Built on top of uber-go/zap for high performance
Enhanced Usability Features
  • Dual calling modes - Use both instance methods (logger.Info()) and global functions (log.Info()) seamlessly
  • Zero-configuration quick start - Get started with one line of code
  • Environment presets - Pre-configured settings for development, production, and testing
  • Builder pattern - Fluent API for easy configuration
  • Multi-format configuration - Load configuration from YAML, JSON, TOML, and other formats
  • HTTP middleware - Built-in middleware for request/response logging
  • Utility functions - Common logging patterns made simple
  • Enhanced error handling - Better error messages and automatic fallbacks
  • Performance optimizations - Buffering, sampling, and other performance features

Installation

go get github.com/kydenul/log

Quick Start

Simplest Usage (Zero Configuration)
package main

import "github.com/kydenul/log"

func main() {
    // Create logger with sensible defaults
    logger := log.Quick()
    
    // Both calling modes work with the same configuration:
    
    // Instance method calls
    logger.Info("Hello from instance method!")
    logger.Warn("Warning from instance method")
    logger.Errorf("Error from instance: %v", err)
    
    // Global function calls (automatically use the same logger)
    log.Info("Hello from global function!")
    log.Warn("Warning from global function")
    log.Errorf("Error from global: %v", err)
    
    // Both produce identical output with the same configuration
}
Using Environment Presets
package main

import "github.com/kydenul/log"

func main() {
    // Development environment (debug level, console output, caller info)
    devLogger := log.WithPreset(log.DevelopmentPreset())
    devLogger.Debug("Development mode enabled")
    
    // Production environment (info level, JSON format, optimized)
    prodLogger := log.WithPreset(log.ProductionPreset())
    prodLogger.Info("Production service started")
    
    // Testing environment (debug level, simplified output)
    testLogger := log.WithPreset(log.TestingPreset())
    testLogger.Debug("Running tests")
}
Using Builder Pattern
package main

import (
    "time"
    "github.com/kydenul/log"
)

func main() {
    // Fluent configuration with builder pattern
    logger := log.NewBuilder().
        Level("debug").
        Format("json").
        Directory("./logs").
        Filename("myapp").
        ConsoleOutput(false).           // Disable console output
        Sampling(true, 100, 1000).
        Build()
    
    logger.Info("Logger configured with builder pattern")
    
    // Or use preset and customize
    logger2 := log.NewBuilder().
        Production().                    // Start with production preset
        Level("debug").                  // Override level for debugging
        Directory("/var/log/myapp").     // Custom log directory
        ConsoleOutput(false).            // Disable console for production
        Build()
    
    logger2.Debug("Custom production logger")
}

Configuration

Powered by Viper

The logging library uses Viper for configuration management, providing:

  • Multiple format support: YAML, JSON, TOML, HCL, INI, and more
  • Automatic format detection: Based on file extension
  • Environment variable support: Can be extended to read from environment variables
  • Configuration validation: Built-in validation with helpful error messages
  • Hot reloading capability: Can be extended for runtime configuration updates
Supported Configuration Formats
Format Extensions Example
YAML .yaml, .yml config.yaml
JSON .json config.json
TOML .toml config.toml

All formats support the same configuration options with automatic conversion between formats.

Configuration File Formats

The library supports two configuration formats:

  1. Nested configuration with KLOG key (Recommended) - Configuration under a KLOG top-level key
  2. Direct configuration - Configuration at the root level

Recommendation: Use the KLOG nested configuration format. This approach allows you to combine logger configuration with other application settings in a single file, keeping your configuration organized and avoiding key conflicts.

YAML configuration (config.yaml):

# config.yaml - Recommended format with KLOG key
# This allows combining with other application settings

# Other application settings can coexist
app:
  name: "my-service"
  port: 8080

# Logger configuration under KLOG key
KLOG:
  prefix: "ZIWI_"
  directory: "./logs"
  filename: "ziwi"
  level: "info"
  format: "json"
  time_layout: "2006-01-02 15:04:05.000"

  # Basic settings
  disable_caller: false
  disable_stacktrace: false
  disable_split_error: false

  # File rotation
  max_size: 100
  max_backups: 5
  compress: true

  # Console output control
  console_output: true

  # Sampling (reduces log volume in high-traffic scenarios)
  enable_sampling: true
  sample_initial: 100
  sample_thereafter: 1000

JSON configuration (config.json):

{
  "app": {
    "name": "my-service",
    "port": 8080
  },
  "KLOG": {
    "prefix": "ZIWI_",
    "directory": "./logs",
    "filename": ziwi",
    "level": "info",
    "format": "json",
    "time_layout": "2006-01-02 15:04:05.000",
    "disable_caller": false,
    "disable_stacktrace": false,
    "disable_split_error": false,
    "max_size": 100,
    "max_backups": 5,
    "compress": true,
    "console_output": true,
    "enable_sampling": true,
    "sample_initial": 100,
    "sample_thereafter": 1000
  }
}

TOML configuration (config.toml):

# config.toml - Recommended format with KLOG section

# Other application settings
[app]
name = "my-service"
port = 8080

# Logger configuration
[KLOG]
prefix = "ZIWI_"
directory = "./logs"
filename = "ziwi"
level = "info"
format = "json"
time_layout = "2006-01-02 15:04:05.000"

# Basic settings
disable_caller = false
disable_stacktrace = false
disable_split_error = false

# File rotation
max_size = 100
max_backups = 5
compress = true

# Console output control
console_output = true

# Sampling
enable_sampling = true
sample_initial = 100
sample_thereafter = 1000
Direct Configuration (Alternative)

If you prefer a dedicated configuration file for logging only, you can use direct configuration without the KLOG key:

YAML configuration (log-config.yaml):

# log-config.yaml - Direct configuration (no KLOG key)
prefix: "ZIWI_"
directory: "./logs"
filename: "ziwi"
level: "info"
format: "json"
time_layout: "2006-01-02 15:04:05.000"

# Basic settings
disable_caller: false
disable_stacktrace: false
disable_split_error: false

# File rotation
max_size: 100
max_backups: 5
compress: true

# Console output control
console_output: true

# Sampling
enable_sampling: true
sample_initial: 100
sample_thereafter: 1000
Configuration Options Reference
Field Type Default Description
prefix string "ZIWI_" Log message prefix
directory string $HOME/logs Log file directory
filename string "" Log filename prefix (e.g., app -> app-2024-01-15.log)
level string "info" Log level: debug, info, warn, error, dpanic, panic, fatal
format string "console" Output format: console or json
time_layout string "2006-01-02 15:04:05.000" Time format layout
disable_caller bool false Disable caller information
disable_stacktrace bool false Disable stack traces
disable_split_error bool true Disable separate error log files
max_size int 100 Maximum log file size in MB
max_backups int 3 Maximum number of old log files to retain
compress bool false Compress rotated log files
console_output bool true Enable console output
enable_sampling bool false Enable log sampling
sample_initial int 100 Initial sample count per second
sample_thereafter int 100 Sample count after initial burst
Advanced Configuration

For more control over configuration loading:

// Load options from YAML file (without creating logger)
opts, err := log.LoadFromYAML("config.yaml")
if err != nil {
    log.Fatal("Failed to load YAML:", err)
}
logger := log.NewLog(opts)

// Load from any supported file format (auto-detected by extension)
opts, err := log.LoadFromFile("config.yaml") // Supports .yaml, .yml, .json, .toml
if err != nil {
    log.Fatal("Failed to load config:", err)
}
logger := log.NewLog(opts)

// Examples with different formats
opts, err = log.LoadFromFile("config.json")  // JSON format
opts, err = log.LoadFromFile("config.toml")  // TOML format
opts, err = log.LoadFromFile("config.yml")   // YAML format

HTTP Middleware

Built-in HTTP middleware for automatic request/response logging:

package main

import (
    "net/http"
    "github.com/kydenul/log"
)

func main() {
    logger := log.WithPreset(log.ProductionPreset())
    
    // Create HTTP middleware
    middleware := log.HTTPMiddleware(logger)
    
    // Wrap your handlers
    http.Handle("/api/users", middleware(http.HandlerFunc(usersHandler)))
    http.Handle("/api/orders", middleware(http.HandlerFunc(ordersHandler)))
    
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func usersHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Users endpoint"))
}

The middleware automatically logs:

  • Request start with method, URL, remote address, user agent
  • Request completion with status code, duration, and timing

Dual Calling Modes

One of the key features of this logging library is dual calling modes - you can use both instance methods and global functions seamlessly with the same configuration.

How It Works

When you create a logger using any method (NewLog(), Quick(), WithPreset(), FromConfigFile(), Builder.Build()), it automatically becomes the global default logger. This means:

  • Instance calls like logger.Info() work directly on your logger instance
  • Global calls like log.Info() automatically use the same logger configuration
  • Both produce identical output with the same formatting, file destinations, and settings
Usage Examples
package main

import "github.com/kydenul/log"

func main() {
    // Create a custom logger
    logger := log.NewBuilder().
        Level("debug").
        Format("json").
        Directory("./logs").
        Prefix("[MyApp] ").
        Build()
    
    // Method 1: Instance method calls
    logger.Info("User logged in", "user_id", 123)
    logger.Warn("Rate limit approaching", "current", 95, "limit", 100)
    logger.Error("Database connection failed", "error", err)
    
    // Method 2: Global function calls (same configuration automatically)
    log.Info("User logged in", "user_id", 123)
    log.Warn("Rate limit approaching", "current", 95, "limit", 100)
    log.Error("Database connection failed", "error", err)
    
    // Both methods produce identical output:
    // [MyApp] {"level":"info","ts":"2024-01-15T10:30:45.123Z","msg":"User logged in","user_id":123}
}

Complete Example: See example/dual-calling/main.go for a comprehensive demonstration of dual calling modes with different logger creation methods.

All Logger Creation Methods Support Dual Calling
// 1. Direct creation
logger := log.NewLog(opts)
logger.Info("Instance call")
log.Info("Global call")  // Uses same config

// 2. Quick setup
logger := log.Quick()
logger.Info("Instance call")
log.Info("Global call")  // Uses same config

// 3. Environment presets
logger := log.WithPreset(log.ProductionPreset())
logger.Info("Instance call")
log.Info("Global call")  // Uses same config

// 4. Configuration files
logger, _ := log.FromConfigFile("config.yaml")
logger.Info("Instance call")
log.Info("Global call")  // Uses same config

// 5. Builder pattern
logger := log.NewBuilder().Level("debug").Build()
logger.Info("Instance call")
log.Info("Global call")  // Uses same config
Multiple Logger Instances

When you create multiple logger instances, the most recently created logger becomes the global default:

// Create first logger
logger1 := log.WithPreset(log.DevelopmentPreset())
log.Info("Uses logger1 config")  // Development preset

// Create second logger
logger2 := log.WithPreset(log.ProductionPreset())
log.Info("Uses logger2 config")  // Production preset (now global)

// Instance methods still work independently
logger1.Info("Still uses development config")
logger2.Info("Still uses production config")
Benefits of Dual Calling Modes
  1. Flexibility: Choose the calling style that fits your code structure
  2. Migration friendly: Existing code using global functions continues to work
  3. Consistent configuration: No need to pass logger instances everywhere
  4. Team preferences: Different team members can use their preferred style
  5. Library integration: Easy to integrate with existing libraries that expect global functions
When to Use Each Mode

Use instance methods (logger.Info()) when:

  • You want explicit control over which logger to use
  • Working with dependency injection patterns
  • Building libraries that accept logger parameters
  • You have multiple loggers with different configurations

Use global functions (log.Info()) when:

  • You have a single logger configuration for your application
  • Migrating from other logging libraries
  • You prefer the simplicity of global functions
  • Working with existing code that uses global logging

Global Logger Functions

The package provides global functions that automatically use the current default logger instance:

import "github.com/kydenul/log"

func main() {
    // Configure the logger (automatically becomes global default)
    logger := log.NewBuilder().
        Level("debug").
        Format("json").
        Directory("./logs").
        Build()
    
    // Now both calling modes work with the same configuration:
    
    // Global functions (use the logger configuration above)
    log.Debug("Debug message")
    log.Info("Info message")
    log.Warn("Warning message")
    log.Error("Error message")
    
    // Structured logging
    log.Infow("User action", "user_id", 123, "action", "login")
    log.Errorw("Operation failed", "error", err, "retry_count", 3)
    
    // Formatted logging
    log.Infof("Processing %d items", count)
    log.Errorf("Failed to connect to %s: %v", host, err)
    
    // Line-based logging
    log.Infoln("This", "is", "a", "line", "message")
    
    // Instance methods (same output as global functions)
    logger.Debug("Debug message")
    logger.Info("Info message")
    logger.Infow("User action", "user_id", 123, "action", "login")
    
    // Manually replace the global logger (optional)
    customLogger := log.NewBuilder().Level("info").Build()
    log.ReplaceLogger(customLogger)
    
    // Sync all loggers before exit
    defer log.Sync()
}

Utility Functions

The logutil package provides convenient utility functions for common logging patterns:

import (
    "github.com/kydenul/log"
    "github.com/kydenul/log/logutil"
)

func main() {
    logger := log.Quick()
    
    // Error handling utilities
    err := someOperation()
    logutil.LogError(logger, err, "Operation failed")
    logutil.FatalOnError(logger, err, "Critical operation failed")
    
    // Performance timing
    defer logutil.Timer(logger, "database_query")()
    // ... database operation ...
    
    // Or time a function
    logutil.TimeFunction(logger, "data_processing", func() {
        // ... processing logic ...
    })
    
    // Conditional logging
    debugMode := true
    logutil.InfoIf(logger, debugMode, "Debug info", "key", "value")
    logutil.ErrorIf(logger, err != nil, "Error occurred", "error", err)
    
    // HTTP request logging
    logutil.LogHTTPRequest(logger, request)
    logutil.LogHTTPResponse(logger, request, 200, duration)
    
    // Application lifecycle
    logutil.LogStartup(logger, "my-service", "v1.0.0", 8080)
    logutil.LogShutdown(logger, "my-service", uptime)
    
    // Panic recovery
    defer logutil.LogPanicAsError(logger, "risky_operation")
}

Key Features

Console Output Control

The logger provides flexible control over console output while maintaining file logging:

  • Independent control: Console output can be enabled/disabled independently of file logging
  • Default behavior: Console output is enabled by default (console_output: true)
  • Production optimization: Disable console output in production to reduce performance overhead
  • File logging preserved: When console output is disabled, all logs still write to files

Usage examples:

// Enable console output (default behavior)
logger := log.NewBuilder().
    ConsoleOutput(true).
    Build()

// Disable console output (logs only to files)
logger := log.NewBuilder().
    ConsoleOutput(false).
    Build()

// Production setup with no console output
prodLogger := log.NewBuilder().
    Production().
    ConsoleOutput(false).  // Override preset to disable console
    Build()

// Development setup with console output
devLogger := log.NewBuilder().
    Development().
    ConsoleOutput(true).   // Explicitly enable (already default)
    Build()

Configuration file examples:

# Enable console output (default)
console_output: true

# Disable console output (production)
console_output: false
{
  "console_output": false
}
Automatic File Management

The logger automatically handles:

  • Date-based file rotation: Creates new log files daily (e.g., app-2024-01-15.log)
  • Separate error logs: Optional separate files for error-level messages
  • Custom filename support: Use custom prefixes for log files
  • Fallback mechanisms: Automatically falls back to safe defaults if custom filenames fail
Performance Optimizations
  • Sampling: Reduce log volume in high-traffic scenarios
  • Atomic operations: Thread-safe file operations with minimal locking
  • Memory pooling: Reuses buffers to reduce garbage collection
Enhanced Error Handling
  • Graceful degradation: Continues logging even when configuration is invalid
  • Automatic recovery: Falls back to safe defaults when file operations fail
  • Detailed error messages: Clear error messages with suggestions for fixes
  • Validation: Comprehensive validation of all configuration options

Environment Presets

Choose from pre-configured environments:

Development Preset
  • Debug level logging
  • Console output format
  • Console output enabled (for immediate feedback)
  • Caller information enabled
  • Stack traces enabled
  • Fast flush for immediate feedback
  • No log sampling
logger := log.WithPreset(log.DevelopmentPreset())
Production Preset
  • Info level logging
  • JSON output format
  • Console output enabled (can be overridden)
  • Caller information disabled (performance)
  • Stack traces disabled (performance)
  • Log sampling enabled
  • File compression enabled
logger := log.WithPreset(log.ProductionPreset())
Testing Preset
  • Debug level logging
  • Console output format
  • Console output enabled (for test visibility)
  • Caller information disabled (cleaner output)
  • Stack traces disabled (cleaner output)
  • Fast flush for test verification
  • No log sampling
logger := log.WithPreset(log.TestingPreset())

Examples

Web Service with Middleware
package main

import (
    "net/http"
    "time"
    "github.com/kydenul/log"
    "github.com/kydenul/log/logutil"
)

func main() {
    // Configure logger for production
    logger := log.NewBuilder().
        Production().
        Directory("/var/log/myservice").
        ConsoleOutput(false).            // Disable console output for production
        Build()
    
    // Log service startup
    logutil.LogStartup(logger, "my-service", "v1.2.3", 8080)
    
    // Setup middleware
    middleware := log.HTTPMiddleware(logger)
    
    // Setup routes
    http.Handle("/health", middleware(http.HandlerFunc(healthHandler)))
    http.Handle("/api/data", middleware(http.HandlerFunc(dataHandler)))
    
    // Start server
    logger.Info("Server starting on :8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        logger.Fatal("Server failed to start", "error", err)
    }
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func dataHandler(w http.ResponseWriter, r *http.Request) {
    logger := log.Quick() // Or get from context
    
    defer logutil.Timer(logger, "data_processing")()
    
    // Simulate processing
    time.Sleep(100 * time.Millisecond)
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write([]byte(`{"status": "success"}`))
}
Configuration-Driven Application
package main

import (
    "os"
    "github.com/kydenul/log"
    "github.com/kydenul/log/logutil"
)

func main() {
    // Load configuration from different formats
    var logger *log.Log
    var err error
    
    // Try different configuration formats
    if _, err := os.Stat("config.yaml"); err == nil {
        logger, err = log.FromConfigFile("config.yaml")
    } else if _, err := os.Stat("config.json"); err == nil {
        logger, err = log.FromConfigFile("config.json")
    } else if _, err := os.Stat("config.toml"); err == nil {
        logger, err = log.FromConfigFile("config.toml")
    } else {
        // Fallback to default configuration
        logger = log.Quick()
    }
    
    logutil.FatalOnError(logger, err, "Failed to initialize logger")
    
    // Application logic
    processData(logger)
}

func processData(logger *log.Log) {
    defer logutil.LogPanicAsError(logger, "data_processing")
    
    // Simulate work with error handling
    data, err := loadData()
    if logutil.CheckError(logger, err, "Failed to load data") {
        return
    }
    
    // Process data with timing
    logutil.TimeFunction(logger, "data_transformation", func() {
        transformData(data)
    })
    
    logger.Info("Data processing completed successfully")
}

Best Practices

  1. Choose your calling mode consistently:

    • Use instance methods (logger.Info()) when you need explicit control or multiple logger configurations
    • Use global functions (log.Info()) for simple applications with a single logger configuration
    • Mix both modes as needed - they work seamlessly together
  2. Use presets for common scenarios: Start with DevelopmentPreset(), ProductionPreset(), or TestingPreset()

  3. Control console output appropriately:

    • Development: Keep console output enabled for immediate feedback
    • Production: Consider disabling console output (ConsoleOutput(false)) to reduce performance overhead
    • Containers: Enable console output if using container log aggregation, disable if using file-based logging
  4. Use structured logging: Prefer logger.Infow("message", "key", "value") over logger.Infof("message %s", value)

  5. Handle errors gracefully: Use logutil.LogError() and logutil.CheckError() for consistent error handling

  6. Time critical operations: Use logutil.Timer() or logutil.TimeFunction() for performance monitoring

  7. Use HTTP middleware: Automatically log all HTTP requests and responses

  8. Configure sampling for high-traffic services: Enable sampling in production to manage log volume

  9. Use appropriate log levels: Debug for development, Info for production events, Error for actual problems

  10. Always call Sync(): Call logger.Sync() or log.Sync() before application exit to flush buffers

  11. Understand global logger behavior: When creating multiple loggers, the most recent one becomes the global default. Use log.ReplaceLogger() if you need explicit control

Requirements

  • Go 1.23.4 or higher
  • Dependencies:
    • go.uber.org/zap
    • gopkg.in/natefinch/lumberjack.v2
    • github.com/spf13/viper (replaces gopkg.in/yaml.v3)
    • github.com/stretchr/testify (for testing)

License

This project is licensed under the terms found in the LICENSE file.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

Examples

Constants

View Source
const (
	MaxRetries = 3                     // Maximum retries for file write operations
	BriefDelay = time.Millisecond * 10 // Brief delay before retry
)
View Source
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"
)
View Source
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

View Source
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

View Source
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 Debug

func Debug(args ...any)

func Debugf

func Debugf(template string, args ...any)

Debugf formats the message according to the format specifier and logs it.

func Debugln

func Debugln(args ...any)

func Debugw

func Debugw(msg string, keysAndValues ...any)

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Error

func Error(args ...any)

func Errorf

func Errorf(template string, args ...any)

Errorf formats the message according to the format specifier and logs it.

func Errorln

func Errorln(args ...any)

func Errorw

func Errorw(msg string, keysAndValues ...any)

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Fatal

func Fatal(args ...any)

func Fatalf

func Fatalf(template string, args ...any)

Fatalf formats the message according to the format specifier and calls os.Exit.

func Fatalln

func Fatalln(args ...any)

func Fatalw

func Fatalw(msg string, keysAndValues ...any)

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

func HTTPMiddleware(logger Logger) func(http.Handler) http.Handler

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 Info

func Info(args ...any)

func Infof

func Infof(template string, args ...any)

Infof formats the message according to the format specifier and logs it.

func Infoln

func Infoln(args ...any)

func Infow

func Infow(msg string, keysAndValues ...any)

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

func IsConfigError(err error) bool

IsConfigError checks if an error is a ConfigError

func Panic

func Panic(args ...any)

func Panicf

func Panicf(template string, args ...any)

Panicf formats the message according to the format specifier and panics.

func Panicln

func Panicln(args ...any)

func Panicw

func Panicw(msg string, keysAndValues ...any)

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.

func Warn

func Warn(args ...any)

func Warnf

func Warnf(template string, args ...any)

Warnf formats the message according to the format specifier and logs it.

func Warnln

func Warnln(args ...any)

func Warnw

func Warnw(msg string, keysAndValues ...any)

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

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

func (b *Builder) Build() *Log

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

func (b *Builder) Compress(compress bool) *Builder

Compress sets whether to compress rotated log files Returns the Builder for method chaining

func (*Builder) ConsoleOutput added in v1.5.0

func (b *Builder) ConsoleOutput(enable bool) *Builder

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

func (b *Builder) Development() *Builder

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

func (b *Builder) Directory(dir string) *Builder

Directory sets the log file directory Returns the Builder for method chaining

func (*Builder) DisableCaller added in v1.4.0

func (b *Builder) DisableCaller(disable bool) *Builder

DisableCaller sets whether to disable caller information Returns the Builder for method chaining

func (*Builder) DisableSplitError added in v1.4.0

func (b *Builder) DisableSplitError(disable bool) *Builder

DisableSplitError sets whether to disable separate error log files Returns the Builder for method chaining

func (*Builder) DisableStacktrace added in v1.4.0

func (b *Builder) DisableStacktrace(disable bool) *Builder

DisableStacktrace sets whether to disable stack traces Returns the Builder for method chaining

func (*Builder) Filename added in v1.4.0

func (b *Builder) Filename(filename string) *Builder

Filename sets the log filename prefix Returns the Builder for method chaining

func (*Builder) Format added in v1.4.0

func (b *Builder) Format(format string) *Builder

Format sets the log format (console or json) Returns the Builder for method chaining

func (*Builder) Level added in v1.4.0

func (b *Builder) Level(level string) *Builder

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

func (b *Builder) MaxBackups(backups int) *Builder

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

func (b *Builder) MaxSize(size int) *Builder

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

func (b *Builder) Prefix(prefix string) *Builder

Prefix sets the log prefix Returns the Builder for method chaining

func (*Builder) Production added in v1.4.0

func (b *Builder) Production() *Builder

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

func (b *Builder) Sampling(enable bool, initial, thereafter int) *Builder

Sampling configures log sampling settings Returns the Builder for method chaining

func (*Builder) Testing added in v1.4.0

func (b *Builder) Testing() *Builder

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

func (b *Builder) TimeLayout(layout string) *Builder

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

type Log struct {
	zapcore.Encoder
	// contains filtered or unexported fields
}

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

func FromConfigFile(configPath string) (*Log, error)

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

func NewLog(opts *Options) *Log

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

func WithPreset(preset *Preset) *Log

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) Debug added in v1.3.0

func (l *Log) Debug(args ...any)

func (*Log) Debugf added in v1.3.0

func (l *Log) Debugf(template string, args ...any)

Debugf formats the message according to the format specifier and logs it.

func (*Log) Debugln added in v1.3.0

func (l *Log) Debugln(args ...any)

func (*Log) Debugw added in v1.3.0

func (l *Log) Debugw(msg string, keysAndValues ...any)

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

func (l *Log) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)

EncodeEntry encodes the entry and fields into a buffer.

func (*Log) Error added in v1.3.0

func (l *Log) Error(args ...any)

func (*Log) Errorf added in v1.3.0

func (l *Log) Errorf(template string, args ...any)

Errorf formats the message according to the format specifier and logs it.

func (*Log) Errorln added in v1.3.0

func (l *Log) Errorln(args ...any)

func (*Log) Errorw added in v1.3.0

func (l *Log) Errorw(msg string, keysAndValues ...any)

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*Log) Fatal added in v1.3.0

func (l *Log) Fatal(args ...any)

func (*Log) Fatalf added in v1.3.0

func (l *Log) Fatalf(template string, args ...any)

Fatalf formats the message according to the format specifier and calls os.Exit.

func (*Log) Fatalln added in v1.3.0

func (l *Log) Fatalln(args ...any)

func (*Log) Fatalw added in v1.3.0

func (l *Log) Fatalw(msg string, keysAndValues ...any)

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) Info added in v1.3.0

func (l *Log) Info(args ...any)

func (*Log) Infof added in v1.3.0

func (l *Log) Infof(template string, args ...any)

Infof formats the message according to the format specifier and logs it.

func (*Log) Infoln added in v1.3.0

func (l *Log) Infoln(args ...any)

func (*Log) Infow added in v1.3.0

func (l *Log) Infow(msg string, keysAndValues ...any)

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*Log) Panic added in v1.3.0

func (l *Log) Panic(args ...any)

func (*Log) Panicf added in v1.3.0

func (l *Log) Panicf(template string, args ...any)

Panicf formats the message according to the format specifier and panics.

func (*Log) Panicln added in v1.3.0

func (l *Log) Panicln(args ...any)

func (*Log) Panicw added in v1.3.0

func (l *Log) Panicw(msg string, keysAndValues ...any)

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

func (l *Log) 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.

func (*Log) Warn added in v1.3.0

func (l *Log) Warn(args ...any)

func (*Log) Warnf added in v1.3.0

func (l *Log) Warnf(template string, args ...any)

Warnf formats the message according to the format specifier and logs it.

func (*Log) Warnln added in v1.3.0

func (l *Log) Warnln(args ...any)

func (*Log) Warnw added in v1.3.0

func (l *Log) Warnw(msg string, keysAndValues ...any)

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

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

func LoadFromFile(configPath string) (*Options, error)

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

func LoadFromJSON(jsonPath string) (*Options, error)

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

func LoadFromTOML(tomlPath string) (*Options, error)

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

func LoadFromYAML(yamlPath string) (*Options, error)

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

func RecoverFromConfigError(err error) *Options

RecoverFromConfigError attempts to recover from configuration errors by providing safe fallback values and logging the issues

func ValidateAndFixOptions added in v1.4.0

func ValidateAndFixOptions(opts *Options) *Options

ValidateAndFixOptions is a convenience function that validates options and automatically recovers from errors by returning fixed options

func ValidateOptions added in v1.4.0

func ValidateOptions(opts *Options) (*Options, error)

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) Validate

func (opt *Options) Validate() error

func (*Options) WithCompress

func (opt *Options) WithCompress(compress bool) *Options

func (*Options) WithConsoleOutput added in v1.5.0

func (opt *Options) WithConsoleOutput(enable bool) *Options

func (*Options) WithDirectory

func (opt *Options) WithDirectory(dir string) *Options

func (*Options) WithDisableCaller

func (opt *Options) WithDisableCaller(disableCaller bool) *Options

func (*Options) WithDisableSplitError

func (opt *Options) WithDisableSplitError(disableSplitError bool) *Options

func (*Options) WithDisableStacktrace

func (opt *Options) WithDisableStacktrace(disableStacktrace bool) *Options

func (*Options) WithFilename added in v1.3.0

func (opt *Options) WithFilename(filename string) *Options

func (*Options) WithFormat

func (opt *Options) WithFormat(format string) *Options

func (*Options) WithLevel

func (opt *Options) WithLevel(level string) *Options

func (*Options) WithMaxBackups

func (opt *Options) WithMaxBackups(maxBackups int) *Options

func (*Options) WithMaxSize

func (opt *Options) WithMaxSize(maxSize int) *Options

func (*Options) WithPrefix

func (opt *Options) WithPrefix(prefix string) *Options

func (*Options) WithSampling added in v1.4.0

func (opt *Options) WithSampling(enable bool, initial, thereafter int) *Options

func (*Options) WithTimeLayout

func (opt *Options) WithTimeLayout(timeLayout string) *Options

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) Apply added in v1.4.0

func (p Preset) Apply(opts *Options)

Apply applies the preset configuration to the given Options

func (Preset) Description added in v1.4.0

func (p Preset) Description() string

Description returns the preset description

func (Preset) Name added in v1.4.0

func (p Preset) Name() string

Name returns the preset name

Directories

Path Synopsis
example
config command
sampling command
Package logutil provides utility functions for common logging tasks.
Package logutil provides utility functions for common logging tasks.

Jump to

Keyboard shortcuts

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