Documentation
¶
Index ¶
- Constants
- func GetDroppedTotal(level string) float64
- func MetricsOnDropped() func(context.Context, slog.Record)
- func MetricsOnProcessed(level slog.Level)
- func NewAsyncHandler(h slog.Handler, cfg AsyncConfig) *asyncHandler
- func NewSamplingHandler(h slog.Handler, cfg SamplingConfig) slog.Handler
- func RegisterMetrics(registry prometheus.Registerer)
- func SetSamplingCounterSize(size int)
- func ToContext(ctx context.Context, logger *Logger) context.Context
- type AsyncConfig
- type AsyncWriter
- type Config
- type ContextKey
- type DroppedLogsCounter
- type Logger
- func (l *Logger) SetDefault()
- func (l *Logger) Stdlib() *slog.Logger
- func (l *Logger) With(args ...any) *Logger
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithError(err error) *Logger
- func (l *Logger) WithField(key string, value any) *Logger
- func (l *Logger) WithFields(fields map[string]any) *Logger
- type SamplingConfig
Constants ¶
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 ¶
GetDroppedTotal returns the current dropped logs count for a level. Useful for testing. In production, use the /metrics endpoint instead.
func MetricsOnDropped ¶
MetricsOnDropped returns an OnDropped callback that increments Prometheus metrics. Use this with SamplingConfig.OnDropped to track dropped logs.
func MetricsOnProcessed ¶
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.
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.
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 ¶
Logger wraps slog.Logger with additional functionality.
func FromContext ¶
FromContext retrieves the logger from the context.
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) WithContext ¶
WithContext returns a new Logger with context values.
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.