log

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 16 Imported by: 0

README

log

Go Reference Go Report Card

A production-ready logging package for Go that wraps slog (Go 1.21+) with enhanced features and a developer-friendly API.

Features

Beautiful Console Output - Auto-detects TTY with color-coded log levels
📊 Multiple Formats - Console, JSON, and Text formats
🎯 Six Log Levels - TRACE, DEBUG, INFO, WARN, ERROR, FATAL
🔧 Functional Options API - Intuitive configuration with option functions
🔄 Log Rotation - Automatic rotation by size, age, and backup count
📦 Buffered Writing - Configurable buffering with auto-flush
🎣 Hooks System - Pre-log hooks for integration (Sentry, metrics, etc.)
🎲 Sampling - Control log volume with smart sampling
🧪 Testing Support - Built-in test logger with capture hooks
🚀 High Performance - Minimal overhead over raw slog
🔌 Context Integration - First-class context.Context support
🌍 Environment Config - Configure via environment variables
🔥 Dynamic Log Levels - Change levels at runtime without restart (slog.Leveler support)

Installation

go get github.com/alexjoedt/log

Requires Go 1.23 or later.

Quick Start

package main

import "github.com/alexjoedt/log"

func main() {
    // Use package-level functions with sensible defaults
    log.Info("application started")
    log.Debug("processing", "count", 42)
    log.Error("something failed", "error", err)
}

Usage

Basic Logging
// Package-level functions (uses default logger)
log.Trace("very detailed trace")
log.Debug("debug information")
log.Info("informational message")
log.Warn("warning message")
log.Error("error occurred", "error", err)
log.Fatal("critical failure") // logs and exits with code 1
Creating Custom Loggers
// Create a custom logger with options
logger := log.New(
    log.WithLevel(log.DEBUG),
    log.WithFormat(log.FormatJSON),
    log.WithDefaultFields("service", "api", "version", "1.0.0"),
)

// Set as default
log.SetDefault(logger)
Log Levels

The package supports six log levels in order of severity:

Level Value Description
TRACE -8 Very detailed trace information
DEBUG -4 Debug information for developers
INFO 0 General informational messages
WARN 4 Warning messages
ERROR 8 Error conditions
FATAL 12 Fatal errors (logs and exits)
// Check if level is enabled (avoid expensive operations)
if log.IsDebugEnabled() {
    log.Debug("expensive data", "dump", computeExpensiveValue())
}
Dynamic Log Levels

Change log levels at runtime without restarting your application - perfect for production debugging:

// Create a dynamic log level using slog.LevelVar
logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelInfo)

logger := log.New(
    log.WithLevel(logLevel),  // Pass the LevelVar
    log.WithFormat(log.FormatJSON),
)

// Later, change the level dynamically (e.g., via HTTP endpoint or signal)
logLevel.Set(slog.LevelDebug)  // Now DEBUG logs will appear!

Production use case - HTTP endpoint to change level:

logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelInfo)
logger := log.New(log.WithLevel(logLevel))

http.HandleFunc("/admin/loglevel", func(w http.ResponseWriter, r *http.Request) {
    level := r.URL.Query().Get("level")
    switch level {
    case "debug":
        logLevel.Set(slog.LevelDebug)
    case "info":
        logLevel.Set(slog.LevelInfo)
    case "warn":
        logLevel.Set(slog.LevelWarn)
    case "error":
        logLevel.Set(slog.LevelError)
    }
    fmt.Fprintf(w, "Log level changed to %s", level)
})

Why dynamic levels?

  • 🐛 Enable debug logging in production without restart
  • 🔍 Troubleshoot issues in real-time
  • 📉 Reduce log volume during normal operation
  • ⚡ Zero downtime log level changes

See examples/dynamic_level for a complete example with signal handlers.

slog.Leveler Support

The package fully supports Go's slog.Leveler interface:

// Static levels (backward compatible)
logger := log.New(log.WithLevel(log.DEBUG))

// slog levels
logger := log.New(log.WithLevel(slog.LevelDebug))

