logger

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultSamplingTick           = time.Second
	DefaultSamplingThreshold      = 100
	DefaultSamplingRate           = 0.1
	DefaultSamplingErrorRate      = 1.0
	DefaultSamplingMaxCounterSize = 10000
)

Default values for sampling configuration

Variables

This section is empty.

Functions

func GetDroppedTotal

func GetDroppedTotal(level string) float64

GetDroppedTotal returns the current dropped logs count for a level. Useful for testing. In production, use the /metrics endpoint instead.

func MetricsOnDropped

func MetricsOnDropped() func(context.Context, slog.Record)

MetricsOnDropped returns an OnDropped callback that increments Prometheus metrics. Use this with SamplingConfig.OnDropped to track dropped logs.

func MetricsOnProcessed

func MetricsOnProcessed(level slog.Level)

MetricsOnProcessed returns a function to call when a log is processed. This should be called for every log, before sampling decision.

func NewAsyncHandler

func NewAsyncHandler(h slog.Handler, cfg AsyncConfig) *asyncHandler

NewAsyncHandler creates a handler that buffers logs and writes them asynchronously. This reduces I/O blocking in the hot path.

IMPORTANT: Call Close() or Flush() before application shutdown to ensure all buffered logs are written.

NOTE: This handler is not yet integrated into the main logger factory (New()). Use it directly when you need async logging:

baseHandler := slog.NewJSONHandler(os.Stdout, nil)
asyncHandler := logger.NewAsyncHandler(baseHandler, logger.AsyncConfig{Enabled: true})
defer asyncHandler.Close()
slog.SetDefault(slog.New(asyncHandler))

func NewSamplingHandler

func NewSamplingHandler(h slog.Handler, cfg SamplingConfig) slog.Handler

NewSamplingHandler creates a handler that samples logs based on config. It wraps the provided handler and applies threshold-based sampling.

Algorithm:

  • First `Threshold` logs with same level+message are logged as-is
  • After threshold, logs are sampled at `Rate` (or `ErrorRate` for errors)
  • Counters reset every `Tick` interval
  • Messages matching NeverSampleMessages prefixes are always logged

func RegisterMetrics

func RegisterMetrics(registry prometheus.Registerer)

RegisterMetrics registers logger metrics with the given registry. If registry is nil, uses the default prometheus registry. This function is safe to call multiple times.

func SetSamplingCounterSize

func SetSamplingCounterSize(size int)

SetSamplingCounterSize sets the current size of the sampling counter. Call this periodically (e.g., in maybeResetCounters) to track memory usage.

func ToContext

func ToContext(ctx context.Context, logger *Logger) context.Context

ToContext adds the logger to the context.

Types

type AsyncConfig

type AsyncConfig struct {
	// Enabled turns async logging on/off (default: false)
	Enabled bool

	// BufferSize is the size of the log buffer (default: 4096)
	// Larger buffers reduce I/O frequency but use more memory
	BufferSize int

	// FlushInterval is how often to flush the buffer (default: 100ms)
	FlushInterval time.Duration

	// DropOnFull determines behavior when buffer is full
	// true = drop logs (never block), false = block until space available (default: false)
	DropOnFull bool

	// OnDrop is called when a log is dropped due to full buffer (optional)
	OnDrop func(count int)
}

AsyncConfig configures async buffered logging.

func DefaultAsyncConfig

func DefaultAsyncConfig() AsyncConfig

DefaultAsyncConfig returns sensible defaults for production.

type AsyncWriter

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

AsyncWriter wraps an io.Writer with async buffered writes. This is an alternative to AsyncHandler when you want to make any writer async (e.g., file writer).

func NewAsyncWriter

func NewAsyncWriter(w io.Writer, cfg AsyncConfig) *AsyncWriter

NewAsyncWriter creates an async buffered writer.

func (*AsyncWriter) Close

func (w *AsyncWriter) Close() error

Close stops the async writer and flushes remaining data.

func (*AsyncWriter) Write

func (w *AsyncWriter) Write(p []byte) (n int, err error)

type Config

type Config struct {
	Level  string
	Format string
	Output io.Writer

	// Sampling configuration for high-traffic production environments
	Sampling SamplingConfig

	// Async configuration for non-blocking logging
	Async AsyncConfig
}

