logx

package module
v1.1.0 Latest Latest
Warning

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

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

README

LogX - Unified Go Logging Library

Go Version License Test Coverage

A high-performance, unified logging library for Go that supports multiple backends (zap and slog) with features like log rotation, buffering, and performance optimization.

✨ Features

  • Multiple Backends: Support for both Uber's Zap and Go's standard slog
  • High Performance: Optimized for high-throughput logging with buffering support
  • Log Rotation: Automatic log file rotation with size and age limits
  • Flexible Configuration: Support for both text and JSON output formats
  • Structured Logging: Full support for structured logging with key-value pairs
  • Concurrent Safe: Thread-safe logging operations
  • Easy Integration: Simple API that works with existing Go applications

🚀 Quick Start

Installation
go get github.com/go4x/logx
Basic Usage
package main

import (
    "github.com/go4x/logx"
)

func main() {
    // Configure the logger
    config := &logx.LoggerConfig{
        Type:         logx.LoggerTypeZap,
        Level:        "info",
        LogInConsole: true,
        Dir:          "logs",
        Format:       "json",
        MaxAge:       7,
        MaxSize:      100,
        MaxBackups:   10,
    }

    // Initialize the logger
    err := logx.Init(config)
    if err != nil {
        panic(err)
    }

    // Use the logger
    logx.Info("Hello, world!")
    logx.Error("Something went wrong", "error", "connection timeout")
}

📖 Documentation

Configuration Options
Option Type Description Default
Type string Logger backend type (zap or slog) zap
Level string Minimum log level (debug, info, warn, error, fatal) info
LogInConsole bool Whether to output logs to console false
Dir string Directory for log files logs
Format string Output format (text or json) text
MaxAge int Maximum days to retain log files (0 = no limit) 0
MaxSize int Maximum log file size in MB (0 = no limit) 0
MaxBackups int Maximum number of log files to keep (0 = no limit) 0
LocalTime bool Use local time instead of UTC false
Compress bool Compress rotated log files false
BufferSize int Buffer size for performance (0 = disabled) 0
FlushInterval int Buffer flush interval in seconds 5
Logger Types
Zap Logger (High Performance)
config := &logx.LoggerConfig{
    Type:         logx.LoggerTypeZap,
    Level:        "debug",
    LogInConsole: true,
    Dir:          "logs",
    Format:       "json",
    BufferSize:   4096,
    FlushInterval: 1,
}
Slog Logger (Standard Library)
config := &logx.LoggerConfig{
    Type:         logx.LoggerTypeSlog,
    Level:        "info",
    LogInConsole: true,
    Dir:          "logs",
    Format:       "text",
}
Log Levels
logx.Debug("Debug message")
logx.Info("Info message")
logx.Warn("Warning message")
logx.Error("Error message")
logx.Fatal("Fatal message") // Exits the program
Structured Logging
logx.Info("User login",
    "user_id", 12345,
    "ip", "192.168.1.1",
    "timestamp", time.Now(),
    "success", true,
)
Performance Optimization

For high-performance scenarios, enable buffering:

config := &logx.LoggerConfig{
    Type:          logx.LoggerTypeZap,
    Level:         "info",
    LogInConsole:  false,
    Dir:           "logs",
    Format:        "json",
    BufferSize:    8192,    // 8KB buffer
    FlushInterval: 2,       // Flush every 2 seconds
    MaxAge:        7,
    MaxSize:       100,
    MaxBackups:    10,
    Compress:      true,
}

🧪 Examples

Check out the usage examples:

# Run all examples
go run ./example/

# Or navigate to the example directory and run
cd example && go run .

Examples include:

  • Basic Usage: Basic usage of zap and slog loggers
  • Global Logger: Usage of global logger functions
  • Log Levels: Demonstration of different log levels
  • Performance Optimization: High-performance configuration and performance testing
  • Buffering Mechanism: Buffer configuration and performance comparison

🧪 Testing

Run the test suite:

# Run all tests
go test -v

# Run tests with coverage
go test -coverprofile=coverage.out -v
go tool cover -html=coverage.out

# Run benchmarks
go test -bench=. -benchmem

📊 Performance

Benchmark Results
Logger Type Operations/sec Memory/op Allocations/op
Zap (JSON) ~1,000,000 ~40B 2
Zap (Text) ~800,000 ~50B 3
Slog (JSON) ~600,000 ~60B 4
Slog (Text) ~500,000 ~70B 5
Performance Tips
  1. Use JSON format for better performance
  2. Enable buffering for high-throughput scenarios
  3. Disable console output in production
  4. Use Zap logger for maximum performance
  5. Configure appropriate buffer sizes based on your workload

🔧 Advanced Usage

Custom Configuration
// YAML configuration
config := &logx.LoggerConfig{
    Type:         logx.LoggerTypeZap,
    Level:        "info",
    LogInConsole: true,
    Dir:          "logs",
    Format:       "json",
    MaxAge:       30,
    MaxSize:      100,
    MaxBackups:   10,
    LocalTime:    true,
    Compress:     true,
    BufferSize:   4096,
    FlushInterval: 5,
}
Error Handling
err := logx.Init(config)
if err != nil {
    log.Fatalf("Failed to initialize logger: %v", err)
}
Context Support
// Get logger instance for advanced usage
logger := logx.GetLogger()
if logger != nil {
    // Use logger methods directly
    logger.Info("Direct logger usage")
}

🤝 Contributing

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

🙏 Acknowledgments

  • Uber's Zap for the high-performance logging backend
  • Go's slog for the standard library logging support
  • Lumberjack for log rotation functionality