// Dynamic levels
logLevel := &slog.LevelVar{}
logger := log.New(log.WithLevel(logLevel))

// Our Level type implements slog.Leveler
var _ slog.Leveler = log.Level(0)
Output Formats
Console Format (default)

Human-readable format with color-coded levels (when TTY detected):

2024-10-03T10:15:30Z [INFO] application started service=api version=1.0
2024-10-03T10:15:31Z [ERROR] database connection failed error="connection timeout"
JSON Format

Structured JSON for production and log aggregators:

{"time":"2024-10-03T10:15:30Z","level":"INFO","msg":"application started","service":"api","version":"1.0"}
{"time":"2024-10-03T10:15:31Z","level":"ERROR","msg":"database failed","error":"connection timeout"}
Text Format

Plain key=value format:

time=2024-10-03T10:15:30Z level=INFO msg="application started" service=api version=1.0
Adding Context Fields
// Create logger with default fields
logger := log.New(
    log.WithDefaultFields("app", "myapp", "env", "prod"),
)

// Add fields to specific logger instance (immutable pattern)
requestLogger := logger.WithFields(
    "request_id", uuid.New(),
    "user_id", 12345,
)

requestLogger.Info("processing request")
// Output includes: app=myapp env=prod request_id=... user_id=12345
Timestamp Configuration

By default, all log formats include timestamps in RFC3339 format. You can customize or disable timestamps:

// Custom timestamp format
logger := log.New(
    log.WithTimestampFormat(time.RFC3339Nano),
)

// Disable timestamps completely (works for all formats)
logger := log.New(
    log.WithoutTimestamp(),
)

Example output without timestamps:

Console: [INFO ] application started service=api
JSON:    {"level":"INFO","msg":"application started","service":"api"}
Text:    level=INFO msg="application started" service=api
Configuration Options
Option Functions
logger := log.New(
    log.WithLevel(log.DEBUG),                    // Set minimum log level
    log.WithFormat(log.FormatJSON),              // Set output format
    log.WithWriter(os.Stdout),                   // Set output writer
    log.WithTimestampFormat(time.RFC3339Nano),   // Custom timestamp format
    log.WithoutTimestamp(),                      // Disable timestamp output
    log.WithCaller(),                            // Enable caller info (file:line)
    log.WithCallerSkip(2),                       // Adjust caller depth
    log.WithDefaultFields("key", "value"),       // Add default fields
)
Environment Variables

Configure the default logger via environment variables:

export LOG_LEVEL=debug              # trace, debug, info, warn, error, fatal
export LOG_FORMAT=json              # console, json, text
export LOG_CALLER=true              # Enable caller information
export LOG_CALLER_SKIP=2            # Adjust caller depth
export LOG_TIMESTAMP_FORMAT=RFC3339 # Timestamp format
// Create logger from environment
logger := log.FromEnv()
Advanced Features
Log Rotation

Automatically rotate logs based on size, age, and backup count:

logger := log.New(
    log.WithRotation(
        100,  // MaxSize: 100 MB
        7,    // MaxBackups: keep 7 old files
        30,   // MaxAge: 30 days
        true, // Compress: gzip old files
    ),
)
Sampling

Reduce log volume by sampling (useful for high-frequency logs):

logger := log.New(
    log.WithSampling(
        100,  // Log first 100 messages
        100,  // Then log every 100th message
    ),
)
Buffered Writing

Buffer logs for better performance with periodic flushing:

logger := log.New(
    log.WithBuffer(
        8192,                    // 8KB buffer
        100*time.Millisecond,    // Flush every 100ms
    ),
)
// Automatically flushes on ERROR and FATAL
Multiple Writers (Fan-out)

Write logs to multiple destinations simultaneously:

logger := log.New(
    log.WithWriters(
        os.Stdout,
        fileWriter,
        networkWriter,
    ),
)
Hooks

Register hooks to intercept log entries (e.g., send errors to Sentry):

// Global hook (affects all loggers)
log.RegisterHook(func(entry *log.Entry) error {
    if entry.Level >= log.ERROR {
        sentry.CaptureException(entry.Error)
    }
    return nil
})

