hyperlogger

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: GPL-3.0 Imports: 15 Imported by: 0

README

Hyperlogger

Go CodeQL golangci-lint

A high-performance, feature-rich logging package for Go applications, focusing on reliability, contextual information, and flexibility.

Features

  • Multiple Log Levels - Supports TRACE, DEBUG, INFO, WARN, ERROR, and FATAL log levels
  • Structured Logging - Add fields and context to your log entries
  • Multiple Output Formats - Output as text or JSON
  • Color Support - Terminal-aware color coding based on log levels
  • File Output - Write logs to files with automatic rotation and compression
  • Performance Optimized - Asynchronous logging with fallback to synchronous for critical logs - Optimized buffer pooling with multiple size classes to minimize allocations - Caller caching for improved performance - Log sampling for high-volume environments
  • Context Integration - Extract and propagate request context information
  • Comprehensive Error Handling - Optional stack traces and detailed error reporting
  • Multiple Output Destinations - Write to console, files, or custom writers
  • Hook System - Register callbacks for custom processing of log entries
  • Fluent Configuration API - Simple, chainable configuration with sensible defaults

Performance

The logger is designed for high performance, with a focus on low latency and minimal memory overhead. It uses a buffered output system to reduce the number of system calls and optimize throughput.

It also implements a sampling mechanism to control log volume in high-throughput scenarios, ensuring that critical logs are captured while reducing the overall load on the system.

Benchmark Results
make bench-mem
go test -bench=. -benchtime=3s -benchmem -run=^-memprofile=mem.out ./...
PASS
ok   github.com/hyp3rd/hyperlogger 0.195s
goos: darwin
goarch: arm64
pkg: github.com/hyp3rd/hyperlogger/pkg/adapter
cpu: Apple M2 Pro
BenchmarkAsyncWriter/drop_newest-12          100937802     35.46 ns/op       32 B/op        1 allocs/op
BenchmarkAsyncWriter/drop_oldest-12          55707408      63.86 ns/op       32 B/op        1 allocs/op
BenchmarkAsyncWriter/block-12                   14348     253723 ns/op      196 B/op        2 allocs/op
BenchmarkAsyncWriter/handoff-12                 28059     128678 ns/op      171 B/op        2 allocs/op
PASS

BenchmarkAdapterLoggingAllocations/Console/NoFields-12          13485333        239.1 ns/op       96 B/op        2 allocs/op
BenchmarkAdapterLoggingAllocations/Console/WithField-12         14182243        251.9 ns/op       96 B/op        2 allocs/op
BenchmarkAdapterLoggingAllocations/Console/WithFields-12        13647421        263.6 ns/op       96 B/op        2 allocs/op
BenchmarkAdapterLoggingAllocations/JSON/NoFields-12             13399689        259.3 ns/op       64 B/op        1 allocs/op
BenchmarkAdapterLoggingAllocations/JSON/WithField-12            13288815        269.2 ns/op       64 B/op        1 allocs/op
BenchmarkAdapterLoggingAllocations/JSON/WithFields-12           12464323        288.6 ns/op       64 B/op        1 allocs/op
BenchmarkAdapterLogging/TextLogging_NoFields-12                  5470588        712.5 ns/op      744 B/op        5 allocs/op
BenchmarkAdapterLogging/TextLogging_5Fields-12                   5021596        756.9 ns/op      993 B/op        5 allocs/op
BenchmarkAdapterLogging/JSONLogging_NoFields-12                  4057200        839.8 ns/op      820 B/op        5 allocs/op
BenchmarkAdapterLogging/JSONLogging_5Fields-12                   3780207        962.4 ns/op      992 B/op        5 allocs/op
BenchmarkAdapterLogging/TextLogging_MultiWriter-12               5229261        699.5 ns/op      865 B/op        5 allocs/op
PASS

Installation

go get -u github.com/hyp3rd/hyperlogger

Quick Start

package main

import (
    "context"
    "fmt"
    "net/http"
    "os"

    logger "github.com/hyp3rd/hyperlogger"
    "github.com/hyp3rd/hyperlogger/adapter"
    "github.com/hyp3rd/hyperlogger/internal/constants"
)

func main() {
    // Create a default logger that writes to stdout
    log, err := adapter.NewAdapter(logger.DefaultConfig())
    if err != nil {
        panic(err)
    }

    // Always call Sync() before application exit to ensure all logs are written
    defer func() {
        err := log.Sync()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Failed to sync logger: %v\n", err)
        }
    }()

    // Basic logging
    log.Info("Hello, Logger!")

    // With fields
    log.WithField("user", "john_doe").Info("User logged in")

    // With error
    err = someFunc()
    if err != nil {
        log.WithError(err).Error("Something went wrong")
    }

    logger.RegisterContextExtractor(func(ctx context.Context) []logger.Field {
        if reqID, ok := ctx.Value(constants.RequestKey{}).(string); ok && reqID != "" {
            return []logger.Field{{Key: "request_id", Value: reqID}}
        }

        return nil
    })

    exporter := logger.NewAsyncMetricsExporter()
    logger.RegisterAsyncMetricsHandler(exporter.Observe)
    http.Handle("/metrics", exporter)

    go func() {
        if err := http.ListenAndServe(":9090", nil); err != nil {
            fmt.Fprintf(os.Stderr, "metrics server error: %v\n", err)
        }
    }()
}

Fluent Configuration API

For cleaner, more readable configuration, use the fluent builder API:

// Development logger with console output
log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithConsoleOutput().
    WithDevelopmentDefaults().
    WithField("service", "auth-service").
    Build())

// Production logger with file output and rotation
log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithFileOutput("/var/log/app.log").
    WithFileRotation(100*1024*1024, true). // 100MB with compression
    WithFileRetention(7, 10). // 7 days, max 10 backup files
    WithProductionDefaults().
    WithAsyncLogging(true, 1024). // Enable async logging with buffer size
    Build())

Application Logger

For applications, you can use the app package which provides environment-aware logger initialization:

package main

import (
    "context"
    "fmt"
    "os"
    logger "github.com/hyp3rd/hyperlogger/log"
)

func main() {
    // Create cancellable context
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // Create an application logger with environment and service information
    log, err := logger.New(ctx, "development", "my-service")
    if err != nil {
        panic(err)
    }

    defer func() {
        err := log.Sync()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Failed to sync logger: %v\n", err)
        }
    }()

    // In development: Text output with debug level
    // In production: JSON output with info level

    log.Info("Application started")

    log.WithError(fmt.Errorf("failed to create client")).Fatal("Failed to create client")

    log.WithFields(logger.Field{
        Key:   "metadata",
        Value: "example",
    }).Info("Processing request")
}

