log

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2025 License: MIT Imports: 11 Imported by: 0

README ΒΆ

log - The Fastest Zero-Allocation Logging Library for Go

Go Reference Go Report Card MIT License Test Coverage

The fastest logging library for Go with true zero allocations, achieving an incredible 7.425 nanoseconds per log operation. Built from the ground up for Go 1.23+ with a focus on extreme performance.

πŸš€ Performance

BenchmarkNanoLogger-10              147687733      7.425 ns/op      0 B/op    0 allocs/op
BenchmarkUltimateLogger-10           53423659     18.84 ns/op      0 B/op    0 allocs/op
BenchmarkStructuredLogger-10         20530777     59.08 ns/op      0 B/op    0 allocs/op
BenchmarkZeroAllocLogger-10          19329052     56.89 ns/op    256 B/op    1 allocs/op
BenchmarkUltralog-10                 17233688     70.05 ns/op    256 B/op    1 allocs/op
BenchmarkDisabledDebug-10          1000000000      1.281 ns/op      0 B/op    0 allocs/op

✨ Features

  • True Zero Allocations: Multiple loggers achieve 0 B/op, 0 allocs/op
  • Extreme Performance: 7.425 ns/op - faster than just copying a string!
  • Lock-Free Design: Uses atomic operations for thread-safe, contention-free logging
  • Cache-Line Aligned: Structures optimized for CPU cache efficiency (64 bytes)
  • Beautiful Terminal Output: Colored, formatted output for development
  • Structured Logging: Type-safe fields without interface boxing
  • Multiple Writers: Terminal, Memory-mapped files, Async ring buffer
  • Binary Format: Compact binary encoding for maximum throughput
  • Go 1.23+ Optimized: Built using the latest Go features and runtime optimizations

πŸ“¦ Installation

go get github.com/semihalev/log

Requires Go 1.23 or later.

🎯 Quick Start

Global Logger (Easy Migration from v0.x)
package main

import "github.com/semihalev/log"

func main() {
    // v0.x compatible - accepts any key-value pairs
    log.Info("Application starting")
    log.Info("User logged in", "username", "john", "user_id", 12345)
    log.Error("Connection failed", "host", "localhost", "port", 5432)
    
    // Configure global logger
    log.SetLevel(log.LevelWarn)  // Only Warn, Error, Fatal will be logged
    
    // Or use typed fields for better performance (0 allocations)
    log.Error("Database error",
        log.String("host", "localhost"),
        log.Int("port", 5432),
        log.String("error", "connection refused"))
}

The global logger intelligently handles both styles:

  • Any values: log.Info("msg", "key", value, ...) - v0.x compatible
  • Typed fields: log.Info("msg", log.String("key", "val")) - Zero allocations
Basic Logging
package main

import "github.com/semihalev/log"

func main() {
    // Create logger instance with beautiful terminal output
    logger := log.New()
    logger.SetWriter(log.StdoutTerminal())
    
    // Basic logging
    logger.Debug("Application starting...")
    logger.Info("Server initialized successfully")
    logger.Warn("Configuration not found, using defaults")
    logger.Error("Failed to connect to database")
    logger.Fatal("Critical error, shutting down") // Exits with code 1
}
Structured Logging
// Create structured logger with zero allocations
logger := log.NewStructured()
logger.SetWriter(log.StdoutTerminal())

// Log with typed fields - 0 allocations thanks to buffer pool!
logger.Info("User logged in",
    log.String("username", "john_doe"),
    log.Int("user_id", 12345),
    log.Bool("admin", true),
    log.Float64("session_time", 30.5))

logger.Error("Request failed",
    log.String("method", "POST"),
    log.String("path", "/api/users"),
    log.Int("status", 500),
    log.Uint64("duration_ns", 1234567))
Zero-Allocation Logging
// For absolute maximum performance
logger := log.NewUltimateLogger()

// 18.84 ns/op with true zero allocations
logger.Info("Ultra-fast logging")
logger.Debug("This is incredibly fast")