// Per-logger hook
logger := log.New(
    log.WithHook(func(entry *log.Entry) error {
        metrics.IncrementCounter("logs", entry.Level.String())
        return nil
    }),
)
Context Integration

Store and retrieve loggers from context:

// Add logger to context
ctx := log.ContextWithLogger(ctx, logger)

// Retrieve and use logger from context
log.FromContext(ctx).Info("message with context logger")

// Falls back to default logger if none in context
log.FromContext(context.Background()).Info("uses default")
Lazy Evaluation

Avoid expensive operations when log level is disabled:

log.Debug("data dump", log.Lazy(func() interface{} {
    return expensiveSerialize(data)
}))
// Function only called if DEBUG level is enabled
Testing Support

Built-in testing utilities for unit tests:

func TestMyFunction(t *testing.T) {
    // Create test logger with hook
    logger, hook := log.NewTestLogger()
    
    // Use logger in your code
    myFunction(logger)
    
    // Assert on captured logs
    assert.Equal(t, 3, hook.Count())
    assert.True(t, hook.HasMessage("expected message"))
    assert.True(t, hook.HasLevel(log.ERROR))
    assert.Equal(t, "last message", hook.LastEntry().Message)
    
    // Check specific level counts
    assert.Equal(t, 1, hook.CountLevel(log.ERROR))
    
    // Reset for next test
    hook.Reset()
}
Custom Exit Handler

Customize behavior for FATAL logs:

log.SetExitHandler(func(code int) {
    cleanup()
    os.Exit(code)
})
Slog Compatibility
Direct slog.Handler Usage

For slog-first workflows, create a handler directly and use it with slog.New():

handler := log.NewSlogHandler(
    log.WithLevel(log.DEBUG),
    log.WithFormat(log.FormatJSON),
    log.WithDefaultFields("service", "api", "version", "1.0"),
)

logger := slog.New(handler)
logger.Info("using slog with enhanced features")

All options work with NewSlogHandler():

  • Log levels, formats, and writers
  • Rotation, sampling, and buffering
  • Hooks and caller information
  • Default fields (applied via handler.WithAttrs())

This is useful when:

  • You prefer working directly with slog.Logger
  • You need to pass a handler to third-party libraries
  • You want a pure slog workflow with enhanced features
Access Underlying Logger

Access the underlying *slog.Logger for compatibility:

logger := log.New()
slogLogger := logger.Slog()
// Use with any library that expects *slog.Logger

Performance

Benchmarks show minimal overhead compared to raw slog:

BenchmarkLoggerInfo-8        2920038    401.2 ns/op    1363 B/op    5 allocs/op
BenchmarkSlogInfo-8          2310099    524.9 ns/op     240 B/op    0 allocs/op
BenchmarkLoggerDisabled-8   38244826     29.9 ns/op       8 B/op    0 allocs/op

Examples

See the examples directory for complete working examples:

Best Practices

  1. Use package-level functions for simple cases: log.Info(), log.Error(), etc.
  2. Create custom loggers for services: Configure once with options, use throughout the service
  3. Add context fields: Use WithFields() to add request IDs, user IDs, etc.
  4. Check levels for expensive operations: Use IsDebugEnabled() before expensive computations
  5. Use JSON format in production: Better for log aggregation and parsing
  6. Enable caller info for debugging: Use WithCaller() option during development
  7. Set up log rotation: Prevent disk space issues in production
  8. Use hooks for integrations: Integrate with Sentry, metrics, etc.
  9. Test with TestLogger: Capture and assert on logs in unit tests
  10. Configure via environment: Use FromEnv() for 12-factor app compliance

Contributing

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

License

MIT License - see LICENSE file for details.

Acknowledgments

Built on top of Go's excellent log/slog package introduced in Go 1.21.

Documentation

Overview

Package log provides a production-ready logging package that wraps Go's slog with enhanced features including beautiful console output, log rotation, sampling, dynamic log levels, and more.