Configuration

Logging Levels

The logger supports multiple log levels, allowing you to control the verbosity of your logs. The available log levels are:

logger.TraceLevel // Most verbose
logger.DebugLevel // Debug information
logger.InfoLevel  // General operational information
logger.WarnLevel  // Warnings
logger.ErrorLevel // Errors
logger.FatalLevel // Fatal errors
Output Configuration
// Using traditional configuration
config := logger.DefaultConfig()

// Configure output destination
config.Output = os.Stdout  // Standard output
// Or use file output with rotation and compression
fileWriter, err := output.NewFileWriter(output.FileConfig{
    Path:     "/var/log/my_app.log",
    MaxSize:  100 * 1024 * 1024, // 100MB
    Compress: true,
    CompressionConfig: &output.CompressionConfig{
        Level: output.CompressionSpeed, // Optimize for speed
    },
})
if err != nil {
    panic(err)
}
config.Output = fileWriter

// Or use multiple outputs
multiWriter, err := output.NewMultiWriter(
    output.NewConsoleWriter(os.Stdout, output.ColorModeAuto),
    fileWriter,
)
if err != nil {
    panic(err)
}
config.Output = multiWriter

// Set log level
config.Level = logger.InfoLevel

// Configure colors
config.Color.Enable = true
config.Color.ForceTTY = false // Only use colors when output is a TTY

// Format settings
config.EnableJSON = false // Use text format (default is JSON)
config.EnableCaller = true // Include caller information
config.EnableStackTrace = true // Include stack traces for errors
config.TimeFormat = time.RFC3339 // Set timestamp format

// Configure asynchronous logging
config.EnableAsync = true // Use non-blocking asynchronous logging
config.AsyncBufferSize = 1024 // Buffer size for async logging

// Configure log sampling for high-volume scenarios
config.Sampling = logger.SamplingConfig{
    Enabled:          true,
    Initial:          1000,   // Log first 1000 entries normally
    Thereafter:       100,    // Then log only 1/100 entries
    PerLevelThreshold: true,  // Apply thresholds per level
}
Create a Logger
// With the adapter directly
log, err := adapter.NewAdapter(config)
if err != nil {
    panic(err)
}

// Or use a no-op logger for testing
noopLog := logger.NewNoop()

API Reference

Basic Logging Methods
log.Trace("Detailed debugging information")
log.Debug("Debugging information")
log.Info("General information")
log.Warn("Warning message")
log.Error("Error message")
log.Fatal("Fatal error message")
Formatted Logging
log.Tracef("User %s made %d requests", username, count)
log.Debugf("Processing took %v", duration)
log.Infof("Server started on port %d", port)
log.Warnf("High memory usage: %.2f%%", memoryPercent)
log.Errorf("Failed to connect to %s: %v", host, err)
log.Fatalf("Critical system failure: %v", err)
Contextual Logging
// With request context
log = log.WithContext(ctx)

// With fields
log = log.WithField("user_id", userID)
log = log.WithFields(
    logger.Field{Key: "request_id", Value: reqID},
    logger.Field{Key: "client_ip", Value: clientIP},
)

// With error information
log = log.WithError(err)
// Register a global extractor that enriches every logger with trace metadata
logger.RegisterContextExtractor(func(ctx context.Context) []logger.Field {
    if traceID, ok := ctx.Value(constants.TraceKey{}).(string); ok && traceID != "" {
        return []logger.Field{{Key: "trace_id", Value: traceID}}
    }
    return nil
})

Global extractors run in addition to per-logger extractors configured through the builder, making it easy to centralize cross-cutting enrichment logic.

Sync - Ensuring Logs are Written

When using asynchronous logging, it's crucial to call the Sync() method before your application exits to ensure all buffered logs are written:

// Make sure all logs are written before exit
err := log.Sync()
if err != nil {
    fmt.Fprintf(os.Stderr, "Failed to sync logger: %v\n", err)
}

For convenience, you can use a defer statement at the start of your main() function:

defer func() {
    err := log.Sync()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Failed to sync logger: %v\n", err)
    }
}()

Hook System

The logger supports hooks for custom processing of log entries:

// Create a metrics hook
metricsHook := &MetricsHook{}

// Create an alert hook
alertHook := &AlertHook{}

// Build a logger with hooks
log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithConsoleOutput().
    WithField("service", "auth-service").
    WithHook("metrics", metricsHook).
    WithHook("alerts", alertHook).
    Build())

Example hook implementation:

// MetricsHook is a sample hook that tracks error counts.
type MetricsHook struct {
    errorCount int
}

// OnLog implements logger.Hook interface
func (m *MetricsHook) OnLog(entry *logger.Entry) error {
    if entry.Level == logger.ErrorLevel {
        m.errorCount++
        // Send to metrics system...
    }
    return nil
}

// Levels implements logger.Hook interface
func (m *MetricsHook) Levels() []logger.Level {
    return []logger.Level{logger.ErrorLevel, logger.FatalLevel}
}

// Register a global error hook
logger.RegisterHook(logger.ErrorLevel, func(ctx context.Context, entry *logger.Entry) error {
    errorCounter.Inc()
    return nil
})

Advanced Features

Asynchronous Logging
Drop Handling Contracts

When the async buffer overflows you can observe dropped payloads via two handlers:

  • AsyncDropHandler func([]byte) keeps the legacy contract by copying the payload before invoking your callback.
  • AsyncDropPayloadHandler DropPayloadHandler delivers a richer DropPayload object that reuses the pooled buffer. Within the handler you can: - Inspect the payload with Bytes() or Size(). - Copy it into your own storage via AppendTo(dst []byte). - Call Retain() to take ownership of the existing buffer and release it later with the returned PayloadLease.Release(), eliminating duplicate allocations when you persist or forward the log.

If you retain the payload you must call Release() once you are done so the async writer can recycle the buffer. If you skip Retain(), the writer reclaims the buffer automatically after the handler returns.

Asynchronous logging decouples logging operations from your application's main execution path, significantly improving performance:

// Enable asynchronous logging with a buffer size of 1024
log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithConsoleOutput().
    WithAsyncLogging(true, 1024).
    Build())

The AsyncWriter implementation provides:

  • Non-blocking write operations (falls back to error when buffer is full)
  • Buffered channel for high throughput
  • Proper cleanup with the Sync() method
  • Configurable buffer size and timeout
  • Error handling for failed write operations
  • Multiple overflow strategies (drop_newest, drop_oldest, block, handoff)
  • Metrics callbacks that surface queue depth, drop counts, synchronous bypasses, and write failures
  • Drop callbacks that can either copy payloads (AsyncDropHandler) or reuse pooled buffers via leases (AsyncDropPayloadHandler)
