output

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: GPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package output provides flexible output destinations for the logger package.

This package implements various writers for log output destinations, including: - Console output with automatic color support based on terminal capabilities - File output with automatic rotation and compression - MultiWriter for sending logs to multiple destinations simultaneously

Each writer implements the Writer interface, which extends io.Writer with methods for synchronization and cleanup:

type Writer interface {
    io.Writer
    Sync() error  // Ensures all data is written
    Close() error // Releases resources
}

FileWriter provides file-based logging with: - Automatic log rotation based on file size - Optional compression of rotated log files - Safe concurrent access - Proper file cleanup and error handling

ConsoleWriter provides console output with: - Automatic color detection for terminals - ANSI color support based on log level - Custom styling options

MultiWriter combines multiple output destinations: - Thread-safe concurrent access - Detailed diagnostics for write failures - Dynamic addition/removal of writers

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrWriterClosed is returned when attempting to write to a closed writer.
	ErrWriterClosed = ewrap.New("writer is closed")

	// ErrBufferFull is returned when the async writer's buffer is full.
	ErrBufferFull = ewrap.New("write buffer is full")

	// ErrFlushTimeout is returned when a flush operation times out.
	ErrFlushTimeout = ewrap.New("flush timed out")

	// ErrInvalidCompression is returned when an invalid compression algorithm is selected.
	ErrInvalidCompression = ewrap.New("invalid compression algorithm")

	// ErrCompressionFailed is returned when a compression operation fails.
	ErrCompressionFailed = ewrap.New("compression failed")
)

Common errors for the output package.

Functions

func ColorWithStyle

func ColorWithStyle(color ColorCode, style Style) string

ColorWithStyle applies a style to a color code.

func CompressFile

func CompressFile(path string, config CompressionConfig) (string, error)

CompressFile compresses a file using the specified algorithm and level. It takes the path to the file to compress, compresses the file, and saves it with the specified extension.

func IsTerminal

func IsTerminal(w io.Writer) bool

IsTerminal checks if the given writer is a terminal. It returns true if the writer is connected to a terminal, and false otherwise. This function is used to determine whether to enable color support for log output.

Types

type AsyncConfig

type AsyncConfig struct {
	// BufferSize is the size of the message buffer channel.
	BufferSize int
	// WaitTimeout is the maximum time to wait for all logs to be written during Flush.
	WaitTimeout time.Duration
	// ErrorHandler is called when an error occurs during async writing.
	ErrorHandler func(error)
	// OverflowStrategy controls what happens when the buffer is full.
	OverflowStrategy AsyncOverflowStrategy
	// DropHandler is invoked with the dropped payload when overflow strategy discards logs.
	DropHandler func([]byte)
	// DropPayloadHandler receives drop notifications with ownership semantics.
	DropPayloadHandler hyperlogger.DropPayloadHandler
	// MetricsReporter receives periodic metrics about the async writer state.
	MetricsReporter func(AsyncMetrics)
	// RetryEnabled enables retry attempts on write failures.
	RetryEnabled bool
	// MaxRetries defines the number of retry attempts after the initial write.
	MaxRetries int
	// RetryBackoff is the base backoff duration between retries.
	RetryBackoff time.Duration
	// RetryBackoffMultiplier scales the backoff after each retry.
	RetryBackoffMultiplier float64
	// RetryMaxBackoff caps the retry backoff duration.
	RetryMaxBackoff time.Duration
}

AsyncConfig configures an AsyncWriter.

type AsyncMetrics

type AsyncMetrics struct {
	Enqueued   uint64
	Processed  uint64
	Dropped    uint64
	WriteError uint64
	Retried    uint64
	QueueDepth int
	Bypassed   uint64
}

AsyncMetrics provides insight into the internal state of the AsyncWriter.

type AsyncOverflowStrategy

type AsyncOverflowStrategy int

AsyncOverflowStrategy defines how AsyncWriter behaves when buffer is full.

const (
	// AsyncOverflowDropNewest drops the incoming log entry (default, previous behaviour).
	AsyncOverflowDropNewest AsyncOverflowStrategy = iota
	// AsyncOverflowBlock makes writers block until there is space in the buffer.
	AsyncOverflowBlock
	// AsyncOverflowDropOldest discards the oldest buffered entry to make space for the new one.
	AsyncOverflowDropOldest
	// AsyncOverflowHandoff writes the entry synchronously when the buffer is full.
	AsyncOverflowHandoff
)