Basic usage with the logger wrapper:

logger := log.New(
    log.WithLevel(log.INFO),
    log.WithFormat(log.FormatJSON),
)
logger.Info("hello world", "key", "value")

Or use the default logger directly:

log.Info("hello world")

Dynamic log levels (change at runtime without restart):

logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelInfo)
logger := log.New(log.WithLevel(logLevel))
// Later: logLevel.Set(slog.LevelDebug)

For slog-first workflows, create a handler directly:

handler := log.NewSlogHandler(
    log.WithLevel(log.DEBUG),
    log.WithFormat(log.FormatJSON),
    log.WithDefaultFields("service", "api"),
)
logger := slog.New(handler)
logger.Info("using slog with enhanced features")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextWithLogger

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

ContextWithLogger returns a new context with the logger attached.

func Debug

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

Debug logs at DEBUG level with the default logger.

func Error

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

Error logs at ERROR level with the default logger.

func Failure added in v1.5.0

func Failure(msg string)

Failure logs a failure message with the default logger.

func Fatal

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

Fatal logs at FATAL level with the default logger and then exits.

func Info

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

Info logs at INFO level with the default logger.

func IsDebugEnabled

func IsDebugEnabled() bool

IsDebugEnabled returns true if DEBUG level is enabled.

func IsErrorEnabled

func IsErrorEnabled() bool

IsErrorEnabled returns true if ERROR level is enabled.

func IsInfoEnabled

func IsInfoEnabled() bool

IsInfoEnabled returns true if INFO level is enabled.

func IsTraceEnabled

func IsTraceEnabled() bool

IsTraceEnabled returns true if TRACE level is enabled.

func IsWarnEnabled

func IsWarnEnabled() bool

IsWarnEnabled returns true if WARN level is enabled.

func Lazy

func Lazy(fn LazyFunc) slog.Attr

Lazy creates a lazy-evaluated value for expensive operations. The function is only called if the log level is enabled.

func NewSlogHandler added in v1.3.0

func NewSlogHandler(opts ...Option) slog.Handler

NewSlogHandler creates a fully-configured slog.Handler with the given options. This allows using the package's enhanced features (rotation, sampling, console formatting, hooks) while maintaining a pure slog-based workflow.

All options that work with New() also work with NewSlogHandler(), including:

  • WithLevel, WithFormat, WithWriter
  • WithRotation, WithSampling, WithBuffer
  • WithHook, WithCaller, WithoutTimestamp
  • WithDefaultFields (applied via handler.WithAttrs)

Example usage:

handler := log.NewSlogHandler(
    log.WithLevel(log.DEBUG),
    log.WithFormat(log.FormatJSON),
    log.WithDefaultFields("service", "api", "version", "1.0"),
)
logger := slog.New(handler)
logger.Info("using slog with enhanced handler")

Note: When using buffered or rotating writers, the caller is responsible for managing writer lifecycle (flushing/closing) if needed.

func NewTestLogger

func NewTestLogger() (*TestLogger, *TestHook)

NewTestLogger creates a logger and hook for testing.

func RegisterHook

func RegisterHook(hook Hook)

RegisterHook registers a global hook that is called for all loggers.

func SetDefault

func SetDefault(logger *Logger)

SetDefault sets the default logger used by package-level functions.

func SetExitHandler

func SetExitHandler(handler func(int))

SetExitHandler sets the function called by Fatal(). The default handler calls os.Exit(1).

func Step added in v1.5.0

func Step(msg string)

Step logs a step/progress message with the default logger.

func Success added in v1.5.0

func Success(msg string)

Success logs a success message with the default logger.

func Trace

func Trace(msg string, args ...any)

Trace logs at TRACE level with the default logger.

func Warn

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

Warn logs at WARN level with the default logger.

func Writer

func Writer(level Level) io.Writer

Writer returns an io.Writer that writes to the logger at the given level.

Types

type BufferConfig

type BufferConfig struct {
	Size          int           // Buffer size in bytes
	FlushInterval time.Duration // Auto-flush interval
}