Config holds logger configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default logger configuration.

type ContextKey

type ContextKey string

Context keys for type safety - must match middleware keys.

const (
	ContextKeyRequestID ContextKey = "request_id"
	ContextKeyUserID    ContextKey = "user_id"
)

type DroppedLogsCounter

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

DroppedLogsCounter is a simple counter for tracking dropped logs. Use this with SamplingConfig.OnDropped to track sampling metrics.

func NewDroppedLogsCounter

func NewDroppedLogsCounter() *DroppedLogsCounter

func (*DroppedLogsCounter) Increment

func (c *DroppedLogsCounter) Increment(ctx context.Context, record slog.Record)

func (*DroppedLogsCounter) Reset

func (c *DroppedLogsCounter) Reset() uint64

func (*DroppedLogsCounter) Total

func (c *DroppedLogsCounter) Total() uint64

type Logger

type Logger struct {
	*slog.Logger
}

Logger wraps slog.Logger with additional functionality.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext retrieves the logger from the context.

func New

func New(cfg Config) *Logger

New creates a new Logger instance.

func NewDefault

func NewDefault() *Logger

NewDefault creates a new Logger with default configuration.

func NewDevelopment

func NewDevelopment() *Logger

NewDevelopment creates a logger configured for development.

func NewNop

func NewNop() *Logger

NewNop creates a no-op logger that discards all output. Useful for testing or when logging is not needed.

func NewProduction

func NewProduction() *Logger

NewProduction creates a logger configured for production. Includes sampling to reduce log volume in high-traffic environments.

func NewProductionWithConfig

func NewProductionWithConfig(sampling SamplingConfig) *Logger

NewProductionWithConfig creates a production logger with custom sampling config.

func (*Logger) SetDefault

func (l *Logger) SetDefault()

SetDefault sets this logger as the default slog logger.

func (*Logger) Stdlib

func (l *Logger) Stdlib() *slog.Logger

Stdlib returns the underlying *slog.Logger for use with standard library.

func (*Logger) With

func (l *Logger) With(args ...any) *Logger

With returns a new Logger with the given attributes.

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a new Logger with context values.

func (*Logger) WithError

func (l *Logger) WithError(err error) *Logger

WithError returns a new Logger with the error attribute.

func (*Logger) WithField

func (l *Logger) WithField(key string, value any) *Logger

WithField returns a new Logger with a single field.

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]any) *Logger

WithFields returns a new Logger with multiple fields.

type SamplingConfig

type SamplingConfig struct {
	// Enabled turns sampling on/off (default: false for backward compatibility)
	Enabled bool

	// Tick is the sampling interval (default: 1 second)
	// Counters reset after each tick
	Tick time.Duration

	// Threshold is the number of identical logs allowed per tick before sampling kicks in
	// First N logs are always logged, then sampling applies (default: 100)
	Threshold uint64

	// Rate is the sampling rate after threshold is reached [0.0, 1.0]
	// 0.1 = log 10% of messages after threshold (default: 0.1)
	Rate float64

	// ErrorRate is the sampling rate for error/warn level logs [0.0, 1.0]
	// Errors are typically more important, so higher rate (default: 1.0 = 100%)
	ErrorRate float64

	// MaxCounterSize limits the number of unique message keys to track (default: 10000)
	// Prevents memory growth with many unique messages
	MaxCounterSize int

	// NeverSampleMessages are message prefixes that should never be sampled
	// Useful for security/audit logs that must always be logged
	// Example: []string{"audit:", "security:", "auth:"}
	NeverSampleMessages []string

	// OnDropped is called when a log is dropped (optional, for metrics)
	// Protected against panics - callback errors are silently ignored
	OnDropped func(ctx context.Context, record slog.Record)

	// EnableMetrics enables Prometheus metrics for dropped logs
	EnableMetrics bool
}

SamplingConfig configures log sampling behavior. Sampling helps reduce log volume in high-traffic production environments.

func DefaultSamplingConfig

func DefaultSamplingConfig() SamplingConfig

DefaultSamplingConfig returns sensible defaults for production.

Jump to

Keyboard shortcuts

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