log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithConsoleOutput().
    WithAsyncLogging(true, 1024).
    WithAsyncOverflowStrategy(logger.AsyncOverflowHandoff).
    WithAsyncMetricsHandler(exporter.Observe).
    Build())
Async Metrics Exporter

Expose async writer health metrics via a Prometheus-style endpoint:

exporter := logger.NewAsyncMetricsExporter()
logger.RegisterAsyncMetricsHandler(exporter.Observe)
http.Handle("/metrics", exporter)

This exporter tracks enqueued, processed, dropped, retried, and bypassed logs as well as the current queue depth.

Log Sampling

When dealing with high-volume logging, you can enable sampling to prevent overwhelming your system:

// Allow first 1000 logs at each level, then only log 1/100
b := logger.NewConfigBuilder().
    WithConsoleOutput().
    WithSampling(true, 1000, 100, true).
    WithSamplingRule(logger.DebugLevel, logger.SamplingRule{Enabled: true, Initial: 200, Thereafter: 10}).
    WithSamplingRule(logger.TraceLevel, logger.SamplingRule{Enabled: false})

log, err := adapter.NewAdapter(*b.Build())

Per-level sampling rules keep critical log levels verbosely while aggressively sampling noisy ones.

Middleware Helpers

Seed context values automatically using the provided HTTP and gRPC middleware:

// HTTP middleware enriches context with request identifiers.
handler := httpmw.ContextMiddleware()(nextHandler)

// gRPC interceptor (build with -tags grpc) maps incoming metadata into context.
interceptor := grpcmw.UnaryServerInterceptor(
    grpcmw.WithTraceKey("x-trace"),
    grpcmw.WithRequestKey("x-request"),
)
grpc.NewServer(grpc.UnaryInterceptor(interceptor))

Downstream logging code can then access these values via context extractors or the built-in key mappings.

Async Benchmarks

Evaluate how overflow strategies behave under sustained load:

go test -bench BenchmarkAsyncWriter -benchmem ./internal/output

This benchmark introduces artificial back-pressure to surface throughput differences between the drop, block, and handoff strategies.

Enhanced File Management

Control compression and retention policies for log files:

log, err := adapter.NewAdapter(*logger.NewConfigBuilder().
    WithFileOutput("/var/log/app.log").
    WithFileRotation(100*1024*1024, true).
    WithFileCompression(1). // Fast compression (1=speed, 9=best compression)
    WithFileRetention(7, 10). // Keep logs for 7 days, max 10 files
    Build())

Performance Considerations

  • Buffer Optimization: The logger uses multiple buffer size classes (512B to 64KB) for efficient memory use
  • Sampling Control: Reduce log volume in high-throughput environments while ensuring critical logs are captured
  • Async Processing: Logs are processed asynchronously by default, with fallback to synchronous for critical logs
  • Memory Management: Proper pooling of buffers and field slices to reduce garbage collection pressure
  • Caller Caching: File and line information is cached to reduce runtime.Caller overhead
  • Efficient Compression: Configurable compression with buffer pooling for rotated log files

When using the logger in performance-critical applications:

  • Use appropriate log levels to avoid unnecessary processing
  • Enable sampling for high-volume logs that aren't critical
  • Always call the Sync() method before application exit to ensure all buffered logs are written
  • Consider using the JSON format in production for more efficient parsing
  • Use async logging for improved performance, but remember to call Sync() before exit

Contributing

Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.

Documentation

Overview

Package hyperlogger defines a flexible, high-performance logging system for Go applications.

This package provides a comprehensive logging abstraction that supports: - Multiple log levels (Trace, Debug, Info, Warn, Error, Fatal) - Structured logging with typed fields - Context-aware logging for propagating request metadata - Color-coded output for terminal readability - Error integration with optional stack traces - Multiple output formats (text and JSON) - Asynchronous logging with fallback to synchronous for critical messages - Log file rotation and compression

The core Logger interface defined in this package serves as the foundation for all logging operations throughout applications using this library. Concrete implementations of this interface are provided by the adapter package.

This separation of interface from implementation allows for flexibility in logging backends while maintaining a consistent API for application code.

Basic usage:

// Create a logger with default configuration
log, err := adapter.NewAdapter(logger.DefaultConfig())
if err != nil {
	panic(err)
}

// Log messages at different levels
log.Info("Application started")
log.WithField("user", "admin").Debug("User logged in")
log.WithError(err).Error("Operation failed")

Always call Sync() before application exit to ensure all logs are written:

defer log.Sync()

Index

Constants

View Source
const (
	Black   = "\x1b[30m"
	Red     = "\x1b[31m"
	Green   = "\x1b[32m"
	Yellow  = "\x1b[33m"
	Blue    = "\x1b[34m"
	Magenta = "\x1b[35m"
	Cyan    = "\x1b[36m"
	White   = "\x1b[37m"

	BoldBlack   = "\x1b[30;1m"
	BoldRed     = "\x1b[31;1m"
	BoldGreen   = "\x1b[32;1m"
	BoldYellow  = "\x1b[33;1m"
	BoldBlue    = "\x1b[34;1m"
	BoldMagenta = "\x1b[35;1m"
	BoldCyan    = "\x1b[36;1m"
	BoldWhite   = "\x1b[37;1m"

	// Reset resets the terminal's color settings.
	Reset = "\x1b[0m"
)
View Source
const (
	// DefaultTimeFormat is the default time format for log entries.
	DefaultTimeFormat = time.RFC3339
	// DefaultLevel is the default logging level.
	DefaultLevel = InfoLevel
	// DefaultBufferSize is the default size of the log buffer.
	DefaultBufferSize = 4096
	// DefaultAsyncBufferSize is the default size of the async log buffer.
	DefaultAsyncBufferSize = 1024
	// LogFilePermissions are the default file permissions for log files.
	LogFilePermissions = 0o666
	// DefaultMaxFileSizeMB is the default maximum size in MB for log files before rotation.
	DefaultMaxFileSizeMB = 100
	// DefaultCompression determines if log files are compressed by default.
	DefaultCompression = true
	// DefaultSamplingInitial is the default number of logs before sampling starts.
	DefaultSamplingInitial = 100
	// DefaultSamplingThereafter is the default sampling rate (1/N) after initial logs.
	DefaultSamplingThereafter = 10
)