type AsyncWriter

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

AsyncWriter implements asynchronous writing to an io.Writer, buffering writes through a channel to decouple logging from I/O operations.

func NewAsyncWriter

func NewAsyncWriter(out io.Writer, config AsyncConfig) *AsyncWriter

NewAsyncWriter creates a new AsyncWriter that writes to the given writer asynchronously.

func (*AsyncWriter) Close

func (w *AsyncWriter) Close() error

Close stops the background goroutine and closes the message channel.

func (*AsyncWriter) Flush

func (w *AsyncWriter) Flush() error

Flush waits for all logs to be written.

func (*AsyncWriter) Metrics

func (w *AsyncWriter) Metrics() AsyncMetrics

Metrics returns a snapshot of the current metrics counters.

func (*AsyncWriter) Sync

func (w *AsyncWriter) Sync() error

Sync ensures that all buffered logs have been written to the underlying writer. This method is called by the Logger's Sync() method, typically before application shutdown.

func (*AsyncWriter) Underlying added in v0.0.3

func (w *AsyncWriter) Underlying() io.Writer

Underlying returns the writer wrapped by the AsyncWriter.

func (*AsyncWriter) Write

func (w *AsyncWriter) Write(data []byte) (int, error)

Write implements the io.Writer interface for asynchronous writing.

func (*AsyncWriter) WriteCritical added in v0.0.4

func (w *AsyncWriter) WriteCritical(data []byte) (int, error)

WriteCritical bypasses the internal buffer and writes synchronously.

type BufferSize

type BufferSize int

BufferSize represents different buffer sizes for memory optimization.

const (
	// SmallBuffer is optimized for small log entries.
	SmallBuffer BufferSize = 512
	// MediumBuffer is for average log entries.
	MediumBuffer BufferSize = 8 * 1024 // 8KB
	// LargeBuffer size for larger log entries.
	LargeBuffer BufferSize = 32 * 1024 // 32KB
	// XLBuffer for very large log entries or file operations.
	XLBuffer BufferSize = 64 * 1024 // 64KB
)

type ColorCode

type ColorCode int

ColorCode represents ANSI color codes for terminal output.

const (
	// ColorReset removes any color or style formatting.
	ColorReset ColorCode = 0

	// ColorBlack is the ANSI code for black text.
	ColorBlack ColorCode = iota + 29
	// ColorRed is the ANSI code for red text.
	ColorRed
	// ColorGreen is the ANSI code for green text.
	ColorGreen
	// ColorYellow is the ANSI code for yellow text.
	ColorYellow
	// ColorBlue is the ANSI code for blue text.
	ColorBlue
	// ColorMagenta is the ANSI code for magenta text.
	ColorMagenta
	// ColorCyan is the ANSI code for cyan text.
	ColorCyan
	// ColorWhite is the ANSI code for white text.
	ColorWhite
)
const (
	// ColorCodeReset resets all color formatting.
	ColorCodeReset ColorCode = ColorReset
	// ColorCodeBlue is used for Debug level logs.
	ColorCodeBlue ColorCode = ColorBlue
	// ColorCodeGreen is used for Info level logs.
	ColorCodeGreen ColorCode = ColorGreen
	// ColorCodeYellow is used for Warning level logs.
	ColorCodeYellow ColorCode = ColorYellow
	// ColorCodeRed is used for Error level logs.
	ColorCodeRed ColorCode = ColorRed
	// ColorCodeMagenta is used for Trace level logs.
	ColorCodeMagenta ColorCode = ColorMagenta
	// ColorCodeRedBold is a combination of Red color with Bold style.
	ColorCodeRedBold ColorCode = ColorRed // Bold style is applied separately.
)

Specific color codes for log levels.

func (ColorCode) End

func (ColorCode) End() string

End returns the ANSI escape sequence to reset to default color.

func (ColorCode) Start

func (c ColorCode) Start() string

Start returns the ANSI escape sequence to start this color.

func (ColorCode) WithStyle

