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
- func ClearAsyncMetricsHandlers()
- func ClearContextExtractors()
- func DefaultLevelColors() map[Level]string
- func EmitAsyncMetrics(ctx context.Context, metrics AsyncMetrics)
- func FireRegisteredHooks(ctx context.Context, entry *Entry) []error
- func ParseLevel(level string) (string, error)
- func RegisterAsyncMetricsHandler(handler AsyncMetricsHandler)
- func RegisterContextExtractor(extractor ContextExtractor)
- func RegisterGlobalHook(hookFunc LogHookFunc)
- func RegisterHook(level Level, hookFunc LogHookFunc)
- func SetOutput(output string) (io.Writer, error)
- func UnregisterAllHooks()
- func UnregisterHooks(level Level)
- type AsyncMetrics
- type AsyncMetricsExporter
- type AsyncMetricsHandler
- type AsyncOverflowStrategy
- type ColorConfig
- type Config
- type ConfigBuilder
- func (b *ConfigBuilder) Build() *Config
- func (b *ConfigBuilder) WithAsyncBufferSize(size int) *ConfigBuilder
- func (b *ConfigBuilder) WithAsyncDropHandler(handler func([]byte)) *ConfigBuilder
- func (b *ConfigBuilder) WithAsyncDropPayloadHandler(handler DropPayloadHandler) *ConfigBuilder
- func (b *ConfigBuilder) WithAsyncMetricsHandler(handler AsyncMetricsHandler) *ConfigBuilder
- func (b *ConfigBuilder) WithAsyncOverflowStrategy(strategy AsyncOverflowStrategy) *ConfigBuilder
- func (b *ConfigBuilder) WithCaller(enable bool) *ConfigBuilder
- func (b *ConfigBuilder) WithColors(enable bool) *ConfigBuilder
- func (b *ConfigBuilder) WithConsoleOutput() *ConfigBuilder
- func (b *ConfigBuilder) WithContextExtractor(extractor ContextExtractor) *ConfigBuilder
- func (b *ConfigBuilder) WithContextExtractors(extractors ...ContextExtractor) *ConfigBuilder
- func (b *ConfigBuilder) WithDebugLevel() *ConfigBuilder
- func (b *ConfigBuilder) WithDevelopmentDefaults() *ConfigBuilder
- func (b *ConfigBuilder) WithEnableAsync(enabled bool) *ConfigBuilder
- func (b *ConfigBuilder) WithEncoder(encoder Encoder) *ConfigBuilder
- func (b *ConfigBuilder) WithEncoderName(name string) *ConfigBuilder
- func (b *ConfigBuilder) WithEncoderRegistry(registry *EncoderRegistry) *ConfigBuilder
- func (b *ConfigBuilder) WithField(key string, value any) *ConfigBuilder
- func (b *ConfigBuilder) WithFields(fields []Field) *ConfigBuilder
- func (b *ConfigBuilder) WithFileCompression(level int) *ConfigBuilder
- func (b *ConfigBuilder) WithFileOutput(path string) *ConfigBuilder
- func (b *ConfigBuilder) WithFileRetention(maxAgeDays, maxFiles int) *ConfigBuilder
- func (b *ConfigBuilder) WithFileRotation(maxSizeBytes int64, compress bool) *ConfigBuilder
- func (b *ConfigBuilder) WithForceColors(force bool) *ConfigBuilder
- func (b *ConfigBuilder) WithHook(name string, hook Hook) *ConfigBuilder
- func (b *ConfigBuilder) WithInfoLevel() *ConfigBuilder
- func (b *ConfigBuilder) WithJSONFormat(enable bool) *ConfigBuilder
- func (b *ConfigBuilder) WithLevel(level Level) *ConfigBuilder
- func (b *ConfigBuilder) WithLocalDefaults() *ConfigBuilder
- func (b *ConfigBuilder) WithNoTimestamp() *ConfigBuilder
- func (b *ConfigBuilder) WithOutput(output io.Writer) *ConfigBuilder
- func (b *ConfigBuilder) WithProductionDefaults() *ConfigBuilder
- func (b *ConfigBuilder) WithSampling(enabled bool, initial, thereafter int, perLevel bool) *ConfigBuilder
- func (b *ConfigBuilder) WithSamplingRule(level Level, rule SamplingRule) *ConfigBuilder
- func (b *ConfigBuilder) WithSamplingRules(rules map[Level]SamplingRule) *ConfigBuilder
- func (b *ConfigBuilder) WithStackTrace(enable bool) *ConfigBuilder
- func (b *ConfigBuilder) WithTimeFormat(format string) *ConfigBuilder
- type ContextExtractor
- type DropPayload
- type DropPayloadHandler
- type Encoder
- type EncoderRegistry
- type Entry
- type Field
- func Any(key string, value any) Field
- func ApplyContextExtractors(ctx context.Context, extractors ...ContextExtractor) []Field
- func Bool(key string, value bool) Field
- func Duration(key string, value time.Duration) Field
- func Error(key string, err error) Field
- func Float64(key string, value float64) Field
- func Int(key string, value int) Field
- func Int64(key string, value int64) Field
- func Str(key, value string) Field
- func Time(key string, value time.Time) Field
- func Uint64(key string, value uint64) Field
- type FileConfig
- type FormattedLogger
- type Hook
- type HookConfig
- type HookRegistry
- func (r *HookRegistry) AddFunc(level Level, hookFunc LogHookFunc)
- func (r *HookRegistry) AddHook(name string, hook Hook) error
- func (r *HookRegistry) Dispatch(ctx context.Context, entry *Entry) []error
- func (r *HookRegistry) FireHooks(entry *Entry) []errordeprecated
- func (r *HookRegistry) GetHook(name string) (Hook, bool)
- func (r *HookRegistry) GetHooksForLevel(level Level) []Hook
- func (r *HookRegistry) RemoveFuncs(level Level)
- func (r *HookRegistry) RemoveHook(name string) bool
- func (r *HookRegistry) ResetFuncs()
- type Level
- type LogHook
- type LogHookFunc
- type Logger
- type Methods
- type NoopLogger
- func (*NoopLogger) Debug(_ string)
- func (*NoopLogger) Debugf(_ string, _ ...any)
- func (*NoopLogger) Error(_ string)
- func (*NoopLogger) Errorf(_ string, _ ...any)
- func (*NoopLogger) Fatal(_ string)
- func (*NoopLogger) Fatalf(_ string, _ ...any)
- func (l *NoopLogger) GetConfig() *Config
- func (l *NoopLogger) GetLevel() Level
- func (*NoopLogger) Info(_ string)
- func (*NoopLogger) Infof(_ string, _ ...any)
- func (l *NoopLogger) SetLevel(level Level)
- func (*NoopLogger) Sync() error
- func (*NoopLogger) Trace(_ string)
- func (*NoopLogger) Tracef(_ string, _ ...any)
- func (*NoopLogger) Warn(_ string)
- func (*NoopLogger) Warnf(_ string, _ ...any)
- func (l *NoopLogger) WithContext(_ context.Context) Logger
- func (l *NoopLogger) WithError(_ error) Logger
- func (l *NoopLogger) WithField(_ string, _ any) Logger
- func (l *NoopLogger) WithFields(_ ...Field) Logger
- type PayloadLease
- type SamplingConfig
- type SamplingRule
- type StandardHook
Constants ¶
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" )
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 ¶
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 ¶
FireRegisteredHooks executes the global LogHookFuncs registered via RegisterHook/RegisterGlobalHook and returns any errors they produced.
func ParseLevel ¶
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 ¶
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 ¶
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.
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 ¶
Field represents a key-value pair in structured logging.
func ApplyContextExtractors ¶ added in v0.0.4
func ApplyContextExtractors(ctx context.Context, extractors ...ContextExtractor) []Field
ApplyContextExtractors executes the provided extractors against the context.
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 ¶
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 )
type LogHook ¶
type LogHook struct {
Name string
Func LogHookFunc
Level Level
}
LogHook is a container for LogHookFunc with associated metadata.
type LogHookFunc ¶
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.
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) 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) 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) 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
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.
Source Files
¶
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
|
|
|
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. |