Variables

This section is empty.

Functions

func ClearAsyncMetricsHandlers added in v0.0.4

func ClearAsyncMetricsHandlers()

ClearAsyncMetricsHandlers removes all registered async metrics handlers.

func ClearContextExtractors added in v0.0.4

func ClearContextExtractors()

ClearContextExtractors removes all global context extractors.

func DefaultLevelColors

func DefaultLevelColors() map[Level]string

DefaultLevelColors returns a map of log levels to their default ANSI color codes. The colors are chosen to provide good visibility and contrast for each log level.

func EmitAsyncMetrics added in v0.0.4

func EmitAsyncMetrics(ctx context.Context, metrics AsyncMetrics)

EmitAsyncMetrics notifies global handlers with the provided metrics snapshot.

func FireRegisteredHooks

func FireRegisteredHooks(ctx context.Context, entry *Entry) []error

FireRegisteredHooks executes the global LogHookFuncs registered via RegisterHook/RegisterGlobalHook and returns any errors they produced.

func ParseLevel

func ParseLevel(level string) (string, error)

ParseLevel parses the given log level string and returns the normalized lowercase string representation of the level, or an error if the level is invalid.

func RegisterAsyncMetricsHandler added in v0.0.4

func RegisterAsyncMetricsHandler(handler AsyncMetricsHandler)

RegisterAsyncMetricsHandler adds a global handler invoked when async metrics are emitted.

func RegisterContextExtractor added in v0.0.4

func RegisterContextExtractor(extractor ContextExtractor)

RegisterContextExtractor adds a global context extractor that runs for every logger.

func RegisterGlobalHook

func RegisterGlobalHook(hookFunc LogHookFunc)

RegisterGlobalHook adds a hook function for all log levels.

func RegisterHook

func RegisterHook(level Level, hookFunc LogHookFunc)

RegisterHook adds a hook function for the specified log level. All hooks registered at a given level will be executed in registration order whenever a log message is generated at that level.

If the level is invalid, the hook will be registered at all levels.

func SetOutput

func SetOutput(output string) (io.Writer, error)

SetOutput sets the output destination for the logger. It accepts "stdout", "stderr", or a file path as input. If a file path is provided, it will create the file if it doesn't exist and open it in append mode. The function returns the io.Writer for the selected output and any error that occurred.

func UnregisterAllHooks

func UnregisterAllHooks()

UnregisterAllHooks removes all hooks for all levels.

func UnregisterHooks

func UnregisterHooks(level Level)

UnregisterHooks removes all hooks for the specified level.

Types

type AsyncMetrics added in v0.0.4

type AsyncMetrics struct {
	Enqueued   uint64
	Processed  uint64
	Dropped    uint64
	WriteError uint64
	Retried    uint64
	QueueDepth int
	Bypassed   uint64
}

AsyncMetrics represents health metrics emitted by the async writer.

type AsyncMetricsExporter added in v0.0.4

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

AsyncMetricsExporter exposes async writer metrics via a Prometheus-style HTTP handler. Register the Observe method using RegisterAsyncMetricsHandler to begin collecting data.

func NewAsyncMetricsExporter added in v0.0.4

func NewAsyncMetricsExporter() *AsyncMetricsExporter

NewAsyncMetricsExporter creates a new exporter instance.

func (*AsyncMetricsExporter) Observe added in v0.0.4

func (e *AsyncMetricsExporter) Observe(_ context.Context, metrics AsyncMetrics)

Observe can be registered with RegisterAsyncMetricsHandler to record async metrics snapshots.

func (*AsyncMetricsExporter) ServeHTTP added in v0.0.4

func (e *AsyncMetricsExporter) ServeHTTP(w http.ResponseWriter, _ *http.Request)

ServeHTTP renders the metrics using Prometheus exposition format.

type AsyncMetricsHandler added in v0.0.4

type AsyncMetricsHandler func(context.Context, AsyncMetrics)

AsyncMetricsHandler receives async writer metrics.

type AsyncOverflowStrategy

type AsyncOverflowStrategy uint8

AsyncOverflowStrategy defines how the async writer handles a full buffer.

const (
	// AsyncOverflowDropNewest drops the incoming log entry when the buffer is full.
	AsyncOverflowDropNewest AsyncOverflowStrategy = iota
	// AsyncOverflowBlock blocks until there is space in the buffer.
	AsyncOverflowBlock
	// AsyncOverflowDropOldest discards the oldest buffered log entry to make room for a new one.
	AsyncOverflowDropOldest
	// AsyncOverflowHandoff writes the log entry synchronously when the buffer is full.
	AsyncOverflowHandoff
)

func (AsyncOverflowStrategy) IsValid

func (s AsyncOverflowStrategy) IsValid() bool

IsValid reports whether the strategy value is recognised.

type ColorConfig

type ColorConfig struct {
	// Enable enables colored output
	Enable bool
	// ForceTTY forces colored output even when stdout is not a terminal
	ForceTTY bool
	// LevelColors maps log levels to their ANSI color codes
	LevelColors map[Level]string
}

ColorConfig holds color-related configuration for the logger. Enable enables colored output. ForceTTY forces colored output even when stdout is not a terminal. LevelColors maps log levels to their ANSI color codes.

func DefaultColorConfig

func DefaultColorConfig() ColorConfig

DefaultColorConfig returns the default color configuration for the logger. The returned ColorConfig has Enable set to true, ForceTTY set to false, and LevelColors set to the DefaultLevelColors map.

type Config