📞 Support

If you have any questions or need help, please:

  1. Check the examples directory
  2. Open an issue on GitHub
  3. Review the test cases for usage patterns

Made with ❤️ for the Go community

Documentation

Overview

Package logx provides a unified logging interface with support for multiple backends. It supports both zap and slog loggers with features like log rotation, buffering, and performance optimization.

Example usage:

config := &logx.LoggerConfig{
    Type:         logx.LoggerTypeZap,
    Level:        "info",
    LogInConsole: true,
    Dir:          "logs",
    Format:       "json",
}
err := logx.Init(config)
if err != nil {
    log.Fatal(err)
}
logx.Info("Hello, world!")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(args ...any)

Debug logs a debug message using the global logger. If the global logger is not initialized, this function does nothing.

func Debugf added in v1.1.0

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

Debugf logs a formatted debug message using the global logger.

func Error

func Error(args ...any)

Error logs an error message using the global logger. If the global logger is not initialized, this function does nothing.

func Errorf added in v1.1.0

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

Errorf logs a formatted error message using the global logger.

func Fatal

func Fatal(args ...any)

Fatal logs a fatal message using the global logger and exits the program. If the global logger is not initialized, this function does nothing.

func Fatalf added in v1.1.0

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

Fatalf logs a formatted fatal message using the global logger and exits the program.

func Info

func Info(args ...any)

Info logs an informational message using the global logger. If the global logger is not initialized, this function does nothing.

func Infof added in v1.1.0

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

Infof logs a formatted informational message using the global logger.

func Init

func Init(c *LoggerConfig) error

Init initializes the logger according to the configuration. It returns an error if the configuration is invalid or initialization fails.

func Warn

func Warn(args ...any)

Warn logs a warning message using the global logger. If the global logger is not initialized, this function does nothing.

func Warnf added in v1.1.0

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

Warnf logs a formatted warning message using the global logger.

Types

type LogFormat

type LogFormat string

LogFormat represents the format of log output.

const (
	// FormatText outputs logs in plain text format.
	FormatText LogFormat = "text"
	// FormatJSON outputs logs in JSON format.
	FormatJSON LogFormat = "json"
)

type Logger

type Logger interface {
	// Debug logs a debug message.
	Debug(args ...any)
	// Debugf logs a formatted debug message.
	Debugf(template string, args ...any)
	// Info logs an informational message.
	Info(args ...any)
	// Infof logs a formatted informational message.
	Infof(template string, args ...any)
	// Warn logs a warning message.
	Warn(args ...any)
	// Warnf logs a formatted warning message.
	Warnf(template string, args ...any)
	// Error logs an error message.
	Error(args ...any)
	// Errorf logs a formatted error message.
	Errorf(template string, args ...any)
	// Fatal logs a fatal message and exits the program.
	Fatal(args ...any)
	// Fatalf logs a formatted fatal message and exits the program.
	Fatalf(template string, args ...any)
}

Logger defines the interface for logging operations. All logger implementations must satisfy this interface.

func GetLogger

func GetLogger() Logger

GetLogger returns the global logger instance.

type LoggerConfig

type LoggerConfig struct {
	// Type specifies the logger backend type (slog or zap).
	Type LoggerType `mapstructure:"type" yaml:"type"`

	// Level specifies the minimum log level (debug, info, warn, error, fatal).
	Level string `mapstructure:"level" yaml:"level"`

	// LogInConsole determines whether to output logs to console.
	LogInConsole bool `mapstructure:"log-in-console" yaml:"log-in-console"`

	// Dir specifies the directory where log files are stored.
	Dir string `mapstructure:"dir" yaml:"dir"`

	// Format specifies the log output format (text or json).
	Format string `mapstructure:"format" yaml:"format"`

	// MaxAge specifies the maximum number of days to retain log files (0 means no limit).
	MaxAge int `mapstructure:"max-age" yaml:"max-age"`

	// MaxSize specifies the maximum size of a log file in MB (0 means no limit).
	MaxSize int `mapstructure:"max-size" yaml:"max-size"`

	// MaxBackups specifies the maximum number of log files to keep (0 means no limit).
	MaxBackups int `mapstructure:"max-backups" yaml:"max-backups"`

	// LocalTime determines whether to use local time (true) or UTC time (false).
	LocalTime bool `mapstructure:"local-time" yaml:"local-time"`

	// Compress determines whether to compress rotated log files.
	Compress bool `mapstructure:"compress" yaml:"compress"`

	// BufferSize specifies the buffer size for performance optimization (0 disables buffering).
	BufferSize int `mapstructure:"buffer-size" yaml:"buffer-size"`

	// FlushInterval specifies the interval in seconds to flush the buffer.
	FlushInterval int `mapstructure:"flush-interval" yaml:"flush-interval"`
}

LoggerConfig holds the configuration for the logger.

type LoggerType

type LoggerType string

LoggerType represents the type of logger backend.

const (
	// LoggerTypeSlog uses Go's standard slog logger.
	LoggerTypeSlog LoggerType = "slog"
	// LoggerTypeZap uses Uber's zap logger for high performance.
	LoggerTypeZap LoggerType = "zap"
)

Directories

Path Synopsis
Package slog provides a slog logger implementation for the logx package.
Package slog provides a slog logger implementation for the logx package.
Package zap provides a zap logger implementation for the logx package.
Package zap provides a zap logger implementation for the logx package.

Jump to

Keyboard shortcuts

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