BufferConfig holds buffering settings.

type Config

type Config struct {
	Format           Format
	Writer           io.Writer
	TimestampFormat  string
	DisableTimestamp bool
	ShowCaller       bool
	CallerSkip       int
	DefaultFields    []any
	EnableStackTrace Level // Show stack trace for this level and above

	// Rotation settings
	Rotation *RotationConfig

	// Sampling settings
	Sampling *SamplingConfig

	// Buffer settings
	Buffer *BufferConfig

	// Multiple writers
	Writers []io.Writer

	// Hooks
	Hooks []Hook

	// CLI settings
	CLISymbols bool // Enable symbol prefixes for CLI format
	CLIFields  bool // Render key=value fields in CLI format; opt-in via WithCLIFields(true) or NewCLILogger
	// contains filtered or unexported fields
}

Config holds the configuration for a Logger.

func (*Config) Level

func (c *Config) Level() Level

Level returns the current minimum log level. This method allows checking the current level even when using dynamic levels.

type Entry

type Entry struct {
	Level   Level
	Message string
	Time    interface{}
	Fields  []any
	Error   error
}

Entry represents a log entry, used for hooks.

type Format

type Format string

Format represents the output format for logs.

const (
	// FormatConsole is human-readable format with colors (when TTY detected)
	FormatConsole Format = "console"
	// FormatJSON is structured JSON output
	FormatJSON Format = "json"
	// FormatText is plain key=value format
	FormatText Format = "text"
	// FormatCLI is clean CLI output with symbols and no timestamps.
	// Structured key=value fields are appended after the message by default;
	// use WithCLIFields(false) to suppress them.
	FormatCLI Format = "cli"
)

type Hook

type Hook func(*Entry) error

Hook is a function called for each log entry. Returning an error prevents the log from being written.

type LazyFunc

type LazyFunc func() any

LazyFunc is a function that computes a value lazily.

type Level

type Level int

Level represents the severity level of a log message.

const (
	// TRACE is for very detailed trace information
	TRACE Level = -8
	// DEBUG is for debug information
	DEBUG Level = -4
	// INFO is for informational messages
	INFO Level = 0
	// WARN is for warning messages
	WARN Level = 4
	// ERROR is for error messages
	ERROR Level = 8
	// FATAL is for fatal errors (logs and exits)
	FATAL Level = 12
)

func ParseLogLevel added in v1.2.0

func ParseLogLevel(levelStr string) Level

ParseLogLevel parses a string and returns the corresponding log Level. It accepts common level abbreviations and full names (case-insensitive). Leading and trailing whitespace is ignored.

Supported values:

  • "trace", "trc" -> TRACE
  • "debug", "dbg" -> DEBUG
  • "info", "inf" -> INFO
  • "warn", "warning" -> WARN
  • "error", "err" -> ERROR
  • "fatal", "fat", "ftl" -> FATAL

If the input doesn't match any recognized level, it returns ERROR as the default.

func (Level) Level added in v1.4.0

func (l Level) Level() slog.Level

Level implements slog.Leveler interface, allowing Level to be used wherever slog expects a Leveler (e.g., slog.HandlerOptions, dynamic levels).

func (Level) String

func (l Level) String() string

String returns the string representation of the level.

func (Level) ToSlogLevel

func (l Level) ToSlogLevel() slog.Level

ToSlogLevel converts our Level to slog.Level Deprecated: Use Level() method instead to satisfy slog.Leveler interface.

type Logger

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

Logger is the main logging type that wraps slog.Logger with enhanced features.

func Default

func Default() *Logger

Default returns the current default logger.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext retrieves the logger from the context. If no logger is found, returns the default logger.

func FromEnv

func FromEnv() *Logger

FromEnv creates a logger with configuration from environment variables. Supported environment variables:

  • LOG_LEVEL: trace, debug, info, warn, error, fatal (default: info)
  • LOG_FORMAT: json, text, console (default: console)
  • LOG_CALLER: true/false - enable caller info (default: false)
  • LOG_CALLER_SKIP: number - adjust caller depth (default: 2)