type Config struct {
	// Level is the minimum level to log.
	Level Level
	// Output is where the logs will be written.
	Output io.Writer
	// EnableStackTrace enables stack trace for error and fatal levels.
	EnableStackTrace bool
	// EnableCaller adds the caller information to log entries.
	EnableCaller bool
	// TimeFormat specifies the format for timestamps.
	TimeFormat string
	// EnableJSON enables JSON output format.
	EnableJSON bool
	// BufferSize sets the size of the log buffer.
	BufferSize int
	// EnableAsync enables asynchronous logging for non-critical log levels.
	EnableAsync bool
	// AsyncBufferSize sets the size of the async log buffer.
	AsyncBufferSize int
	// AsyncOverflowStrategy controls how async logging behaves when the buffer is full.
	AsyncOverflowStrategy AsyncOverflowStrategy
	// AsyncDropHandler is invoked when the async writer drops a log entry.
	AsyncDropHandler func([]byte)
	// AsyncDropPayloadHandler receives drop notifications with ownership semantics,
	// allowing handlers to retain the underlying buffer and release it later via
	// PayloadLease.Release to avoid extra allocations.
	AsyncDropPayloadHandler DropPayloadHandler
	// AsyncMetricsHandler receives async writer metrics snapshots.
	AsyncMetricsHandler AsyncMetricsHandler
	// DisableTimestamp disables timestamp in log entries.
	DisableTimestamp bool
	// AdditionalFields adds these fields to all log entries.
	AdditionalFields []Field
	// Color configuration.
	Color ColorConfig
	// Encoder overrides the default encoder used for log entries.
	Encoder Encoder
	// EncoderName refers to a registered encoder to be loaded at runtime.
	EncoderName string
	// EncoderRegistry holds available encoders for name resolution.
	EncoderRegistry *EncoderRegistry
	// Sampling configures log sampling for high-volume scenarios.
	Sampling SamplingConfig
	// File configures file output settings when using file output.
	File FileConfig
	// FilePath is a convenience field for simple file output configuration.
	FilePath string
	// FileMaxSize is a convenience field for simple rotation configuration (in bytes).
	FileMaxSize int64
	// FileCompress is a convenience field for simple compression configuration.
	FileCompress bool
	// Hooks contains hooks to be called during logging.
	Hooks []HookConfig
	// ContextExtractors apply additional enrichment from context values.
	ContextExtractors []ContextExtractor
}

Config holds configuration for the logger.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default logger configuration.

func DevelopmentConfig

func DevelopmentConfig() Config

DevelopmentConfig returns a configuration optimized for development environments. It enables colors, stack traces, and sets a lower log level for more verbose output.

func ProductionConfig

func ProductionConfig() Config

ProductionConfig returns a configuration optimized for production environments. It enables JSON output, disables colors, and sets reasonable defaults for production use.

type ConfigBuilder

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

ConfigBuilder provides a fluent API for constructing logger configurations. It allows for more readable and chainable configuration setup.

func NewConfigBuilder

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a new builder with sensible defaults. This is the entry point for the fluent configuration API.

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() *Config

Build creates a Config object from the builder.

func (*ConfigBuilder) WithAsyncBufferSize

func (b *ConfigBuilder) WithAsyncBufferSize(size int) *ConfigBuilder

WithAsyncBufferSize sets the buffer size for asynchronous logging. Example: builder.WithAsyncBufferSize(1000).

func (*ConfigBuilder) WithAsyncDropHandler

func (b *ConfigBuilder) WithAsyncDropHandler(handler func([]byte)) *ConfigBuilder

WithAsyncDropHandler sets the handler invoked when async logging drops an entry.

func (*ConfigBuilder) WithAsyncDropPayloadHandler added in v0.0.5

func (b *ConfigBuilder) WithAsyncDropPayloadHandler(handler DropPayloadHandler) *ConfigBuilder

WithAsyncDropPayloadHandler sets the ownership-aware drop handler.

func (*ConfigBuilder) WithAsyncMetricsHandler added in v0.0.4

func (b *ConfigBuilder) WithAsyncMetricsHandler(handler AsyncMetricsHandler) *ConfigBuilder

WithAsyncMetricsHandler sets the handler that receives async writer metrics snapshots.

func (*ConfigBuilder) WithAsyncOverflowStrategy

func (b *ConfigBuilder) WithAsyncOverflowStrategy(strategy AsyncOverflowStrategy) *ConfigBuilder

WithAsyncOverflowStrategy sets the behaviour when the async buffer is full.

func (*ConfigBuilder) WithCaller

func (b *ConfigBuilder) WithCaller(enable bool) *ConfigBuilder

WithCaller enables or disables including the caller information. Example: builder.WithCaller(true).

func (*ConfigBuilder) WithColors

func (b *ConfigBuilder) WithColors(enable bool) *ConfigBuilder

WithColors enables or disables color output. Example: builder.WithColors(true).

func (*ConfigBuilder) WithConsoleOutput

func (b *ConfigBuilder) WithConsoleOutput() *ConfigBuilder

WithConsoleOutput configures the logger to write to the console (stdout). This is a convenience method for WithOutput(os.Stdout).

func (*ConfigBuilder) WithContextExtractor

func (b *ConfigBuilder) WithContextExtractor(extractor ContextExtractor) *ConfigBuilder

WithContextExtractor appends a context extractor used to enrich log fields.

func (*ConfigBuilder) WithContextExtractors

func (b *ConfigBuilder) WithContextExtractors(extractors ...ContextExtractor) *ConfigBuilder

WithContextExtractors appends multiple context extractors.

func (*ConfigBuilder) WithDebugLevel

func (b *ConfigBuilder) WithDebugLevel() *ConfigBuilder

WithDebugLevel is a convenience method for WithLevel(DebugLevel).

func (*ConfigBuilder) WithDevelopmentDefaults

func (b *ConfigBuilder) WithDevelopmentDefaults() *ConfigBuilder

WithDevelopmentDefaults configures the logger with sensible defaults for development. This enables debug level, caller info, no colors, and JSON format.

func (*ConfigBuilder) WithEnableAsync

func (b *ConfigBuilder) WithEnableAsync(enabled bool) *ConfigBuilder

WithEnableAsync enables or disables asynchronous logging. Example: builder.WithEnableAsync(true). This is useful for high-throughput applications. It uses a goroutine to write logs in the background, improving performance. However, it may introduce some latency in log delivery. The buffer size can be configured using WithAsyncBufferSize.

func (*ConfigBuilder) WithEncoder

func (b *ConfigBuilder) WithEncoder(encoder Encoder) *ConfigBuilder

WithEncoder assigns a custom encoder to the configuration.

func (*ConfigBuilder) WithEncoderName

func (b *ConfigBuilder) WithEncoderName(name string) *ConfigBuilder

WithEncoderName selects an encoder by name from the global registry.

func (*ConfigBuilder) WithEncoderRegistry

func (b *ConfigBuilder) WithEncoderRegistry(registry *EncoderRegistry) *ConfigBuilder

WithEncoderRegistry sets the encoder registry used when resolving named encoders.

func (*ConfigBuilder) WithField

func (b *ConfigBuilder) WithField(key string, value any) *ConfigBuilder

WithField adds a field to the log entries. Example: builder.WithField("version", "1.0.0").

func (*ConfigBuilder) WithFields

func (b *ConfigBuilder) WithFields(fields []Field) *ConfigBuilder

WithFields adds multiple fields to the log entries. Example: builder.WithFields([]Field{{Key: "version", Value: "1.0.0"}}).

func (*ConfigBuilder) WithFileCompression

func (b *ConfigBuilder) WithFileCompression(level int) *ConfigBuilder