// Or use NanoLogger for 7.425 ns/op!
nano := log.NewNanoLogger(nil)
var buf [256]byte
nano.Info(buf[:], "Fastest possible logging")

πŸ—οΈ Architecture

Logger Types
  1. Logger - Basic ultra-fast logger (73 ns/op)

    • Simple and fast for basic logging needs
    • Binary format output
    • Configurable log levels
  2. StructuredLogger - Type-safe structured logging (59 ns/op, 0 allocs)

    • Typed fields without interface boxing
    • Zero-allocation field encoding with buffer pool
    • Perfect for production systems
  3. ZeroAllocLogger - Uses ZeroWriter interface (56 ns/op)

    • Stack-allocated buffers only
    • Special interface to prevent heap escapes
    • Ideal for hot paths
  4. UltimateLogger - Direct memory writes (18.84 ns/op, 0 allocs)

    • Lock-free ring buffer
    • Memory-mapped output
    • For extreme throughput requirements
  5. NanoLogger - The absolute fastest (7.425 ns/op, 0 allocs)

    • Caller provides buffer
    • Minimal overhead
    • For the most demanding applications
Writers
  • StdoutTerminal/StderrTerminal - Beautiful colored terminal output
  • StdoutWriter/StderrWriter - Basic standard output
  • DiscardWriter - Discard all output (benchmarking)
  • MMapWriter - Memory-mapped files for zero-syscall writes
  • AsyncWriter - Lock-free ring buffer for async logging
  • Custom Writers - Implement the simple Writer interface

🎨 Terminal Output

The terminal writer provides beautiful, colored output:

DEBUG[01-02|15:04:05] Application starting...
INFO [01-02|15:04:05] Server initialized successfully
WARN [01-02|15:04:05] Config not found, using defaults
ERROR[01-02|15:04:05] Database connection failed         error="timeout" retry=3

Colors:

  • DEBUG - Cyan
  • INFO - Green
  • WARN - Yellow
  • ERROR - Red
  • FATAL - Magenta

πŸ”§ Advanced Usage

Memory-Mapped File Logging
// Create memory-mapped file writer for zero-syscall logging
mmap, err := log.NewMMapWriter("/var/log/app.log", 100*1024*1024) // 100MB
if err != nil {
    panic(err)
}
defer mmap.Close()

logger := log.New()
logger.SetWriter(mmap.Writer())
Asynchronous Logging
// Create async writer with ring buffer
async := log.NewAsyncWriter(log.StdoutTerminal(), 8192)
defer async.Close()

logger := log.New()
logger.SetWriter(async.Writer())

// Logs are written asynchronously
logger.Info("This won't block")
Custom Writers
// Implement your own writer
type CustomWriter struct{}

func (w CustomWriter) Write(p []byte) error {
    // Your custom logic here
    return nil
}

logger := log.New()
logger.SetWriter(CustomWriter{}.Write)
Log Levels
logger := log.New()

// Set minimum log level
logger.SetLevel(log.LevelWarn) // Only Warn, Error, Fatal will be logged

// Check current level
if logger.GetLevel() <= log.LevelDebug {
    // Expensive debug operation
}
Field Types

All field types are available with zero allocations:

logger.Info("event",
    log.String("name", "John"),
    log.Int("age", 30),
    log.Int64("id", 123456789),
    log.Uint("count", 42),
    log.Uint64("total", 9999999),
    log.Float32("score", 98.5),
    log.Float64("precision", 3.14159265359),
    log.Bool("active", true),
    log.Bytes("data", []byte{0x01, 0x02, 0x03}))

πŸ† Benchmarks

Run on Apple M4:

$ go test -bench=. -benchmem