func New

func New(opts ...Option) *Logger

New creates a new Logger with the given options.

func NewCLILogger added in v1.5.0

func NewCLILogger(opts ...Option) *Logger

NewCLILogger creates a logger optimized for CLI applications. It writes to stderr, disables timestamps, enables symbol prefixes, and appends structured key=value fields after the message by default.

Defaults:

  • Format: FormatCLI
  • Writer: os.Stderr
  • Level: INFO
  • Symbols: enabled (WithCLISymbols)
  • Fields: enabled (WithCLIFields(true))

Example:

logger := log.NewCLILogger()
logger.Step("Building application")
logger.Info("processed", "count", 42)
logger.Success("Build complete")
logger.Failure("Push failed")

Options can be provided to override defaults:

logger := log.NewCLILogger(
    log.WithLevel(log.DEBUG),
    log.WithCLIFields(false), // suppress key=value fields
)

func WithFields

func WithFields(args ...any) *Logger

WithFields creates a new logger from the default logger with additional fields.

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any)

Debug logs at DEBUG level.

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any)

Error logs at ERROR level.

func (*Logger) Failure added in v1.5.0

func (l *Logger) Failure(msg string)

Failure logs a failure message (CLI-friendly, message only). This is intended for CLI applications to indicate failed operations. When using FormatCLI, it renders with a red X symbol. For other formats, it logs at ERROR level.

Example:

logger.Failure("Deployment failed")

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...any)

Fatal logs at FATAL level and then exits.

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any)

Info logs at INFO level.

func (*Logger) IsLevelEnabled

func (l *Logger) IsLevelEnabled(level Level) bool

IsLevelEnabled returns true if the given level is enabled. This checks against the current log level, which may be dynamic.

func (*Logger) Slog

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

Slog returns the underlying *slog.Logger for compatibility.

func (*Logger) Step added in v1.5.0

func (l *Logger) Step(msg string)

Step logs a step/progress message (CLI-friendly, message only). This is intended for CLI applications to indicate progress or steps. When using FormatCLI, it renders with a blue bullet symbol. For other formats, it logs at INFO level.

Example:

logger.Step("Building application...")

func (*Logger) Success added in v1.5.0

func (l *Logger) Success(msg string)

Success logs a success message (CLI-friendly, message only). This is intended for CLI applications to indicate successful operations. When using FormatCLI, it renders with a green checkmark symbol. For other formats, it logs at INFO level.

Example:

logger.Success("Deployment completed successfully")

func (*Logger) Trace

func (l *Logger) Trace(msg string, args ...any)

Trace logs at TRACE level.

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any)

Warn logs at WARN level.

func (*Logger) WithFields

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

WithFields creates a new logger with additional fields. This follows the immutable pattern - returns a new instance.

func (*Logger) Writer

func (l *Logger) Writer(level Level) io.Writer

Writer returns an io.Writer that writes to the logger at the given level.

type Option added in v1.0.0

type Option func(*Config)

Option is a function that configures a Logger.

func WithBuffer added in v1.0.0

func WithBuffer(size int, flushInterval time.Duration) Option

WithBuffer configures buffered writing.

func WithCLIFields added in v1.6.0

func WithCLIFields(enabled bool) Option

WithCLIFields controls whether structured key=value fields are appended to log lines when using FormatCLI. Pass false to suppress all fields and render only the message (the original minimal CLI behaviour). Defaults to true for loggers using FormatCLI unless explicitly disabled.

func WithCLISymbols added in v1.5.0

func WithCLISymbols() Option

WithCLISymbols enables or disables symbol prefixes for CLI format output. Symbols include ✓ for success, ✗ for failure, ⚠ for warnings, etc. This option only affects FormatCLI.

func WithCaller added in v1.0.0

func WithCaller() Option

WithCaller enables caller information.

func WithCallerSkip added in v1.0.0

func WithCallerSkip(skip int) Option

WithCallerSkip sets the number of stack frames to skip for caller info.

func WithDefaultFields added in v1.0.0