WithFileCompression configures compression level for rotated files Level values: -1 = Default compression (good compromise between speed and compression) 0 = No compression 1 = Best speed 9 = Best compression Example: builder.WithFileCompression(1) // Fast compression.

func (*ConfigBuilder) WithFileOutput

func (b *ConfigBuilder) WithFileOutput(path string) *ConfigBuilder

WithFileOutput configures the logger to write to a file. The file will be created if it doesn't exist, and appended to if it does. Example: builder.WithFileOutput("/var/log/my_app.log").

func (*ConfigBuilder) WithFileRetention

func (b *ConfigBuilder) WithFileRetention(maxAgeDays, maxFiles int) *ConfigBuilder

WithFileRetention configures retention policies for log files Example: builder.WithFileRetention(7, 10) // Keep logs for 7 days, max 10 files.

func (*ConfigBuilder) WithFileRotation

func (b *ConfigBuilder) WithFileRotation(maxSizeBytes int64, compress bool) *ConfigBuilder

WithFileRotation configures log file rotation. Example: builder.WithFileRotation(100*1024*1024, true).

func (*ConfigBuilder) WithForceColors

func (b *ConfigBuilder) WithForceColors(force bool) *ConfigBuilder

WithForceColors forces color output even when not writing to a terminal. Example: builder.WithForceColors(true).

func (*ConfigBuilder) WithHook

func (b *ConfigBuilder) WithHook(name string, hook Hook) *ConfigBuilder

WithHook adds a hook to be called during logging. Example: builder.WithHook("metrics", NewMetricsHook([]Level{ErrorLevel, FatalLevel})).

func (*ConfigBuilder) WithInfoLevel

func (b *ConfigBuilder) WithInfoLevel() *ConfigBuilder

WithInfoLevel is a convenience method for WithLevel(InfoLevel).

func (*ConfigBuilder) WithJSONFormat

func (b *ConfigBuilder) WithJSONFormat(enable bool) *ConfigBuilder

WithJSONFormat enables JSON formatting for log entries. Example: builder.WithJSONFormat(true).

func (*ConfigBuilder) WithLevel

func (b *ConfigBuilder) WithLevel(level Level) *ConfigBuilder

WithLevel sets the logging level. Example: builder.WithLevel(logger.DebugLevel).

func (*ConfigBuilder) WithLocalDefaults

func (b *ConfigBuilder) WithLocalDefaults() *ConfigBuilder

WithLocalDefaults configures the logger with sensible defaults for local development. This enables debug level, caller info, colorized output, and text (non-JSON) format.

func (*ConfigBuilder) WithNoTimestamp

func (b *ConfigBuilder) WithNoTimestamp() *ConfigBuilder

WithNoTimestamp disables timestamp output in log entries.

func (*ConfigBuilder) WithOutput

func (b *ConfigBuilder) WithOutput(output io.Writer) *ConfigBuilder

WithOutput sets the output destination. Example: builder.WithOutput(os.Stderr).

func (*ConfigBuilder) WithProductionDefaults

func (b *ConfigBuilder) WithProductionDefaults() *ConfigBuilder

WithProductionDefaults configures the logger with sensible defaults for production. This enables info level, no caller info, no colors, and JSON format.

func (*ConfigBuilder) WithSampling

func (b *ConfigBuilder) WithSampling(enabled bool, initial, thereafter int, perLevel bool) *ConfigBuilder

WithSampling configures log sampling for high-volume logging. Initial is the number of logs to allow before sampling starts. Thereafter is the sampling rate (1/N) after the initial threshold. PerLevel applies separate thresholds for each log level. Example: builder.WithSampling(true, 1000, 100, false).

func (*ConfigBuilder) WithSamplingRule added in v0.0.4

func (b *ConfigBuilder) WithSamplingRule(level Level, rule SamplingRule) *ConfigBuilder

WithSamplingRule sets or overrides sampling behaviour for a specific level.

func (*ConfigBuilder) WithSamplingRules added in v0.0.4

func (b *ConfigBuilder) WithSamplingRules(rules map[Level]SamplingRule) *ConfigBuilder

WithSamplingRules merges multiple sampling rules into the configuration.

func (*ConfigBuilder) WithStackTrace

func (b *ConfigBuilder) WithStackTrace(enable bool) *ConfigBuilder

WithStackTrace enables or disables including stack traces for errors. Example: builder.WithStackTrace(true).

func (*ConfigBuilder) WithTimeFormat

func (b *ConfigBuilder) WithTimeFormat(format string) *ConfigBuilder

WithTimeFormat sets the time format string. Example: builder.WithTimeFormat(time.RFC3339).

type ContextExtractor

type ContextExtractor func(ctx context.Context) []Field

ContextExtractor transforms a context into structured fields.

func GlobalContextExtractors added in v0.0.4

func GlobalContextExtractors() []ContextExtractor

GlobalContextExtractors returns the currently registered global extractors.

type DropPayload added in v0.0.5

type DropPayload interface {
	// Bytes returns a read-only view of the dropped payload.
	Bytes() []byte
	// Size reports the number of bytes contained in the payload.
	Size() int
	// AppendTo appends the payload bytes to the provided destination slice and returns it.
	AppendTo(dst []byte) []byte
	// Retain acquires a lease over the underlying buffer. The returned lease's Release
	// method must be called once the handler no longer needs the payload so the buffer
	// can be reclaimed. Calling Retain more than once returns a no-op lease.
	Retain() PayloadLease
}

DropPayload represents a log payload that was dropped by the asynchronous writer. Handlers can inspect the payload, copy it, or retain ownership of the underlying buffer by calling Retain. When Retain is used, the returned PayloadLease must be released once the handler finishes processing to allow buffer reuse.

type DropPayloadHandler added in v0.0.5

type DropPayloadHandler func(DropPayload)

DropPayloadHandler receives advanced drop notifications with ownership semantics. Handlers can retain dropped payloads without incurring additional allocations.

type Encoder

type Encoder interface {
	Encode(entry *Entry, cfg *Config, buf *bytes.Buffer) ([]byte, error)
	EstimateSize(entry *Entry) int
}

Encoder encodes a log entry into bytes suitable for output writers. Implementations can reuse the provided buffer to minimize allocations.

type EncoderRegistry

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

EncoderRegistry manages named encoders that can be referenced from configuration.

func NewEncoderRegistry

func NewEncoderRegistry() *EncoderRegistry

NewEncoderRegistry creates an empty encoder registry.

func (*EncoderRegistry) Get

