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 ¶
- func ContextWithLogger(ctx context.Context, logger *Logger) context.Context
- func Debug(msg string, args ...any)
- func Error(msg string, args ...any)
- func Failure(msg string)
- func Fatal(msg string, args ...any)
- func Info(msg string, args ...any)
- func IsDebugEnabled() bool
- func IsErrorEnabled() bool
- func IsInfoEnabled() bool
- func IsTraceEnabled() bool
- func IsWarnEnabled() bool
- func Lazy(fn LazyFunc) slog.Attr
- func NewSlogHandler(opts ...Option) slog.Handler
- func NewTestLogger() (*TestLogger, *TestHook)
- func RegisterHook(hook Hook)
- func SetDefault(logger *Logger)
- func SetExitHandler(handler func(int))
- func Step(msg string)
- func Success(msg string)
- func Trace(msg string, args ...any)
- func Warn(msg string, args ...any)
- func Writer(level Level) io.Writer
- type BufferConfig
- type Config
- type Entry
- type Format
- type Hook
- type LazyFunc
- type Level
- type Logger
- func (l *Logger) Debug(msg string, args ...any)
- func (l *Logger) Error(msg string, args ...any)
- func (l *Logger) Failure(msg string)
- func (l *Logger) Fatal(msg string, args ...any)
- func (l *Logger) Info(msg string, args ...any)
- func (l *Logger) IsLevelEnabled(level Level) bool
- func (l *Logger) Slog() *slog.Logger
- func (l *Logger) Step(msg string)
- func (l *Logger) Success(msg string)
- func (l *Logger) Trace(msg string, args ...any)
- func (l *Logger) Warn(msg string, args ...any)
- func (l *Logger) WithFields(args ...any) *Logger
- func (l *Logger) Writer(level Level) io.Writer
- type Option
- func WithBuffer(size int, flushInterval time.Duration) Option
- func WithCLIFields(enabled bool) Option
- func WithCLISymbols() Option
- func WithCaller() Option
- func WithCallerSkip(skip int) Option
- func WithDefaultFields(args ...any) Option
- func WithFormat(format Format) Option
- func WithHook(hook Hook) Option
- func WithLevel(leveler slog.Leveler) Option
- func WithRotation(maxSize, maxBackups, maxAge int, compress bool) Option
- func WithSampling(first, thereafter int) Option
- func WithStackTrace(level Level) Option
- func WithTimestampFormat(format string) Option
- func WithWriter(w io.Writer) Option
- func WithWriters(writers ...io.Writer) Option
- func WithoutTimestamp() Option
- type RotationConfig
- type SamplingConfig
- type TestHook
- type TestLogger
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextWithLogger ¶
ContextWithLogger returns a new context with the logger attached.
func Failure ¶ added in v1.5.0
func Failure(msg string)
Failure logs a failure message 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 IsTraceEnabled ¶
func IsTraceEnabled() bool
IsTraceEnabled returns true if TRACE level is enabled.
func Lazy ¶
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
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.
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.
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 ¶
Hook is a function called for each log entry. Returning an error prevents the log from being written.
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
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
Level implements slog.Leveler interface, allowing Level to be used wherever slog expects a Leveler (e.g., slog.HandlerOptions, dynamic levels).
func (Level) ToSlogLevel ¶
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 FromContext ¶
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 NewCLILogger ¶ added in v1.5.0
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 ¶
WithFields creates a new logger from the default logger with additional fields.
func (*Logger) Failure ¶ added in v1.5.0
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) IsLevelEnabled ¶
IsLevelEnabled returns true if the given level is enabled. This checks against the current log level, which may be dynamic.
func (*Logger) Step ¶ added in v1.5.0
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
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) WithFields ¶
WithFields creates a new logger with additional fields. This follows the immutable pattern - returns a new instance.
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
WithBuffer configures buffered writing.
func WithCLIFields ¶ added in v1.6.0
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 WithCallerSkip ¶ added in v1.0.0
WithCallerSkip sets the number of stack frames to skip for caller info.
func WithDefaultFields ¶ added in v1.0.0
WithDefaultFields adds default fields to all log messages.
func WithFormat ¶ added in v1.0.0
WithFormat sets the output format.
func WithLevel ¶ added in v1.0.0
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
WithRotation configures log rotation.
func WithSampling ¶ added in v1.0.0
WithSampling configures log sampling.
func WithStackTrace ¶ added in v1.0.0
WithStackTrace enables stack traces for the given level and above.
func WithTimestampFormat ¶ added in v1.0.0
WithTimestampFormat sets the timestamp format.
func WithWriter ¶ added in v1.0.0
WithWriter sets the output writer.
func WithWriters ¶ added in v1.0.0
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) CountLevel ¶
CountLevel returns the number of entries at the given level.
func (*TestHook) HasMessage ¶
HasMessage checks if any entry contains the given message.
type TestLogger ¶
type TestLogger struct {
*Logger
// contains filtered or unexported fields
}
TestLogger is a logger designed for testing that captures log entries.
Source Files
¶
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
|