func (c ColorCode) WithStyle(style Style) string

WithStyle returns a new color string with the given style applied.

func (ColorCode) Wrap

func (c ColorCode) Wrap(s string) string

Wrap wraps the given string with this color code.

type ColorMode

type ColorMode int

ColorMode determines how colors are handled.

const (
	// ColorModeAuto detects if the output supports colors.
	ColorModeAuto ColorMode = iota
	// ColorModeAlways forces color output.
	ColorModeAlways
	// ColorModeNever disables color output.
	ColorModeNever
)

type CompressionAlgorithm

type CompressionAlgorithm string

CompressionAlgorithm represents a compression algorithm.

const (
	// NoCompression represents no compression.
	NoCompression CompressionAlgorithm = "none"
	// GzipCompression represents gzip compression.
	GzipCompression CompressionAlgorithm = "gzip"
)

type CompressionConfig

type CompressionConfig struct {
	// Algorithm is the compression algorithm to use.
	Algorithm CompressionAlgorithm
	// Level is the compression level to use.
	Level int
	// DeleteOriginal determines if the original file should be deleted after compression.
	DeleteOriginal bool
	// Extension is the file extension to use for compressed files (default: .gz).
	Extension string
}

CompressionConfig configures compression for log files.

type CompressionLevel

type CompressionLevel int

CompressionLevel defines the compression level to use.

const (
	// CompressionDefault uses the default gzip compression level.
	CompressionDefault CompressionLevel = 1
	// CompressionBest uses the best (slowest but most effective) compression level.
	CompressionBest CompressionLevel = 9
	// CompressionSpeed optimizes for speed over compression ratio.
	CompressionSpeed CompressionLevel = 1
)

func (CompressionLevel) GzipLevel

func (c CompressionLevel) GzipLevel() int

GzipLevel converts the CompressionLevel to its corresponding gzip compression level integer. It allows seamless conversion between the custom CompressionLevel type and the standard gzip compression level.

type ConsoleWriter

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

ConsoleWriter is a writer that writes to the console with color support and performance optimizations.

func NewConsoleWriter

func NewConsoleWriter(out io.Writer, mode ColorMode) *ConsoleWriter

NewConsoleWriter creates a new ConsoleWriter with improved initialization and performance. The ConsoleWriter is a writer that writes to the console with color support and performance optimizations. It takes an io.Writer and a ColorMode as input, and returns a new ConsoleWriter instance. If the provided io.Writer is nil, it defaults to os.Stdout. The ConsoleWriter initializes its internal state, including the output mode, terminal detection, and color styles for different log levels.

func (*ConsoleWriter) Close

func (w *ConsoleWriter) Close() error

Close closes the underlying io.Writer if it implements the io.Closer interface. If an error occurs while closing the underlying writer, it is wrapped and returned.

func (*ConsoleWriter) Sync

func (w *ConsoleWriter) Sync() error

Sync synchronizes the underlying io.Writer if it implements the Sync() error interface. If the underlying writer does not implement Sync(), this method returns nil.

func (*ConsoleWriter) Write

func (w *ConsoleWriter) Write(payload []byte) (int, error)

Write implements the io.Writer interface for the ConsoleWriter. It writes the provided payload to the console with color support and performance optimizations. It first locks the writer's mutex, then resets and resizes the internal buffer as needed. It then checks if color output should be used based on the configured color mode and the detected log level of the payload. If colors should be used, it applies the appropriate ANSI escape codes before writing the payload to the underlying io.Writer. Finally, it returns the number of bytes written and any error that occurred during the write operation.

type FileConfig

type FileConfig struct {
	// Path is the log file path
	Path string
	// MaxSize is the maximum size in bytes before rotation
	MaxSize int64
	// Compress determines if rotated files should be compressed
	Compress bool
	// FileMode sets the permissions for new log files
	FileMode os.FileMode
	// CompressionConfig provides detailed compression options
	CompressionConfig *CompressionConfig
	// RotationCallback is called after rotation with the path of the rotated file
	RotationCallback func(string)
	// ErrorHandler is called when errors occur during file operations
	ErrorHandler func(error)
}

FileConfig holds configuration for file output.