func (r *EncoderRegistry) Get(name string) (Encoder, bool)

Get retrieves an encoder by name.

func (*EncoderRegistry) MustRegister

func (r *EncoderRegistry) MustRegister(name string, encoder Encoder)

MustRegister registers an encoder and panics if registration fails.

func (*EncoderRegistry) Register

func (r *EncoderRegistry) Register(name string, encoder Encoder) error

Register adds an encoder to the registry under the provided name.

type Entry

type Entry struct {
	// Level is the log level for this entry.
	Level Level
	// Message is the log message.
	Message string
	// Fields contains any structured data associated with this entry.
	Fields []Field
	// Raw provides access to the raw entry data for hook implementations
	// that need to access implementation-specific details.
	Raw any
}

Entry represents a log entry that's passed to hooks.

type Field

type Field struct {
	Key   string
	Value any
}

Field represents a key-value pair in structured logging.

func Any

func Any(key string, value any) Field

Any creates a Field with an arbitrary value.

func ApplyContextExtractors added in v0.0.4

func ApplyContextExtractors(ctx context.Context, extractors ...ContextExtractor) []Field

ApplyContextExtractors executes the provided extractors against the context.

func Bool

func Bool(key string, value bool) Field

Bool creates a Field with a boolean value.

func Duration

func Duration(key string, value time.Duration) Field

Duration creates a Field with a time.Duration value.

func Error

func Error(key string, err error) Field

Error creates a Field from an error. Nil errors are ignored.

func Float64

func Float64(key string, value float64) Field

Float64 creates a Field with a float64 value.

func Int

func Int(key string, value int) Field

Int creates a Field with an int value.

func Int64

func Int64(key string, value int64) Field

Int64 creates a Field with an int64 value.

func Str

func Str(key, value string) Field

Str creates a Field with a string value.

func Time

func Time(key string, value time.Time) Field

Time creates a Field with a time.Time value.

func Uint64

func Uint64(key string, value uint64) Field

Uint64 creates a Field with an uint64 value.

type FileConfig

type FileConfig struct {
	// Path is the path to the log file
	Path string
	// MaxSizeBytes is the max size in bytes before rotation (0 = no rotation).
	MaxSizeBytes int64
	// Compress determines if rotated files should be compressed.
	Compress bool
	// MaxAge is the maximum age of log files in days before deletion (0 = no deletion).
	MaxAge int
	// MaxBackups is the maximum number of backup files to retain (0 = no limit).
	MaxBackups int
	// LocalTime uses local time instead of UTC for file names.
	LocalTime bool
	// FileMode sets the permissions for new log files.
	FileMode os.FileMode
	// CompressionLevel sets the gzip compression level (0=default, 1=best speed, 9=best compression).
	CompressionLevel int
}

FileConfig holds configuration specific to file-based logging.

type FormattedLogger

type FormattedLogger interface {
	// Tracef logs a message at the Trace level
	Tracef(format string, args ...any)
	// Debugf logs a message at the Debug level
	Debugf(format string, args ...any)
	// Infof logs a message at the Info level
	Infof(format string, args ...any)
	// Warnf logs a message at the Warn level
	Warnf(format string, args ...any)
	// Errorf logs a message at the Error level
	Errorf(format string, args ...any)
	// Fatalf logs a message at the Fatal level
	Fatalf(format string, args ...any)
}

FormattedLogger defines the interface for logging formatted messages.

type Hook

type Hook interface {
	// OnLog is called when a log entry is being processed.
	OnLog(entry *Entry) error

	// Levels returns the log levels this hook should be triggered for.
	Levels() []Level
}

Hook is an interface that provides a way to hook into the logging process at various points.

type HookConfig

type HookConfig struct {
	// Name is the name of the hook.
	Name string
	// Levels are the log levels this hook should be triggered for.
	Levels []Level
	// Hook is the hook function to call.
	Hook Hook
}

HookConfig defines a hook to be called during the logging process.

type HookRegistry

type HookRegistry struct {
	Hooks map[string]Hook
	// contains filtered or unexported fields
}

HookRegistry manages a collection of hooks and provides thread-safe access to them.

func NewHookRegistry

func NewHookRegistry() *HookRegistry

NewHookRegistry creates a new hook registry.

func (*HookRegistry) AddFunc added in v0.0.3

func (r *HookRegistry) AddFunc(level Level, hookFunc LogHookFunc)

AddFunc registers a LogHookFunc for the specified level. If level is invalid, the hook is registered for all levels.

func (*HookRegistry) AddHook

func (r *HookRegistry) AddHook(name string, hook Hook) error

AddHook adds a named hook to the registry.

func (*HookRegistry) Dispatch added in v0.0.3

func (r *HookRegistry) Dispatch(ctx context.Context, entry *Entry) []error

Dispatch triggers all hooks for a given log entry with context propagation. It returns any errors encountered during hook execution.

func (*HookRegistry) FireHooks deprecated

func (r *HookRegistry) FireHooks(entry *Entry) []error

FireHooks triggers all hooks for a given log entry using a background context.

Deprecated: use Dispatch to control context propagation.

func (*HookRegistry) GetHook

func (r *HookRegistry) GetHook(name string) (Hook, bool)

GetHook retrieves a hook by name.

func (*HookRegistry) GetHooksForLevel

func (r *HookRegistry) GetHooksForLevel(level Level) []Hook

GetHooksForLevel returns all hooks that should trigger for a given level.

func (*HookRegistry) RemoveFuncs added in v0.0.3

func (r *HookRegistry) RemoveFuncs(level Level)

RemoveFuncs clears all function hooks for the provided level.

func (*HookRegistry) RemoveHook

func (r *HookRegistry) RemoveHook(name string) bool

RemoveHook removes a hook by name.

func (*HookRegistry) ResetFuncs added in v0.0.3

func (r *HookRegistry) ResetFuncs()

ResetFuncs removes all registered function hooks.

type Level

type Level uint8

Level represents the severity of a log message.

const (
	// TraceLevel represents verbose debugging information.
	TraceLevel Level = iota
	// DebugLevel represents debugging information.
	DebugLevel
	// InfoLevel represents general operational information.
	InfoLevel
	// WarnLevel represents warning messages.
	WarnLevel
	// ErrorLevel represents error messages.
	ErrorLevel
	// FatalLevel represents fatal error messages.
	FatalLevel
)

func (Level) IsValid

func (l Level) IsValid() bool

IsValid returns true if the given Level is a valid log level, and false otherwise.

func (Level) String

func (l Level) String() string

String returns the string representation of a log level.

type LogHook