BenchmarkNanoLogger-10              147687733      7.425 ns/op      0 B/op    0 allocs/op
BenchmarkNanoLoggerWithOutput-10    155354494      7.958 ns/op      0 B/op    0 allocs/op
BenchmarkUltimateLogger-10           53423659     18.84 ns/op       0 B/op    0 allocs/op
BenchmarkUltimateLoggerParallel-10   18684834     65.53 ns/op       0 B/op    0 allocs/op
BenchmarkStructuredLogger-10         20530777     59.08 ns/op       0 B/op    0 allocs/op
BenchmarkStructuredLogger5Fields-10  13193077     80.72 ns/op       0 B/op    0 allocs/op
BenchmarkStructuredLogger10Fields-10 10458685    110.7 ns/op        0 B/op    0 allocs/op
BenchmarkZeroAllocLogger-10          19329052     56.89 ns/op     256 B/op    1 allocs/op
BenchmarkUltralog-10                 17233688     70.05 ns/op     256 B/op    1 allocs/op
BenchmarkAsyncWriter-10               7035481    184.6 ns/op      544 B/op    2 allocs/op
BenchmarkMMapWriter-10               11997840     94.14 ns/op     256 B/op    1 allocs/op

πŸ“Š Comparison with Other Loggers

Logger ns/op B/op allocs/op Notes
log (NanoLogger) 7.425 0 0 Fastest possible
log (UltimateLogger) 18.84 0 0 Direct memory writes
log (CompatibilityKV) 57.62 0 0 v0.x compatible with common types
log (StructuredLogger) 59.08 0 0 Type-safe fields
log (Basic) 70.05 256 1 Simple API
zap ~100-200 varies varies
zerolog ~100-150 varies varies
logrus ~500-1000 varies varies

πŸ”¬ How It Works

Zero Allocations
  1. Stack-allocated buffers: All temporary buffers are allocated on the stack
  2. Buffer pools: StructuredLogger uses sync.Pool to eliminate allocations
  3. Direct memory writes: Use unsafe for direct memory manipulation
  4. No interface boxing: Typed fields avoid interface{} allocations
  5. Binary format: Compact encoding reduces memory usage
  6. Lock-free atomics: Avoid mutex allocations
Performance Techniques
  • Cache-line alignment: 64-byte aligned structures
  • Atomic operations: Lock-free level checks and updates
  • Memory-mapped I/O: Zero-syscall writes to files
  • Ring buffers: Lock-free async logging
  • Inlining: Critical paths are inlined by the compiler
  • Direct syscalls: Using Go's runtime linkname for nanotime()

πŸ”„ Migration from v0.x

The new version provides full backward compatibility while offering better performance:

v0.x Style (Still Works!)
// Old code continues to work
log.Info("User action", "username", "john", "action", "login", "ip", "192.168.1.1")
log.Error("Database error", "error", err, "query", sqlQuery)
New Style (Better Performance)
// Use typed fields for zero allocations
log.Info("User action",
    log.String("username", "john"),
    log.String("action", "login"),
    log.String("ip", "192.168.1.1"))
Performance Comparison
  • v0.x style with common types: 57.62 ns/op, 0 allocations
  • Typed fields: 59.08 ns/op, 0 allocations
  • Both are significantly faster than other loggers!

πŸ§ͺ Testing

The library has 85.3% test coverage and passes all tests including race detection:

$ go test -race ./...
ok  github.com/semihalev/log  1.886s

$ go test -cover ./...
ok  github.com/semihalev/log  0.520s  coverage: 85.3% of statements

πŸ“ Examples

High-Performance HTTP Server
// Create the fastest possible logger for request logging
logger := log.NewUltimateLogger()

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    start := time.Now()
    
    // Your handler logic here
    
    // Log with 18.84 ns overhead
    logger.Info(fmt.Sprintf("%s %s %d %dns", 
        r.Method, r.URL.Path, 200, time.Since(start).Nanoseconds()))
})
Production Service
// Structured logger for production with terminal output
logger := log.NewStructured()
logger.SetWriter(log.StdoutTerminal())

// Log with rich context
logger.Info("service started",
    log.String("version", "1.0.0"),
    log.String("env", "production"),
    log.Int("pid", os.Getpid()),
    log.String("node", hostname))