func WithDefaultFields(args ...any) Option

WithDefaultFields adds default fields to all log messages.

func WithFormat added in v1.0.0

func WithFormat(format Format) Option

WithFormat sets the output format.

func WithHook added in v1.0.0

func WithHook(hook Hook) Option

WithHook adds a hook to this logger.

func WithLevel added in v1.0.0

func WithLevel(leveler slog.Leveler) Option

WithLevel sets the minimum log level. Accepts slog.Leveler interface, supporting:

  • Static levels: log.DEBUG, log.INFO, etc.
  • slog levels: slog.LevelDebug, slog.LevelInfo, etc.
  • Dynamic levels: &slog.LevelVar{} (can be changed at runtime)

Example with static level:

logger := log.New(log.WithLevel(log.DEBUG))

Example with dynamic level:

logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelInfo)
logger := log.New(log.WithLevel(logLevel))
// Later: logLevel.Set(slog.LevelDebug)

func WithRotation added in v1.0.0

func WithRotation(maxSize, maxBackups, maxAge int, compress bool) Option

WithRotation configures log rotation.

func WithSampling added in v1.0.0

func WithSampling(first, thereafter int) Option

WithSampling configures log sampling.

func WithStackTrace added in v1.0.0

func WithStackTrace(level Level) Option

WithStackTrace enables stack traces for the given level and above.

func WithTimestampFormat added in v1.0.0

func WithTimestampFormat(format string) Option

WithTimestampFormat sets the timestamp format.

func WithWriter added in v1.0.0

func WithWriter(w io.Writer) Option

WithWriter sets the output writer.

func WithWriters added in v1.0.0

func WithWriters(writers ...io.Writer) Option

WithWriters sets multiple output writers (fan-out).

func WithoutTimestamp added in v1.1.0

func WithoutTimestamp() Option

WithoutTimestamp disables timestamp output in logs.

type RotationConfig

type RotationConfig struct {
	MaxSize    int  // Maximum size in MB before rotation
	MaxBackups int  // Maximum number of old log files to retain
	MaxAge     int  // Maximum days to retain old log files
	Compress   bool // Whether to compress rotated files
}

RotationConfig holds log rotation settings.

type SamplingConfig

type SamplingConfig struct {
	First      int // Log first N messages
	Thereafter int // Then log every Nth message
}

SamplingConfig holds sampling settings.

type TestHook

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

TestHook captures log entries for testing.

func (*TestHook) Count

func (h *TestHook) Count() int

Count returns the number of captured entries.

func (*TestHook) CountLevel

func (h *TestHook) CountLevel(level Level) int

CountLevel returns the number of entries at the given level.

func (*TestHook) Entries

func (h *TestHook) Entries() []*Entry

Entries returns all captured entries.

func (*TestHook) HasLevel

func (h *TestHook) HasLevel(level Level) bool

HasLevel checks if any entry has the given level.

func (*TestHook) HasMessage

func (h *TestHook) HasMessage(msg string) bool

HasMessage checks if any entry contains the given message.

func (*TestHook) LastEntry

func (h *TestHook) LastEntry() *Entry

LastEntry returns the last captured entry, or nil if none.

func (*TestHook) Reset

func (h *TestHook) Reset()

Reset clears all captured entries.

type TestLogger

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

TestLogger is a logger designed for testing that captures log entries.

Directories

Path Synopsis
examples
basic command
Basic example demonstrating simple logging usage
Basic example demonstrating simple logging usage
cli command
CLI example demonstrating CLI-optimized logging for command-line tools
CLI example demonstrating CLI-optimized logging for command-line tools
context command
Context example showing logger propagation through context
Context example showing logger propagation through context
dynamic_level command
Dynamic log level example showing runtime level changes
Dynamic log level example showing runtime level changes
hooks command
Hooks example showing integration with external services
Hooks example showing integration with external services
no_timestamp command
production command
Production example with JSON logging, rotation, and hooks
Production example with JSON logging, rotation, and hooks
slog_handler command

Jump to

Keyboard shortcuts

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