type LogHook struct {
	Name  string
	Func  LogHookFunc
	Level Level
}

LogHook is a container for LogHookFunc with associated metadata.

type LogHookFunc

type LogHookFunc func(ctx context.Context, entry *Entry) error

LogHookFunc defines a hook function that executes during the logging process. Hooks are called after the log entry is created but before it's written to output. They can be used to modify log entries, perform additional actions based on log content, or integrate with external monitoring systems.

type Logger

type Logger interface {
	// Log methods for different levels
	Trace(msg string)
	Debug(msg string)
	Info(msg string)
	Warn(msg string)
	Error(msg string)
	Fatal(msg string)

	// Formatted log methods
	FormattedLogger

	Methods
}

Logger defines the interface for logging operations.

func NewNoop

func NewNoop() Logger

NewNoop creates a new NoopLogger.

type Methods

type Methods interface {
	// WithContext adds context information to the logger
	WithContext(ctx context.Context) Logger
	// WithFields adds structured fields to the logger
	WithFields(fields ...Field) Logger
	// WithField adds a single field to the logger
	WithField(key string, value any) Logger
	// WithError adds an error to the logger
	WithError(err error) Logger
	// GetLevel returns the current logging level
	GetLevel() Level
	// SetLevel sets the logging level
	SetLevel(level Level)
	// Sync ensures all logs are written
	Sync() error
	// GetConfig returns the current logger configuration
	GetConfig() *Config
}

Methods defines the interface for logging methods.

type NoopLogger

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

NoopLogger is a logger that does nothing.

func (*NoopLogger) Debug

func (*NoopLogger) Debug(_ string)

Debug logs a message at the Debug level.

func (*NoopLogger) Debugf

func (*NoopLogger) Debugf(_ string, _ ...any)

Debugf logs a formatted message at the Debug level.

func (*NoopLogger) Error

func (*NoopLogger) Error(_ string)

Error logs a message at the Error level.

func (*NoopLogger) Errorf

func (*NoopLogger) Errorf(_ string, _ ...any)

Errorf logs a formatted message at the Error level.

func (*NoopLogger) Fatal

func (*NoopLogger) Fatal(_ string)

Fatal logs a message at the Fatal level.

func (*NoopLogger) Fatalf

func (*NoopLogger) Fatalf(_ string, _ ...any)

Fatalf logs a formatted message at the Fatal level.

func (*NoopLogger) GetConfig

func (l *NoopLogger) GetConfig() *Config

GetConfig returns a default config.

func (*NoopLogger) GetLevel

func (l *NoopLogger) GetLevel() Level

GetLevel returns the current log level.

func (*NoopLogger) Info

func (*NoopLogger) Info(_ string)

Info logs a message at the Info level.

func (*NoopLogger) Infof

func (*NoopLogger) Infof(_ string, _ ...any)

Infof logs a formatted message at the Info level.

func (*NoopLogger) SetLevel

func (l *NoopLogger) SetLevel(level Level)

SetLevel sets the log level.

func (*NoopLogger) Sync

func (*NoopLogger) Sync() error

Sync is a no-op operation.

func (*NoopLogger) Trace

func (*NoopLogger) Trace(_ string)

Trace logs a message at the Trace level.

func (*NoopLogger) Tracef

func (*NoopLogger) Tracef(_ string, _ ...any)

Tracef logs a formatted message at the Trace level.

func (*NoopLogger) Warn

func (*NoopLogger) Warn(_ string)

Warn logs a message at the Warn level.

func (*NoopLogger) Warnf

func (*NoopLogger) Warnf(_ string, _ ...any)

Warnf logs a formatted message at the Warn level.

func (*NoopLogger) WithContext

func (l *NoopLogger) WithContext(_ context.Context) Logger

WithContext returns a new logger with the given context.

func (*NoopLogger) WithError

func (l *NoopLogger) WithError(_ error) Logger

WithError returns a new logger with the given error.

func (*NoopLogger) WithField

func (l *NoopLogger) WithField(_ string, _ any) Logger

WithField returns a new logger with the given field.

func (*NoopLogger) WithFields

func (l *NoopLogger) WithFields(_ ...Field) Logger

WithFields returns a new logger with the given fields.

type PayloadLease added in v0.0.5

type PayloadLease interface {
	Bytes() []byte
	Release()
}

PayloadLease represents ownership of a dropped payload buffer. Call Release when finished with the buffer to allow it to be recycled. Release is idempotent.

type SamplingConfig

type SamplingConfig struct {
	// Enabled turns sampling on/off.
	Enabled bool
	// Initial is the number of entries to log before sampling starts.
	Initial int
	// Thereafter is the sampling rate (1/N) after Initial entries.
	Thereafter int
	// PerLevelThreshold when true, applies separate thresholds per level.
	PerLevelThreshold bool
	// Rules overrides sampling configuration per level.
	Rules map[Level]SamplingRule
}

SamplingConfig defines parameters for log sampling.

type SamplingRule added in v0.0.4

type SamplingRule struct {
	Enabled    bool
	Initial    int
	Thereafter int
}

SamplingRule customizes sampling configuration for a specific level.

type StandardHook

type StandardHook struct {
	// LevelList contains the levels this hook should trigger for
	LevelList []Level
	// LogHandler is called when a log entry is processed
	LogHandler func(entry *Entry) error
}

StandardHook provides a simpler way to implement the Hook interface.

func NewStandardHook

func NewStandardHook(levels []Level, handler func(entry *Entry) error) *StandardHook

NewStandardHook creates a new StandardHook with the given levels and handler.

func (*StandardHook) Levels

func (h *StandardHook) Levels() []Level

Levels implements Hook.Levels.

func (*StandardHook) OnLog

func (h *StandardHook) OnLog(entry *Entry) error

OnLog implements Hook.OnLog.

Directories

Path Synopsis
examples
hooks command
hooks/main demonstrates the creation and use of logger hooks.
hooks/main demonstrates the creation and use of logger hooks.
writers command
internal
constants
Package constants provides application-wide constant values used throughout the logger system.
Package constants provides application-wide constant values used throughout the logger system.
output
Package output provides flexible output destinations for the logger package.
Package output provides flexible output destinations for the logger package.
utils
Package utils provides internal utility functions used throughout the logger package.
Package utils provides internal utility functions used throughout the logger package.
middleware
chi
gin
pkg
adapter
Package adapter provides concrete implementations of the logger interface.
Package adapter provides concrete implementations of the logger interface.
log
Package log provides application-level logging functionality for services.
Package log provides application-level logging functionality for services.

Jump to

Keyboard shortcuts

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