// Log errors with context
logger.Error("database query failed",
    log.String("query", query),
    log.String("error", err.Error()),
    log.Float64("duration_ms", duration.Seconds()*1000))

See more examples in example_test.go and demo/main.go.

🀝 Contributing

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

πŸ“„ License

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

πŸ™ Acknowledgments

  • Built with ❀️ for the Go community
  • Inspired by the need for truly zero-allocation logging
  • Special thanks to all contributors

Note: This logger uses unsafe operations for maximum performance. While thoroughly tested, please evaluate if this fits your risk tolerance for production systems.

Documentation ΒΆ

Overview ΒΆ

Package log provides the world's fastest logging library for Go Zero allocations, zero compromises, pure performance

Example (GlobalLogger) ΒΆ
package main

import (
	"github.com/semihalev/log"
)

func main() {
	// Global logger is ready to use immediately
	log.Info("Starting application")

	// Log with key-value pairs (v0.x compatible)
	log.Info("User logged in", "username", "john", "user_id", 123)

	// Change log level
	log.SetLevel(log.LevelWarn)

	// This won't be logged (below threshold)
	log.Debug("Debug message")

	// This will be logged
	log.Warn("Low memory", "available", "512MB")
}
Example (Structured) ΒΆ
package main

import (
	"github.com/semihalev/log"
)

func main() {
	// Create structured logger with terminal output
	logger := log.NewStructured()
	logger.SetWriter(log.StdoutTerminal())

	// Log with structured fields
	logger.Info("User logged in",
		log.String("username", "john"),
		log.Int("user_id", 12345),
		log.Bool("admin", true))

	logger.Error("Request failed",
		log.String("method", "POST"),
		log.String("path", "/api/users"),
		log.Int("status", 500),
		log.Float64("duration", 1.234))

	// Output shows colored terminal format with fields
}
Example (Terminal) ΒΆ
package main

import (
	"github.com/semihalev/log"
)

func main() {
	// Create logger with beautiful terminal output
	logger := log.New()
	logger.SetWriter(log.StdoutTerminal())

	// Basic logging
	logger.Debug("Starting application")
	logger.Info("Server started successfully")
	logger.Warn("Memory usage is high")
	logger.Error("Failed to connect to database")

	// Output shows colored terminal format
}

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

View Source
const (
	MagicHeader = 0x554C4F47 // "ULOG"
	Version     = 1

	// Cache line size for padding
	CacheLineSize = 64
)

Magic constants for binary format

