Documentation
¶
Index ¶
- Constants
- Variables
- func IsProtocolError(err error) bool
- func Trace(message string, err error) error
- type Buffer
- type BufferConfig
- type BufferProfile
- type CallInfo
- type Clock
- type ConsoleTransport
- type Field
- func Bool(key string, val bool) Field
- func Duration(key string, d time.Duration) Field
- func Float(key string, val float64) Field
- func Int(key string, val int) Field
- func NamedErr(key string, err error) Field
- func RawBytes(key string, b []byte) Field
- func String(key, val string) Field
- func Time(key string, t time.Time) Field
- func UUID(key string, id [16]byte) Field
- func Uint(key string, num uint) Field
- func Uint64(key string, num uint64) Field
- type FileTransport
- type HTTPStatusError
- type HTTPTransport
- type Kind
- type Logger
- func (l *Logger) Close() error
- func (l *Logger) Debug(msg string, fields ...Field)
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) EnableStats(enabled bool) *Logger
- func (l *Logger) Error(msg string, fields ...Field)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) Fatal(msg string, fields ...Field)
- func (l *Logger) Fatalf(format string, args ...any)
- func (l *Logger) Flush() error
- func (l *Logger) Info(msg string, fields ...Field)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) LastError() error
- func (l *Logger) LimitRate(max int, interval time.Duration) *Logger
- func (l *Logger) LogDebug(msg string, fields ...Field)
- func (l *Logger) LogError(msg string, fields ...Field)
- func (l *Logger) LogFatal(msg string, fields ...Field)
- func (l *Logger) LogInfo(msg string, fields ...Field)
- func (l *Logger) LogWarn(msg string, fields ...Field)
- func (l *Logger) Stats() LoggerStats
- func (l *Logger) TrackErrorTypes(maxKinds int) *Logger
- func (l *Logger) Warn(msg string, fields ...Field)
- func (l *Logger) Warnf(format string, args ...any)
- func (l *Logger) With(fields ...Field) *Logger
- type LoggerStats
- type MultiTransport
- type MultiTransportError
- type Option
- func WithBuffer(config BufferConfig) Option
- func WithBufferProfile(profile BufferProfile) Option
- func WithFields(fields ...Field) Option
- func WithFlushInterval(interval time.Duration) Option
- func WithFlushSize(size int) Option
- func WithRetryPolicy(policy RetryPolicy) Option
- func WithTransport(transports ...Transport) Option
- type Pipeline
- func (p *Pipeline) Close() error
- func (p *Pipeline) Flush(flushing []byte) error
- func (p *Pipeline) FlushBuffer() error
- func (p *Pipeline) FlushErrors() uint64
- func (p *Pipeline) LastError() error
- func (p *Pipeline) Push(data []byte) error
- func (p *Pipeline) SetFlushSize(size int) *Pipeline
- func (p *Pipeline) Start()
- type ProtocolError
- type RetryClassifier
- type RetryPolicy
- type Shard
- type SyncMode
- type TCPTransport
- type TracedError
- type Transport
- type UDPTransport
Constants ¶
const ( KB = 1 << (10 * iota) // 1 << 10 (1 Килобайт)KB MB = 1 << (10 * iota) // 1 << 20 (1 Мегабайт)MB GB = 1 << (10 * iota) // 1 << 30 (1 Гигабайт)GB )
Variables ¶
var ( // ErrNoPipeline is returned when Flush is called without a configured pipeline. ErrNoPipeline = errors.New("siglog: logger has no pipeline") // ErrNoTransport is returned when the configured pipeline has no transport. ErrNoTransport = errors.New("siglog: pipeline has no transport") // ErrPipelineClosed is returned when trying to add a record after Close begins. ErrPipelineClosed = errors.New("siglog: pipeline is closing or closed") // ErrRecordTooLarge is returned when a record cannot fit in one shard. ErrRecordTooLarge = errors.New("siglog: record exceeds shard writable capacity") // ErrBufferFull is retained for explicit buffer-full reporting. ErrBufferFull = errors.New("siglog: buffer is full") // ErrTransportClosed is returned when writing to a closed transport. ErrTransportClosed = errors.New("siglog: transport is closed") // ErrMalformedRecord is returned when a binary record cannot be decoded. ErrMalformedRecord = errors.New("siglog: malformed binary record") )
Functions ¶
func IsProtocolError ¶
IsProtocolError reports whether err or one of its wrapped errors is a ProtocolError. This helper is optional; errors.As can be used directly.
Types ¶
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer distributes records across a fixed ring of shards. The ring of shards is intentionally retained; each Shard owns its byte ring and its lock.
func NewBuffer ¶
NewBuffer creates a sharded buffer. Each shard reserves one byte, so its writable capacity is shardCapacity-1. Invalid small inputs are normalized.
func (*Buffer) Len ¶
Len returns the approximate number of buffered bytes. With size tracking enabled it is an O(1) atomic read; otherwise it scans the shards.
func (*Buffer) SetTrackLen ¶
SetTrackLen enables the aggregate byte counter used by size-triggered flushing. Configure it before concurrent writes. When disabled, Len scans shards on demand and writes avoid a shared atomic update on every record.
type BufferConfig ¶
BufferConfig controls the sharded ring buffer. ShardCapacity is the physical byte capacity of each shard, including the one reserved byte that distinguishes a full ring from an empty ring. A shard can therefore store ShardCapacity-1 bytes.
type BufferProfile ¶
type BufferProfile uint8
BufferProfile selects a tested starting point for the ring-buffer configuration. Profiles are defaults to benchmark against your workload, not throughput guarantees.
const ( // ProfileBalanced favors a moderate memory footprint and general workloads. ProfileBalanced BufferProfile = iota + 1 // ProfileLowMemory reduces the memory reserved for ring buffers. ProfileLowMemory // ProfileHighThroughput reserves more ring-buffer memory and uses more shards. ProfileHighThroughput )
type CallInfo ¶
type CallInfo struct {
// contains filtered or unexported fields
}
CallInfo describes the source location associated with a log record. Its fields are private so the value can be extended without breaking callers.
func ReceiveInfo ¶
func ReceiveInfo() *CallInfo
ReceiveInfo returns the file and line of the caller of ReceiveInfo.
type Clock ¶
type Clock struct {
// contains filtered or unexported fields
}
Clock caches a formatted wall-clock timestamp. It refreshes every millisecond and should be closed when no longer used. The cached bytes are immutable and never exposed directly to callers.
func NewClock ¶
NewClock starts a timestamp cache using layout, following time.Time.Format. Close stops its background goroutine. An empty layout is passed to Format as-is.
func (*Clock) AppendTime ¶
AppendTime appends the latest cached timestamp to dst. It avoids allocating a separate slice when dst already has enough capacity.
type ConsoleTransport ¶
type ConsoleTransport struct {
// contains filtered or unexported fields
}
ConsoleTransport decodes binary records and writes human-readable lines. ANSI colors are enabled automatically only when the target writer is a terminal.
func NewConsoleTransport ¶
func NewConsoleTransport() *ConsoleTransport
NewConsoleTransport creates a color-aware, human-readable stdout transport. Use WithWriter to redirect output and WithColor to explicitly control colors.
func (*ConsoleTransport) Close ¶
func (t *ConsoleTransport) Close() error
Close is a no-op because ConsoleTransport does not own stdout or custom writers.
func (*ConsoleTransport) WithColor ¶
func (t *ConsoleTransport) WithColor(enabled bool) *ConsoleTransport
WithColor explicitly enables or disables ANSI colors.
func (*ConsoleTransport) WithWriter ¶
func (t *ConsoleTransport) WithWriter(writer io.Writer) *ConsoleTransport
WithWriter directs console output to a custom writer, useful for tests and embedding. Color detection is not repeated; call WithColor to choose it.
func (*ConsoleTransport) Write ¶
func (t *ConsoleTransport) Write(data []byte) error
type Field ¶
Field represents a key-value pair without using interfaces. NumVal is always 64 bits so timestamps, durations, float bit patterns and uint64 values are encoded consistently on 32-bit and 64-bit Go targets. Use the constructors below rather than constructing numeric fields manually.
type FileTransport ¶
type FileTransport struct {
// contains filtered or unexported fields
}
func NewFileTransport ¶
func NewFileTransport(file *os.File, mode SyncMode) *FileTransport
NewFileTransport writes binary batches to file. SyncAlways calls Sync after each batch.
func (*FileTransport) Close ¶
func (t *FileTransport) Close() error
Close closes the underlying file once. The transport takes ownership of file.
func (*FileTransport) Write ¶
func (t *FileTransport) Write(data []byte) error
Write writes the complete batch and optionally syncs it to stable storage.
type HTTPStatusError ¶
HTTPStatusError represents a non-2xx response. 429 and 5xx responses are retryable; other status codes are treated as permanent client-side failures.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
func (*HTTPStatusError) Retryable ¶
func (e *HTTPStatusError) Retryable() bool
type HTTPTransport ¶
type HTTPTransport struct {
Client *http.Client
Headers http.Header
// contains filtered or unexported fields
}
func NewHTTPTransport ¶
func NewHTTPTransport(host string, client *http.Client) *HTTPTransport
NewHTTPTransport creates an HTTP POST transport. When client is nil, a client with a five-second timeout is used. A supplied client retains its own timeout settings, so callers should configure one to keep shutdown bounded.
func (*HTTPTransport) Close ¶
func (t *HTTPTransport) Close() error
Close is a no-op; net/http manages HTTP connections through its Client.
func (*HTTPTransport) Write ¶
func (t *HTTPTransport) Write(data []byte) error
Write posts the complete binary batch and rejects non-2xx HTTP status codes.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger writes binary records through an internal Pipeline. Applications use Logger's methods rather than manipulating the pipeline or its ring-buffer shards. Context fields are immutable after construction; use With to derive a logger.
func New ¶
New creates a logger using the balanced default profile or the supplied options. With no WithTransport option, output is written as readable, color-aware console lines. New starts background flushing; always call Close when the logger is done.
func NewWithPipeline ¶
NewWithPipeline attaches a logger to an existing Pipeline. This is a low-level integration hook for tests or advanced setups; the caller is responsible for starting the pipeline. Most applications should use New with functional options.
func (*Logger) Close ¶
Close stops background flushing, performs a final flush, and closes transports. It is safe to call more than once. Derived loggers from With share this lifecycle.
func (*Logger) EnableStats ¶
EnableStats controls aggregate counters. Statistics are disabled by default to minimize hot-path overhead. Enabling them starts counting immediately; disabling them preserves already collected values without further updates.
func (*Logger) Fatal ¶
Fatal logs a fatal-level record. It deliberately does not terminate the process.
func (*Logger) Fatalf ¶
Fatalf logs a formatted fatal-level message without terminating the process.
func (*Logger) Flush ¶
Flush sends the currently buffered batch to configured transports and returns the final transport error after the configured bounded retry attempts.
func (*Logger) LimitRate ¶
LimitRate allows at most max messages per fixed interval. A non-positive max or interval disables limiting. The configuration is shared with loggers derived through With. Configure the limit before concurrent log calls. Fixed windows are efficient but can allow a burst at a window boundary.
func (*Logger) LogInfo ¶
LogInfo, LogWarn, LogError, LogDebug and LogFatal are explicit-name aliases.
func (*Logger) Stats ¶
func (l *Logger) Stats() LoggerStats
Stats returns a point-in-time snapshot of activity counters. Per-error-type counts are empty unless TrackErrorTypes was explicitly enabled.
func (*Logger) TrackErrorTypes ¶
TrackErrorTypes enables bounded per-error-type counters and aggregate stats. maxKinds limits the number of concrete error-type keys; additional keys are counted under the extra "other" bucket. Passing maxKinds <= 0 disables detailed tracking. Aggregate counters remain enabled until EnableStats(false).
type LoggerStats ¶
type LoggerStats struct {
Total uint64 `json:"total"`
Debug uint64 `json:"debug"`
Info uint64 `json:"info"`
Warn uint64 `json:"warn"`
Error uint64 `json:"error"`
Fatal uint64 `json:"fatal"`
Dropped uint64 `json:"dropped"`
RateLimited uint64 `json:"rate_limited"`
EncodingErrors uint64 `json:"encoding_errors"`
FlushErrors uint64 `json:"flush_errors"`
FlushRecordsUnconfirmed uint64 `json:"flush_records_unconfirmed"`
BufferErrors uint64 `json:"buffer_errors"`
ErrorsByType map[string]uint64 `json:"errors_by_type,omitempty"`
}
LoggerStats is a snapshot of logging activity collected while EnableStats(true) is active. Statistics are disabled by default to minimize high-load overhead. Total and per-level counters count attempted calls, including rate-limited or otherwise dropped calls. RateLimited is a subset of Dropped. FlushErrors reflects batch-write failures reported by the attached Pipeline. ErrorsByType is derived from the "error_type" or "error" string field on Error/Fatal calls; a stable value such as "db_timeout" is preferable.
func (LoggerStats) Format ¶
func (s LoggerStats) Format(color bool) string
Format returns a compact statistics report. Set color=true to request ANSI colors; callers should disable it for files, CI logs, and non-terminal output.
func (LoggerStats) String ¶
func (s LoggerStats) String() string
String renders a stable, human-readable, non-colored representation of the snapshot.
type MultiTransport ¶
type MultiTransport struct {
// contains filtered or unexported fields
}
MultiTransport fans each binary batch out to every configured destination. Delivery is best-effort with bounded retries; if the whole batch is retried later after one destination succeeded and another failed, successful sinks may receive the same batch more than once.
func NewTransport ¶
func NewTransport(transports ...Transport) *MultiTransport
NewTransport creates a group that writes each batch to every configured transport. A failing transport is retried independently, so another transport's successful write is not repeated within the same Write call.
func (*MultiTransport) Close ¶
func (t *MultiTransport) Close() error
Close closes each configured transport once and joins any errors.
func (*MultiTransport) SetRetryPolicy ¶
func (t *MultiTransport) SetRetryPolicy(policy RetryPolicy) error
SetRetryPolicy configures retries for subsequent writes. Configure this before starting concurrent logging. MaxAttempts=1 disables retries.
func (*MultiTransport) Write ¶
func (t *MultiTransport) Write(data []byte) error
Write sends a batch to every transport, retrying failures according to RetryPolicy.
type MultiTransportError ¶
type MultiTransportError struct {
// contains filtered or unexported fields
}
MultiTransportError reports failures from one or more destinations. It wraps all per-transport errors for errors.Is/errors.As and is retryable only when every failed destination classified its final error as retryable.
func (*MultiTransportError) Error ¶
func (e *MultiTransportError) Error() string
func (*MultiTransportError) Retryable ¶
func (e *MultiTransportError) Retryable() bool
Retryable is false if any failed destination reported a permanent error.
func (*MultiTransportError) Unwrap ¶
func (e *MultiTransportError) Unwrap() error
type Option ¶
type Option func(*loggerConfig) error
Option configures a Logger created by New. Options are validated before any background goroutine is started.
func WithBuffer ¶
func WithBuffer(config BufferConfig) Option
WithBuffer uses an explicit shard count and physical capacity per shard. Flush settings remain independently configurable. If WithFlushSize is not supplied, the constructor chooses a conservative threshold based on capacity.
func WithBufferProfile ¶
func WithBufferProfile(profile BufferProfile) Option
WithBufferProfile selects a preset for shard count, per-shard capacity, flush interval, and flush threshold. Later WithFlushInterval/WithFlushSize options override the profile's corresponding values. It cannot be combined with WithBuffer; choose either a profile or explicit shard settings.
func WithFields ¶
WithFields adds persistent context fields that are included in every record written by the new logger. Call Logger.With to derive a contextual logger later.
func WithFlushInterval ¶
WithFlushInterval sets the period for background flushing. A value of zero disables timer-triggered flushing; size-triggered flushes and Close still work.
func WithFlushSize ¶
WithFlushSize requests a flush when buffered bytes reach size. Zero disables size-triggered flushing. A negative size is invalid.
func WithRetryPolicy ¶
func WithRetryPolicy(policy RetryPolicy) Option
WithRetryPolicy configures the bounded retry behavior for transport writes. MaxAttempts includes the initial write; a value of one disables retries.
func WithTransport ¶
WithTransport adds one or more destinations. Batches are sent to all configured transports through MultiTransport. If no transport option is supplied, New uses a human-readable console transport.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
func NewPipeline ¶
func NewPipeline(count, capacity int, timeout time.Duration, transport *MultiTransport) *Pipeline
NewPipeline creates a pipeline. The shard count and capacities are normalized by NewBuffer. A timeout <= 0 disables timer-based flushes; Flush or Close still drains buffered records.
func (*Pipeline) Close ¶
Close is idempotent. It prevents new pushes, waits for Start if running, flushes the records still in the ring buffer, closes transports, and returns any final flush/close error. If an earlier batch failed, Close also reports the most recent flush failure so asynchronous errors are not silently lost.
func (*Pipeline) Flush ¶
Flush writes an already assembled batch. It returns an error after the MultiTransport retry policy is exhausted; the supplied batch is not retained. Use FlushBuffer or Logger.Flush to drain the pipeline's ring buffer.
func (*Pipeline) FlushBuffer ¶
FlushBuffer drains records from Buffer and writes them to the configured transport. On failure, it returns the final transport error and discards that unconfirmed batch rather than retaining memory or retrying it automatically. It serializes periodic, size-triggered, and explicit flush operations.
func (*Pipeline) FlushErrors ¶
FlushErrors returns the cumulative number of batch-write failures after the configured MultiTransport retry policy was exhausted.
func (*Pipeline) LastError ¶
LastError returns the most recent flush failure. Successful later flushes do not clear it, because a failed batch has already been reported as unconfirmed.
func (*Pipeline) SetFlushSize ¶
SetFlushSize requests a flush once the approximate buffered byte count reaches size. A non-positive size disables size-triggered flushes. Call before Start for deterministic configuration.
func (*Pipeline) Start ¶
func (p *Pipeline) Start()
Start runs the periodic/size-triggered flusher until Close is called. Calling Start more than once has no effect. Each failed batch is attempted according to MultiTransport's bounded RetryPolicy and then reported through LastError, statistics, and Close; Pipeline does not retry that batch in the background.
type ProtocolError ¶
ProtocolError describes a protocol-level failure returned by a transport.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type RetryClassifier ¶
type RetryClassifier interface {
Retryable() bool
}
RetryClassifier lets a custom transport error control whether MultiTransport retries it. Errors without this interface are retried using the configured bounded policy; errors classified as permanent are returned immediately.
type RetryPolicy ¶
RetryPolicy controls transport write retries. MaxAttempts includes the first attempt. A value of one disables retries.
type Shard ¶
type Shard struct {
// contains filtered or unexported fields
}
Shard is a fixed-size, lock-protected ring buffer. One byte is deliberately left unused, so a physical capacity of N can store at most N-1 bytes.
type SyncMode ¶
type SyncMode uint8
SyncMode controls whether FileTransport calls fsync after each write.
type TCPTransport ¶
type TCPTransport struct {
// contains filtered or unexported fields
}
TCPTransport writes batches over a persistent TCP connection. Writes have a finite default deadline so Pipeline.Close cannot wait forever on a stalled peer.
func NewTCPTransport ¶
func NewTCPTransport(address string) (*TCPTransport, error)
NewTCPTransport connects to address, limiting connection establishment to five seconds.
func (*TCPTransport) Close ¶
func (t *TCPTransport) Close() error
Close closes the TCP connection once and returns the same close error thereafter.
func (*TCPTransport) WithWriteTimeout ¶
func (t *TCPTransport) WithWriteTimeout(timeout time.Duration) *TCPTransport
WithWriteTimeout sets the deadline for each TCP write. A non-positive value disables the deadline; configure it before concurrent use.
func (*TCPTransport) Write ¶
func (t *TCPTransport) Write(data []byte) error
Write sends all bytes over TCP, handling short writes until complete or error.
type TracedError ¶
type TracedError struct {
// contains filtered or unexported fields
}
TracedError adds context to an existing error while preserving its identity for errors.Is and errors.As.
func (*TracedError) Error ¶
func (e *TracedError) Error() string
func (*TracedError) Unwrap ¶
func (e *TracedError) Unwrap() error
Unwrap exposes the wrapped error to the standard errors package.
type UDPTransport ¶
type UDPTransport struct {
// contains filtered or unexported fields
}
UDPTransport sends each batch as one datagram. The entire batch must fit in a single UDP datagram; callers should use small FlushSize/record sizes.
func NewUDPTransport ¶
func NewUDPTransport(address string) (*UDPTransport, error)
NewUDPTransport connects a UDP socket to address with a bounded dial timeout.
func (*UDPTransport) Close ¶
func (t *UDPTransport) Close() error
Close closes the UDP connection once and returns the same close error thereafter.
func (*UDPTransport) WithWriteTimeout ¶
func (t *UDPTransport) WithWriteTimeout(timeout time.Duration) *UDPTransport
WithWriteTimeout sets the deadline for each UDP datagram write. A non-positive value disables the deadline; configure it before concurrent use.
func (*UDPTransport) Write ¶
func (t *UDPTransport) Write(data []byte) error
Write sends exactly one UDP datagram; it never splits a short write into multiple packets.