Documentation
¶
Overview ¶
Package logmgr provides high-performance structured logging for Go applications.
Index ¶
- Variables
- func AddSink(sink Sink)
- func Debug(message string, fields ...LogField)
- func Error(message string, fields ...LogField)
- func Fatal(message string, fields ...LogField)
- func Info(message string, fields ...LogField)
- func SetLevel(level Level)
- func SetSinks(sinks ...Sink)
- func Shutdown()
- func Warn(message string, fields ...LogField)
- type AsyncFileSink
- type ConsoleSink
- type Entry
- type FileSink
- type Level
- type LogField
- type Logger
- type RingBuffer
- type Sink
- type StderrSink
- type Worker
Constants ¶
This section is empty.
Variables ¶
var DefaultConsoleSink = NewConsoleSink()
DefaultConsoleSink is a pre-configured console sink instance that can be used immediately. This is the most common way to add console logging to your application.
Example:
logmgr.AddSink(logmgr.DefaultConsoleSink)
Functions ¶
func AddSink ¶
func AddSink(sink Sink)
AddSink adds a sink to the logger
Example:
logmgr.AddSink(logmgr.DefaultConsoleSink) fileSink, _ := logmgr.NewFileSink("app.log", 24*time.Hour, 100*1024*1024) logmgr.AddSink(fileSink)
func Debug ¶
Debug logs a message at debug level with optional structured fields
Example:
logmgr.Debug("Processing request", logmgr.Field("request_id", "req-123"), logmgr.Field("user_id", 456), )
func Error ¶
Error logs a message at error level with optional structured fields
Example:
logmgr.Error("Database connection failed", logmgr.Field("error", "connection timeout"), logmgr.Field("host", "db.example.com"), logmgr.Field("retries", 3), )
func Fatal ¶
Fatal logs a message at fatal level with optional structured fields and exits the program
Example:
logmgr.Fatal("Critical system failure", logmgr.Field("error", "out of memory"), logmgr.Field("available_memory", "0MB"), )
func Info ¶
Info logs a message at info level with optional structured fields
Example:
logmgr.Info("User logged in", logmgr.Field("user_id", 12345), logmgr.Field("action", "login"), )
func SetLevel ¶
func SetLevel(level Level)
SetLevel sets the global log level
Example:
logmgr.SetLevel(logmgr.DebugLevel)
func SetSinks ¶
func SetSinks(sinks ...Sink)
SetSinks replaces all sinks with the provided ones
Example:
logmgr.SetSinks(logmgr.DefaultConsoleSink, fileSink)
Types ¶
type AsyncFileSink ¶
type AsyncFileSink struct { *FileSink // Embedded FileSink for actual file operations // contains filtered or unexported fields }
AsyncFileSink is a high-performance asynchronous file sink that writes log entries in a background goroutine. This provides maximum performance by decoupling log writing from the application's critical path.
Features:
- Non-blocking writes with configurable buffer
- Background writer goroutine
- Automatic fallback to synchronous writes when buffer is full
- All FileSink features (rotation, buffering, etc.)
Example:
asyncSink, err := logmgr.NewAsyncFileSink("app.log", 24*time.Hour, 100*1024*1024, 1000) if err != nil { panic(err) } defer asyncSink.Close() logmgr.AddSink(asyncSink)
func NewAsyncFileSink ¶
func NewAsyncFileSink(filename string, maxAge time.Duration, maxSize int64, bufferSize int) (*AsyncFileSink, error)
NewAsyncFileSink creates a new asynchronous file sink with the specified parameters.
Parameters:
- filename: Path to the log file
- maxAge: Maximum age before rotation (0 disables age-based rotation)
- maxSize: Maximum size in bytes before rotation (0 disables size-based rotation)
- bufferSize: Size of the internal channel buffer for async writes
The background writer goroutine is started automatically and will process log entries every 100ms or when entries are available.
Example:
// High-performance async sink with 1000-entry buffer sink, err := logmgr.NewAsyncFileSink("logs/app.log", 24*time.Hour, 100*1024*1024, 1000) if err != nil { return err } defer sink.Close()
func (*AsyncFileSink) Close ¶
func (afs *AsyncFileSink) Close() error
Close gracefully shuts down the async file sink by stopping the background writer and ensuring all buffered entries are written to disk.
This method will block until all pending writes are completed, ensuring no log entries are lost during shutdown. It's safe to call Close multiple times.
Example:
defer asyncSink.Close()
func (*AsyncFileSink) Write ¶
func (afs *AsyncFileSink) Write(entries []*Entry) error
Write writes log entries to the async buffer for background processing. This method is non-blocking and returns immediately in most cases.
If the internal buffer is full, the method falls back to synchronous writing to prevent blocking the application. A copy of the entries is made since the original slice may be reused by the caller.
This method is safe for concurrent use.
type ConsoleSink ¶
type ConsoleSink struct {
// contains filtered or unexported fields
}
ConsoleSink writes log entries to stdout in JSON format with high performance buffering. It implements the Sink interface and is safe for concurrent use.
Example:
sink := logmgr.NewConsoleSink() logmgr.AddSink(sink)
func NewConsoleSink ¶
func NewConsoleSink() *ConsoleSink
NewConsoleSink creates a new console sink that writes to stdout. The sink uses an 8KB buffer for optimal performance.
Example:
consoleSink := logmgr.NewConsoleSink() logmgr.AddSink(consoleSink)
func (*ConsoleSink) Close ¶
func (cs *ConsoleSink) Close() error
Close flushes any remaining buffered data and closes the console sink. This method should be called during application shutdown to ensure all log entries are written.
Example:
defer consoleSink.Close()
func (*ConsoleSink) Write ¶
func (cs *ConsoleSink) Write(entries []*Entry) error
Write writes a batch of log entries to stdout in JSON format. Each entry is written as a single line of JSON followed by a newline. This method is safe for concurrent use.
The method will skip any entries that fail to marshal to JSON rather than failing the entire batch.
Example output:
{"level":"info","timestamp":"2024-01-15T10:30:45.123Z","message":"User logged in","user_id":12345} {"level":"error","timestamp":"2024-01-15T10:30:46.456Z","message":"Database error","error":"connection timeout"}
type Entry ¶
type Entry struct { Level Level `json:"level"` Timestamp time.Time `json:"timestamp"` Message string `json:"message"` Fields map[string]interface{} `json:"-"` // Don't marshal this directly // contains filtered or unexported fields }
Entry represents a log entry with structured fields
func (*Entry) MarshalJSON ¶
MarshalJSON implements custom JSON marshaling for Entry with flattened fields Field ordering convention: level, timestamp, message, then custom fields in alphabetical order
type FileSink ¶
type FileSink struct {
// contains filtered or unexported fields
}
FileSink writes log entries to a file with automatic rotation support. It implements the Sink interface and provides both time-based and size-based rotation. The sink is safe for concurrent use and uses buffered I/O for optimal performance.
Features:
- Automatic file rotation based on age and/or size
- Thread-safe concurrent writes
- Buffered I/O with 16KB buffer
- Automatic directory creation
- Timestamped rotated files
Example:
fileSink, err := logmgr.NewFileSink("app.log", 24*time.Hour, 100*1024*1024) if err != nil { panic(err) } logmgr.AddSink(fileSink)
func NewDefaultFileSink ¶
NewDefaultFileSink creates a file sink with default settings for backward compatibility. Uses a default maximum size of 100MB with the specified age limit.
This function will panic if the file cannot be created, making it suitable for initialization code where errors should be fatal.
Example:
sink := logmgr.NewDefaultFileSink("app.log", 24*time.Hour) logmgr.AddSink(sink)
func NewFileSink ¶
NewFileSink creates a new file sink with the specified rotation parameters.
Parameters:
- filename: Path to the log file (directories will be created if needed)
- maxAge: Maximum age before rotation (0 disables age-based rotation)
- maxSize: Maximum size in bytes before rotation (0 disables size-based rotation)
The sink will rotate the file when either condition is met. Rotated files are renamed with a timestamp suffix (e.g., "app_2024-01-15_10-30-45.log").
Example:
// Rotate daily or when file reaches 100MB sink, err := logmgr.NewFileSink("logs/app.log", 24*time.Hour, 100*1024*1024) if err != nil { return err } defer sink.Close()
func (*FileSink) Close ¶
Close flushes any remaining buffered data and closes the file sink. This method should be called during application shutdown to ensure all log entries are written and the file is properly closed. It's safe to call Close multiple times.
Example:
defer fileSink.Close()
func (*FileSink) Write ¶
Write writes a batch of log entries to the file in JSON format. Each entry is written as a single line of JSON followed by a newline. This method is safe for concurrent use and will automatically rotate the file if rotation conditions are met.
The method will skip any entries that fail to marshal to JSON rather than failing the entire batch. File rotation is checked before writing the batch.
Example output in file:
{"level":"info","timestamp":"2024-01-15T10:30:45.123Z","message":"User logged in","user_id":12345} {"level":"error","timestamp":"2024-01-15T10:30:46.456Z","message":"Database error","error":"connection timeout"}
type Level ¶
type Level int32
Level represents log severity levels
const ( // DebugLevel is used for detailed debugging information DebugLevel Level = iota // InfoLevel is used for general informational messages InfoLevel // WarnLevel is used for potentially harmful situations WarnLevel // ErrorLevel is used for error events that might still allow the application to continue ErrorLevel // FatalLevel is used for very severe error events that will lead the application to abort FatalLevel )
type LogField ¶
type LogField struct { Key string Value interface{} }
LogField represents a structured logging field
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger represents the main logger instance with high-performance features
type RingBuffer ¶
type RingBuffer struct {
// contains filtered or unexported fields
}
RingBuffer implements a lock-free ring buffer for high-performance logging
func NewRingBuffer ¶
func NewRingBuffer(size uint64) *RingBuffer
NewRingBuffer creates a new ring buffer with the given size (must be power of 2)
func (*RingBuffer) Pop ¶
func (rb *RingBuffer) Pop(entries []*Entry) int
Pop removes and returns entries from the ring buffer
func (*RingBuffer) Push ¶
func (rb *RingBuffer) Push(entry *Entry) bool
Push adds an entry to the ring buffer (lock-free)
type Sink ¶
type Sink interface { // Write processes a batch of log entries Write(entries []*Entry) error // Close gracefully shuts down the sink Close() error }
Sink interface for output destinations
type StderrSink ¶
type StderrSink struct {
// contains filtered or unexported fields
}
StderrSink writes log entries to stderr in JSON format. This is useful for separating error logs from regular output or when stdout is used for application data.
Example:
stderrSink := logmgr.NewStderrSink() logmgr.AddSink(stderrSink)
func NewStderrSink ¶
func NewStderrSink() *StderrSink
NewStderrSink creates a new stderr sink that writes to stderr. The sink uses an 8KB buffer for optimal performance.
Example:
stderrSink := logmgr.NewStderrSink() logmgr.AddSink(stderrSink)
func (*StderrSink) Close ¶
func (ss *StderrSink) Close() error
Close flushes any remaining buffered data and closes the stderr sink. This method should be called during application shutdown to ensure all log entries are written.
func (*StderrSink) Write ¶
func (ss *StderrSink) Write(entries []*Entry) error
Write writes a batch of log entries to stderr in JSON format. Each entry is written as a single line of JSON followed by a newline. This method is safe for concurrent use.
The method will skip any entries that fail to marshal to JSON rather than failing the entire batch.