View Source
const (
	// MS_ASYNC performs asynchronous sync
	MS_ASYNC = 0x1
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Debug ΒΆ

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

Debug logs a debug message using the default logger

func DebugKV ΒΆ added in v1.1.1

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

DebugKV logs debug with key-value pairs

func Error ΒΆ

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

Error logs an error message using the default logger

func ErrorKV ΒΆ added in v1.1.1

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

ErrorKV logs error with key-value pairs

func Fatal ΒΆ added in v1.1.0

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

Fatal logs a fatal message using the default logger and exits

func FatalKV ΒΆ added in v1.1.1

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

FatalKV logs fatal with key-value pairs and exits

func Info ΒΆ

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

Info logs an info message using the default logger

func InfoKV ΒΆ added in v1.1.1

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

InfoKV logs info with key-value pairs

func SetDefault ΒΆ added in v1.1.0

func SetDefault(logger *StructuredLogger)

SetDefault sets the default global logger

Example ΒΆ
package main

import (
	"github.com/semihalev/log"
)

func main() {
	// Create a custom logger
	logger := log.NewStructured()
	logger.SetWriter(log.StderrWriter)
	logger.SetLevel(log.LevelDebug)

	// Set it as the global default
	log.SetDefault(logger)

	// Now all global calls use your custom logger
	log.Debug("This goes to stderr")
}

func SetLevel ΒΆ

func SetLevel(level Level)

SetLevel sets the minimum log level for the default logger

func SetWriter ΒΆ added in v1.1.0

func SetWriter(w Writer)

SetWriter sets the writer for the default logger

func Warn ΒΆ

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

Warn logs a warning message using the default logger

func WarnKV ΒΆ added in v1.1.1

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

WarnKV logs warning with key-value pairs

Types ΒΆ

type AsyncWriter ΒΆ added in v1.0.0

type AsyncWriter struct {
	// contains filtered or unexported fields
}

AsyncWriter wraps a writer with a ring buffer for async operation

func NewAsyncWriter ΒΆ added in v1.0.0

func NewAsyncWriter(w Writer, bufferSize int) *AsyncWriter

NewAsyncWriter creates a new async writer

func (*AsyncWriter) Close ΒΆ added in v1.0.0

func (aw *AsyncWriter) Close() error

Close stops the async writer

func (*AsyncWriter) Write ΒΆ added in v1.0.0

func (aw *AsyncWriter) Write(b []byte) error

Write adds data to the ring buffer

func (*AsyncWriter) Writer ΒΆ added in v1.0.0

func (aw *AsyncWriter) Writer() Writer

Writer returns a Writer function for the logger

type DiscardZeroWriter ΒΆ added in v1.0.0

type DiscardZeroWriter struct{}

DiscardZeroWriter discards all output with zero allocations

func (DiscardZeroWriter) WriteZero ΒΆ added in v1.0.0

func (DiscardZeroWriter) WriteZero(*[256]byte, int)

type Entry ΒΆ added in v1.0.0

type Entry struct {
	// contains filtered or unexported fields
}

Entry represents a log entry in the ring buffer

type Field ΒΆ added in v0.1.2

type Field struct {
	Key  string
	Type FieldType
	// contains filtered or unexported fields
}

Field represents a typed field without allocations

func Any ΒΆ added in v0.1.2

func Any(key string, value any) Field

Helper to create field from any type (for convenience)

func Bool ΒΆ added in v0.1.2

func Bool(key string, val bool) Field

Bool creates a bool field

func Bytes ΒΆ added in v1.0.0

func Bytes(key string, val []byte) Field

Bytes creates a bytes field

func Float32 ΒΆ added in v1.0.0

func Float32(key string, val float32) Field

Float32 creates a float32 field

func Float64 ΒΆ added in v0.1.2

func Float64(key string, val float64) Field

Float64 creates a float64 field

func Int ΒΆ added in v0.1.2

func Int(key string, val int) Field

Int creates an int field

func Int64 ΒΆ added in v0.1.2

func Int64(key string, val int64) Field

Int64 creates an int64 field

func String ΒΆ added in v0.1.2

func String(key string, val string) Field

String creates a string field

func Uint ΒΆ added in v1.0.0

func Uint(key string, val uint) Field

Uint creates a uint field

func Uint64 ΒΆ added in v1.0.0

func Uint64(key string, val uint64) Field

Uint64 creates a uint64 field

type FieldType ΒΆ added in v0.1.5

type FieldType uint8

FieldType represents the type of a field

const (
	FieldTypeInt FieldType = iota
	FieldTypeUint
	FieldTypeFloat32
	FieldTypeFloat64
	FieldTypeString
	FieldTypeBool
	FieldTypeBytes
)

type KV ΒΆ added in v1.1.1

type KV struct {
	Key   string
	Value any
}

KV represents a key-value pair for compatibility

type Level ΒΆ added in v1.0.0

type Level uint8

Level represents log severity

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

type Logger ΒΆ

type Logger struct {
	// contains filtered or unexported fields
}

Logger is the core logger - exactly one cache line (64 bytes)

func New ΒΆ

func New() *Logger

New creates a new ultra-fast logger

func (*Logger) Debug ΒΆ

func (l *Logger) Debug(msg string)

Debug logs a debug message

func (*Logger) Error ΒΆ

func (l *Logger) Error(msg string)

Error logs an error message

func (*Logger) Fatal ΒΆ added in v1.0.0

func (l *Logger) Fatal(msg string)

Fatal logs a fatal message and exits

func (*Logger) GetLevel ΒΆ added in v1.0.0

func (l *Logger) GetLevel() Level

GetLevel atomically gets the log level

func (*Logger) Info ΒΆ

func (l *Logger) Info(msg string)

Info logs an info message

func (*Logger) SetLevel ΒΆ

func (l *Logger) SetLevel(level Level)

SetLevel atomically sets the log level

func (*Logger) SetWriter ΒΆ added in v1.0.0

func (l *Logger) SetWriter(w Writer)

SetWriter atomically sets the writer

func (*Logger) Warn ΒΆ

func (l *Logger) Warn(msg string)

Warn logs a warning message

type MMapWriter ΒΆ added in v1.0.0

type MMapWriter struct {
	// contains filtered or unexported fields
}

MMapWriter provides zero-copy, zero-syscall logging via memory-mapped files

func NewMMapWriter ΒΆ added in v1.0.0

func NewMMapWriter(path string, size int64) (*MMapWriter, error)

NewMMapWriter creates a new memory-mapped file writer

func (*MMapWriter) Close ΒΆ added in v1.0.0

func (w *MMapWriter) Close() error

Close unmaps and closes the file

func (*MMapWriter) Write ΒΆ added in v1.0.0

func (w *MMapWriter) Write(b []byte) error

Write writes data to the memory-mapped file

func (*MMapWriter) Writer ΒΆ added in v1.0.0

func (w *MMapWriter) Writer() Writer

Writer returns a Writer function for the logger

type NanoLogger ΒΆ added in v1.0.0

type NanoLogger struct {
	// contains filtered or unexported fields
}

NanoLogger - Even faster with pre-allocated message buffers

func NewNanoLogger ΒΆ added in v1.0.0

func NewNanoLogger(output func([]byte)) *NanoLogger

NewNanoLogger creates a logger that writes to a function

func (*NanoLogger) Info ΒΆ added in v1.0.0

func (nl *NanoLogger) Info(buf []byte, msg string) int

Info logs with zero allocations using caller's buffer

type Record ΒΆ

type Record struct {
	Sequence uint64 // 8 bytes - unique sequence
	Time     uint64 // 8 bytes - unix nano timestamp
	Level    Level  // 1 byte

	MsgLen  uint16 // 2 bytes - message length
	DataLen uint16 // 2 bytes - data length

	Data [32]byte // 32 bytes - inline storage for small messages
	// contains filtered or unexported fields
}

Record represents a log entry - exactly one cache line (64 bytes)

type RingBuffer ΒΆ added in v1.0.0

type RingBuffer struct {
	// contains filtered or unexported fields
}

RingBuffer is a lock-free single producer, multiple consumer ring buffer

func NewRingBuffer ΒΆ added in v1.0.0

func NewRingBuffer(size int) *RingBuffer

NewRingBuffer creates a new ring buffer with the given size (must be power of 2)

func (*RingBuffer) Get ΒΆ added in v1.0.0

func (rb *RingBuffer) Get() ([]byte, bool)

Get retrieves data from the ring buffer (multiple consumers)

func (*RingBuffer) Put ΒΆ added in v1.0.0

func (rb *RingBuffer) Put(data []byte) bool

Put adds data to the ring buffer (single producer)

type SimpleLogger ΒΆ added in v1.1.1

type SimpleLogger struct {
	*Logger
}

Simple logger that accepts any values (like v0.x)

func NewSimple ΒΆ added in v1.1.1

func NewSimple() *SimpleLogger

NewSimple creates a simple logger that accepts any values

func (*SimpleLogger) Debug ΒΆ added in v1.1.1

func (l *SimpleLogger) Debug(v ...any)

Debug logs debug accepting any values

func (*SimpleLogger) Debugf ΒΆ added in v1.1.1

func (l *SimpleLogger) Debugf(format string, v ...any)

Debugf logs formatted debug

func (*SimpleLogger) Error ΒΆ added in v1.1.1

func (l *SimpleLogger) Error(v ...any)

Error logs error accepting any values

func (*SimpleLogger) Errorf ΒΆ added in v1.1.1

func (l *SimpleLogger) Errorf(format string, v ...any)

Errorf logs formatted error

func (*SimpleLogger) Fatal ΒΆ added in v1.1.1

func (l *SimpleLogger) Fatal(v ...any)

Fatal logs fatal accepting any values and exits

func (*SimpleLogger) Fatalf ΒΆ added in v1.1.1

func (l *SimpleLogger) Fatalf(format string, v ...any)

Fatalf logs formatted fatal and exits

func (*SimpleLogger) Info ΒΆ added in v1.1.1

func (l *SimpleLogger) Info(v ...any)

Info logs info accepting any values

func (*SimpleLogger) Infof ΒΆ added in v1.1.1

func (l *SimpleLogger) Infof(format string, v ...any)

Infof logs formatted info

func (*SimpleLogger) Warn ΒΆ added in v1.1.1

func (l *SimpleLogger) Warn(v ...any)

Warn logs warning accepting any values

func (*SimpleLogger) Warnf ΒΆ added in v1.1.1

func (l *SimpleLogger) Warnf(format string, v ...any)

Warnf logs formatted warning

type StructuredLogger ΒΆ added in v0.1.2

type StructuredLogger struct {
	*Logger
}

StructuredLogger provides zero-allocation structured logging

func Default ΒΆ added in v1.1.0

func Default() *StructuredLogger

Default returns the current default logger

func NewStructured ΒΆ added in v0.1.2

func NewStructured() *StructuredLogger

NewStructured creates a new structured logger

func (*StructuredLogger) Debug ΒΆ added in v0.1.2

func (l *StructuredLogger) Debug(msg string, fields ...Field)

Debug logs a debug message with fields

func (*StructuredLogger) DebugKV ΒΆ added in v1.1.1

func (l *StructuredLogger) DebugKV(msg string, keysAndValues ...any)

DebugKV logs debug with key-value pairs (backward compatible)

func (*StructuredLogger) Error ΒΆ added in v0.1.2

func (l *StructuredLogger) Error(msg string, fields ...Field)

Error logs an error message with fields

func (*StructuredLogger) ErrorKV ΒΆ added in v1.1.1

func (l *StructuredLogger) ErrorKV(msg string, keysAndValues ...any)

ErrorKV logs error with key-value pairs (backward compatible)

func (*StructuredLogger) Fatal ΒΆ added in v1.0.0

func (l *StructuredLogger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message with fields and exits

func (*StructuredLogger) FatalKV ΒΆ added in v1.1.1

func (l *StructuredLogger) FatalKV(msg string, keysAndValues ...any)

FatalKV logs fatal with key-value pairs and exits (backward compatible)

func (*StructuredLogger) Info ΒΆ added in v0.1.2

func (l *StructuredLogger) Info(msg string, fields ...Field)

Info logs an info message with fields

func (*StructuredLogger) InfoKV ΒΆ added in v1.1.1

func (l *StructuredLogger) InfoKV(msg string, keysAndValues ...any)

InfoKV logs info with key-value pairs (backward compatible)

func (*StructuredLogger) Warn ΒΆ added in v0.1.2

func (l *StructuredLogger) Warn(msg string, fields ...Field)

Warn logs a warning message with fields

func (*StructuredLogger) WarnKV ΒΆ added in v1.1.1

func (l *StructuredLogger) WarnKV(msg string, keysAndValues ...any)

WarnKV logs warning with key-value pairs (backward compatible)

type TerminalWriter ΒΆ added in v1.0.0

type TerminalWriter struct {
	// contains filtered or unexported fields
}

TerminalWriter decodes binary log format and outputs beautiful terminal format

func NewTerminalWriter ΒΆ added in v1.0.0

func NewTerminalWriter(out *os.File) *TerminalWriter

NewTerminalWriter creates a new terminal writer

func (*TerminalWriter) Write ΒΆ added in v1.0.0

func (w *TerminalWriter) Write(b []byte) error

Write decodes binary log and outputs formatted text

func (*TerminalWriter) Writer ΒΆ added in v1.0.0

func (w *TerminalWriter) Writer() Writer

Writer returns a Writer function for the logger

type UltimateLogger ΒΆ added in v1.0.0

type UltimateLogger struct {
	// contains filtered or unexported fields
}

UltimateLogger - The world's fastest logger with ZERO allocations Uses direct memory writes and inlined operations

func NewUltimateLogger ΒΆ added in v1.0.0

func NewUltimateLogger() *UltimateLogger

NewUltimateLogger creates the ultimate zero-allocation logger

func (*UltimateLogger) Debug ΒΆ added in v1.0.0

func (l *UltimateLogger) Debug(msg string)

Debug logs a debug message

func (*UltimateLogger) Error ΒΆ added in v1.0.0

func (l *UltimateLogger) Error(msg string)

Error logs an error message

func (*UltimateLogger) GetBuffer ΒΆ added in v1.0.0

func (l *UltimateLogger) GetBuffer() ([]byte, uint64)

GetBuffer returns the current position in the buffer for reading

func (*UltimateLogger) Info ΒΆ added in v1.0.0

func (l *UltimateLogger) Info(msg string)

Info logs with absolutely zero allocations

func (*UltimateLogger) SetLevel ΒΆ added in v1.0.0

func (l *UltimateLogger) SetLevel(level Level)

SetLevel sets the log level

type Writer ΒΆ added in v1.0.0

type Writer func([]byte) error

Writer is a function that writes log data

var DiscardWriter Writer = func(b []byte) error {
	return nil
}

DiscardWriter discards all output

var StderrWriter Writer = func(b []byte) error {
	_, err := os.Stderr.Write(b)
	return err
}

StderrWriter writes to stderr

var StdoutWriter Writer = func(b []byte) error {
	_, err := os.Stdout.Write(b)
	return err
}

StdoutWriter writes to stdout

func StderrTerminal ΒΆ added in v1.0.0

func StderrTerminal() Writer

StderrTerminal creates a terminal writer for stderr

func StdoutTerminal ΒΆ added in v1.0.0

func StdoutTerminal() Writer

StdoutTerminal creates a terminal writer for stdout

type ZeroAllocLogger ΒΆ added in v0.1.2

type ZeroAllocLogger struct {
	// contains filtered or unexported fields
}

ZeroAllocLogger is the world's fastest logger - truly zero allocations

func NewZeroAllocLogger ΒΆ added in v0.1.2

func NewZeroAllocLogger() *ZeroAllocLogger

NewZeroAllocLogger creates the fastest possible logger

func (*ZeroAllocLogger) Debug ΒΆ added in v0.1.2

func (l *ZeroAllocLogger) Debug(msg string)

Debug logs a debug message

func (*ZeroAllocLogger) Error ΒΆ added in v0.1.2

func (l *ZeroAllocLogger) Error(msg string)

Error logs an error message

func (*ZeroAllocLogger) Info ΒΆ added in v0.1.2

func (l *ZeroAllocLogger) Info(msg string)

Info logs an info message with zero allocations

func (*ZeroAllocLogger) SetLevel ΒΆ added in v0.1.2

func (l *ZeroAllocLogger) SetLevel(level Level)

SetLevel atomically sets the log level

func (*ZeroAllocLogger) SetZeroWriter ΒΆ added in v1.0.0

func (l *ZeroAllocLogger) SetZeroWriter(w ZeroWriter)

SetZeroWriter atomically sets the writer

func (*ZeroAllocLogger) Warn ΒΆ added in v0.1.2

func (l *ZeroAllocLogger) Warn(msg string)

Warn logs a warning message

type ZeroWriter ΒΆ added in v1.0.0

type ZeroWriter interface {
	// WriteZero writes with zero allocations - buffer is reused
	WriteZero(buf *[256]byte, n int)
}

ZeroWriter is a zero-allocation writer interface

Jump to

Keyboard shortcuts

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