- Path is the log file path - MaxSize is the maximum size in bytes before rotation - Compress determines if rotated files should be compressed - FileMode sets the permissions for new log files. - CompressionConfig provides detailed compression options - RotationCallback is called after rotation with the path of the rotated file - ErrorHandler is called when errors occur during file operations.

type FileWriter

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

FileWriter implements Writer for file-based logging. It manages the log file, including rotating the file when it reaches a maximum size, and optionally compressing rotated files.

func NewFileWriter

func NewFileWriter(config FileConfig) (*FileWriter, error)

NewFileWriter creates a new file-based log writer. It initializes a FileWriter instance based on the provided FileConfig, ensuring the necessary directories and files are created. The returned FileWriter can be used to write log data to a file, with automatic rotation and compression of rotated files.

func (*FileWriter) Close

func (w *FileWriter) Close() error

Close closes the underlying file. It first syncs any remaining data to the file, and then closes the file. If the file has already been closed, Close returns nil without error.

func (*FileWriter) Sync

func (w *FileWriter) Sync() error

Sync ensures any buffered data is written to the underlying file. If the file has already been closed, Sync returns nil without error. Otherwise, it returns an error if the file could not be synced.

func (*FileWriter) Write

func (w *FileWriter) Write(data []byte) (int, error)

Write implements io.Writer. It writes the provided data to the log file, handling automatic rotation of the log file when the maximum size is reached. It returns the number of bytes written and any error that occurred during the write operation.

type MultiWriter

type MultiWriter struct {
	Writers []Writer
	// contains filtered or unexported fields
}

MultiWriter combines multiple writers into one.

func NewMultiWriter

func NewMultiWriter(writers ...Writer) (*MultiWriter, error)

NewMultiWriter creates a new writer that writes to all provided writers. It filters out nil writers and returns an error if no valid writers are provided.

func (*MultiWriter) AddWriter

func (mw *MultiWriter) AddWriter(writer Writer) error

AddWriter adds a new writer to the MultiWriter. If the provided writer is nil, an error is returned.

func (*MultiWriter) Close

func (mw *MultiWriter) Close() error

Close closes all writers with detailed cleanup tracking. It iterates through the list of writers in the MultiWriter, calling the Close() method on each one. It tracks the number of successful and failed closes, and returns an error if any of the closes fail, including a detailed error report with the failure details.

func (*MultiWriter) RemoveWriter

func (mw *MultiWriter) RemoveWriter(writer Writer)

RemoveWriter removes a writer from the MultiWriter.

func (*MultiWriter) Sync

func (mw *MultiWriter) Sync() error

Sync ensures all writers are synced with comprehensive diagnostics. It iterates through the list of writers in the MultiWriter, calling the Sync() method on each one. It tracks the number of successful and failed syncs, and returns an error if any of the syncs fail, including a detailed error report with the failure details.

func (*MultiWriter) Write

func (mw *MultiWriter) Write(payload []byte) (int, error)

Write sends the output to all writers with detailed diagnostics.

type Style

type Style int

Style represents text style formatting codes for terminal output.

const (
	// StyleBold enables bold text.
	StyleBold Style = 1
	// StyleDim enables dimmed text.
	StyleDim Style = 2
	// StyleItalic enables italic text.
	StyleItalic Style = 3
	// StyleUnderline enables underlined text.
	StyleUnderline Style = 4
	// StyleNormal resets all formatting.
	StyleNormal Style = 22 // Reset to normal style
)

type WriteResult

type WriteResult struct {
	Writer Writer // The writer instance
	Name   string // A descriptive name of the writer
	Bytes  int    // Number of bytes written
	Err    error  // Any error encountered during write
}

WriteResult holds the results of a write operation to a specific Writer. It includes the Writer instance, its name for diagnostics, bytes written, and any error encountered.

type Writer

type Writer interface {
	// Write writes the given bytes to the underlying output.
	Write(p []byte) (n int, err error)
	// Sync ensures that all data has been written.
	Sync() error
	// Close closes the writer and releases any resources.
	Close() error
}

Writer is an interface for log output writers.

func NewWriterAdapter

func NewWriterAdapter(w io.Writer) Writer

NewWriterAdapter wraps a basic io.Writer into a Writer interface implementation used by the output package.

Jump to

Keyboard shortcuts

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