Documentation
ΒΆ
Overview ΒΆ
Package fiberlog provides structured logging for Fiber applications with support for console and file outputs, log rotation, color-coding, customizable formats, and more.
Features:
- Structured JSON logging with zerolog
- Console output with optional pretty printing and colors
- File output with rotation and compression
- Non-blocking I/O with diode writer
- Log sampling for high-volume environments
- Request-scoped logging via middleware
- Customizable log formats with templates
- Preset configurations for common scenarios
Index ΒΆ
- Constants
- Variables
- func APIMiddleware(logger *Logger) fiber.Handler
- func ConfigureDefaultLogger(opts ...LoggerOption)
- func ConfigureSonic(config SonicJSONConfig)
- func ConfigureWriterWithSonic(w io.Writer) zerolog.LevelWriter
- func ContextWithLogger(ctx context.Context, logger *zerolog.Logger) context.Context
- func DebugMiddleware(logger *Logger) fiber.Handler
- func GetErrorCategory(err error) string
- func GetErrorCode(err error) string
- func GetHostname() string
- func GraphQLMiddleware(logger *Logger) fiber.Handler
- func IsRecoverable(err error) bool
- func IsSonicAvailable() bool
- func JSONMiddleware(logger *Logger) fiber.Handler
- func MarshalJSON(v interface{}) ([]byte, error)
- func Middleware(logger *Logger, opts ...MiddlewareOption) fiber.Handler
- func MinimalMiddleware(logger *Logger) fiber.Handler
- func NewAdaptiveDiodeWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
- func NewAdaptiveNonBlockingWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
- func NewBatchingWriter(w io.Writer, batchSize int, flushInterval time.Duration) io.WriteCloser
- func NewConfiguredSonicJSONWriter(w io.Writer, cfg SonicWriterConfig) zerolog.LevelWriter
- func NewDiodeWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
- func NewNonBlockingWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
- func NewSonicJSONWriter(w io.Writer) zerolog.LevelWriter
- func RESTfulAPIMiddleware(logger *Logger) fiber.Handler
- func ReleaseData(data *Data)
- func ShutdownDefaultLogger() error
- func StandardMiddleware(logger *Logger) fiber.Handler
- func UnmarshalJSON(data []byte, v interface{}) error
- func WrapError(err error, message string) error
- type AdaptiveNonBlockingMetrics
- type AdaptiveSampler
- type AlertFunc
- type BatchManager
- type BoolValue
- type ContextValue
- type Data
- type DiodeConfig
- type DiodeMetrics
- type DiodeOption
- func WithAdaptiveBuffer(minSize, maxSize int, scaleFactor float64) DiodeOption
- func WithAlertFunction(fn AlertFunc) DiodeOption
- func WithBufferSize(size int) DiodeOption
- func WithDiscard(discard bool) DiodeOption
- func WithPollInterval(interval time.Duration) DiodeOption
- func WithStaticBuffer() DiodeOption
- type ErrorCategory
- type Float64Value
- type FormatType
- type IntValue
- type LogFunc
- type Logger
- func DefaultLogger() *Logger
- func NewAPILogger(serviceName, version string) *Logger
- func NewConsoleLogger(serviceName string, level string) *Logger
- func NewDebugLogger(serviceName string) *Logger
- func NewDevelopmentLogger(serviceName string) *Logger
- func NewHighPerformanceLogger(serviceName, logDir string) *Logger
- func NewHighThroughputLogger(serviceName, logDir string) *Logger
- func NewLogger(options ...LoggerOption) *Logger
- func NewMetricsLogger(serviceName string) *Logger
- func NewMinimalLogger(serviceName string) *Logger
- func NewProductionLogger(serviceName, logDir string) *Logger
- func NewRESTAPILogger(serviceName, version, logDir string) *Logger
- func (l *Logger) Close() error
- func (l *Logger) FromContext(ctx context.Context) *zerolog.Logger
- func (l *Logger) Middleware(opts ...MiddlewareOption) fiber.Handler
- func (l *Logger) ReplaceOutput(w io.Writer)
- func (l *Logger) WithContext(c *fiber.Ctx) *zerolog.Logger
- func (l *Logger) WithField(key string, value interface{}) *Logger
- func (l *Logger) WithFields(fields map[string]interface{}) *Logger
- func (l *Logger) WithSonicJSON() *Logger
- type LoggerConfig
- type LoggerError
- func CloseError(resource string, cause error) *LoggerError
- func DiodeBufferOverflowError(source string, missed int) *LoggerError
- func FileOpenError(filename string, cause error) *LoggerError
- func FormatError(format string, cause error) *LoggerError
- func InvalidConfigError(component string, details string, cause error) *LoggerError
- func MissingDirectoryError(dir string, cause error) *LoggerError
- func NewConfigError(code, message string, cause error) *LoggerError
- func NewDiodeError(code, message string, cause error) *LoggerError
- func NewIOError(code, message string, cause error) *LoggerError
- func NewInternalError(code, message string, cause error) *LoggerError
- func NewLoggerError(category ErrorCategory, code, message string, cause error) *LoggerError
- func NewMiddlewareError(code, message string, cause error) *LoggerError
- func NewTemplateError(code, message string, cause error) *LoggerError
- func TemplateParseError(format string, position int, cause error) *LoggerError
- type LoggerOption
- func WithAlertLogLevel(level zerolog.Level) LoggerOption
- func WithAlertToStderr(enabled bool) LoggerOption
- func WithBoolValue(key string, value bool) LoggerOption
- func WithConsoleOutput(opts ...OutputOption) LoggerOption
- func WithContextValue(key string, value ContextValue) LoggerOption
- func WithFileOutput(opts ...OutputOption) LoggerOption
- func WithFloat64Value(key string, value float64) LoggerOption
- func WithIntValue(key string, value int) LoggerOption
- func WithLevel(level string) LoggerOption
- func WithOutput(outputType OutputType, opts ...OutputOption) LoggerOption
- func WithSampling(opts ...SamplingOption) LoggerOption
- func WithServiceName(name string) LoggerOption
- func WithSonicJSON() LoggerOption
- func WithStringValue(key string, value string) LoggerOption
- func WithTimeValue(key string, value time.Time) LoggerOption
- func WithTypedContext(context map[string]ContextValue) LoggerOption
- type MiddlewareConfig
- type MiddlewareFactory
- type MiddlewareOption
- func WithCustomTag(name string, fn LogFunc) MiddlewareOption
- func WithErrorLogLevel(level zerolog.Level) MiddlewareOption
- func WithHeaderLogging(enable bool, level zerolog.Level, filters []string) MiddlewareOption
- func WithLogLevel(level zerolog.Level) MiddlewareOption
- func WithMiddlewareColors(enable bool) MiddlewareOption
- func WithMiddlewareFormat(format string) MiddlewareOption
- func WithMiddlewareTimeFormat(format string) MiddlewareOption
- func WithMinLatency(minLatency time.Duration) MiddlewareOption
- func WithPooling(enable bool) MiddlewareOption
- func WithPresetFormat(preset string) MiddlewareOption
- func WithRequestBodyLogging(enable bool, maxSize int, level zerolog.Level) MiddlewareOption
- func WithResponseBodyLogging(enable bool, maxSize int, level zerolog.Level) MiddlewareOption
- func WithSkipPaths(paths []string) MiddlewareOption
- func WithTimeInterval(interval time.Duration) MiddlewareOption
- func WithTimeZone(zone string) MiddlewareOption
- type OutputConfig
- type OutputOption
- func WithBatchedWrites(batchSize int, flushInterval time.Duration) OutputOption
- func WithColors(enabled bool) OutputOption
- func WithCompression(enabled bool) OutputOption
- func WithDiode(opts ...DiodeOption) OutputOption
- func WithDirectory(dir string) OutputOption
- func WithFormat(format FormatType) OutputOption
- func WithRotation(maxSizeMB, maxBackups, maxAgeDays int) OutputOption
- func WithTimeFormat(format string) OutputOption
- type OutputType
- type SamplingConfig
- type SamplingOption
- type SonicJSONConfig
- type SonicJSONWriter
- type SonicWriterConfig
- type SonicWriterMetrics
- type StringValue
- type Template
- type TimeValue
Constants ΒΆ
const ( // Basic request information tags TagRequestID = "requestID" // Unique request identifier TagTime = "time" // Formatted timestamp TagReferer = "referer" // HTTP referer header TagProtocol = "protocol" // HTTP protocol version TagPort = "port" // Server port TagIP = "ip" // Client IP address TagIPs = "ips" // X-Forwarded-For header values TagHost = "host" // HTTP host header TagMethod = "method" // HTTP method (GET, POST, etc.) TagPath = "path" // Request URL path TagURL = "url" // Full request URL TagUA = "ua" // User agent string TagLatency = "latency" // Request processing time TagStatus = "status" // HTTP status code // Request and response body tags TagResBody = "resBody" // Response body content TagReqHeaders = "reqHeaders" // All request headers TagQueryStringParams = "queryParams" // URL query parameters TagBody = "body" // Request body content TagBytesSent = "bytesSent" // Response size in bytes TagBytesReceived = "bytesReceived" // Request size in bytes TagRoute = "route" // Matched route pattern TagError = "error" // Error message if any // Header and parameter tags with dynamic parameter TagReqHeader = "reqHeader:" // Single request header TagRespHeader = "respHeader:" // Single response header TagLocals = "locals:" // Fiber context local value TagQuery = "query:" // Single query parameter TagForm = "form:" // Single form parameter TagCookie = "cookie:" // Single cookie value // Color tags TagBlack = "black" // Black ANSI color TagRed = "red" // Red ANSI color TagGreen = "green" // Green ANSI color TagYellow = "yellow" // Yellow ANSI color TagBlue = "blue" // Blue ANSI color TagMagenta = "magenta" // Magenta ANSI color TagCyan = "cyan" // Cyan ANSI color TagWhite = "white" // White ANSI color TagReset = "reset" // Reset ANSI color // Deprecated tags TagHeader = "header:" // Deprecated: Use TagReqHeader instead TagPid = "pid" // Deprecated: Use TagProcessID instead )
Logger variables (tags)
const ( // Version is the current package version Version = "1.0.0" // VersionMajor is the major version component VersionMajor = 1 // VersionMinor is the minor version component VersionMinor = 0 // VersionPatch is the patch version component VersionPatch = 0 )
Version information
const MaxPoolSize = 1000
MaxPoolSize is the maximum number of Data objects to keep in the pool This helps prevent memory leaks by limiting pool growth
Variables ΒΆ
var ( // SimpleFormat is a minimal format with basic request information SimpleFormat = "${time} | ${status} | ${method} ${path}" // DetailedFormat includes more information about the request DetailedFormat = "${time} | ${status} | ${latency} | ${method} ${path} | ${ip} | ${error}" // JsonFormat is a special value that outputs structured JSON JsonFormat = "json" )
Common format presets for middleware
Functions ΒΆ
func APIMiddleware ΒΆ
APIMiddleware returns a middleware configuration optimized for APIs
func ConfigureDefaultLogger ΒΆ
func ConfigureDefaultLogger(opts ...LoggerOption)
ConfigureDefaultLogger sets options for the default logger before it's created. This allows customizing the default logger without changing the singleton pattern.
func ConfigureSonic ΒΆ
func ConfigureSonic(config SonicJSONConfig)
ConfigureSonic configures the global Sonic instance with custom settings
func ConfigureWriterWithSonic ΒΆ
func ConfigureWriterWithSonic(w io.Writer) zerolog.LevelWriter
ConfigureWriterWithSonic wraps an existing writer with Sonic JSON handling This maintains compatibility with the existing API
func ContextWithLogger ΒΆ
ContextWithLogger adds a logger to the context
func DebugMiddleware ΒΆ
DebugMiddleware returns a detailed middleware for debugging
func GetErrorCategory ΒΆ
GetErrorCategory extracts the error category from an error
func GetErrorCode ΒΆ
GetErrorCode extracts the error code from an error
func GetHostname ΒΆ
func GetHostname() string
GetHostname returns the machine hostname or a fallback value. This is useful for adding host information to logs.
func GraphQLMiddleware ΒΆ
GraphQLMiddleware returns a middleware configured for GraphQL APIs
func IsRecoverable ΒΆ
IsRecoverable checks if an error is recoverable
func IsSonicAvailable ΒΆ
func IsSonicAvailable() bool
IsSonicAvailable checks if Sonic's full performance is available on the current platform (with ASM optimizations)
func JSONMiddleware ΒΆ
JSONMiddleware returns a middleware that logs in structured JSON format
func MarshalJSON ΒΆ
MarshalJSON uses Sonic to marshal an object to JSON bytes
func Middleware ΒΆ
func Middleware(logger *Logger, opts ...MiddlewareOption) fiber.Handler
Middleware creates a Fiber middleware that logs requests using the provided logger.
func MinimalMiddleware ΒΆ
MinimalMiddleware returns a middleware with minimal overhead
func NewAdaptiveDiodeWriter ΒΆ
func NewAdaptiveDiodeWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
NewAdaptiveDiodeWriter provides backward compatibility Deprecated: Use NewAdaptiveNonBlockingWriter instead
func NewAdaptiveNonBlockingWriter ΒΆ
func NewAdaptiveNonBlockingWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
NewAdaptiveNonBlockingWriter creates a writer with automatic buffer sizing
func NewBatchingWriter ΒΆ
NewBatchingWriter creates a new writer that batches writes to improve performance
func NewConfiguredSonicJSONWriter ΒΆ
func NewConfiguredSonicJSONWriter(w io.Writer, cfg SonicWriterConfig) zerolog.LevelWriter
NewConfiguredSonicJSONWriter creates a new writer with custom configuration
func NewDiodeWriter ΒΆ
func NewDiodeWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
NewDiodeWriter provides backward compatibility Deprecated: Use NewNonBlockingWriter instead
func NewNonBlockingWriter ΒΆ
func NewNonBlockingWriter(w io.Writer, cfg *DiodeConfig) io.WriteCloser
NewNonBlockingWriter creates a writer with configurable buffer parameters. By default, it uses adaptive buffer sizing for optimal performance.
func NewSonicJSONWriter ΒΆ
func NewSonicJSONWriter(w io.Writer) zerolog.LevelWriter
NewSonicJSONWriter creates a new writer that uses Sonic for JSON serialization with default configuration
func RESTfulAPIMiddleware ΒΆ
RESTfulAPIMiddleware returns a middleware configured for RESTful APIs
func ReleaseData ΒΆ
func ReleaseData(data *Data)
ReleaseData returns a Data object to the pool after clearing its fields. It's safe to call this multiple times or with nil.
func ShutdownDefaultLogger ΒΆ
func ShutdownDefaultLogger() error
ShutdownDefaultLogger ensures the default logger is properly closed. This should be called during application shutdown to release resources.
func StandardMiddleware ΒΆ
StandardMiddleware returns a standard middleware configuration for web applications
func UnmarshalJSON ΒΆ
UnmarshalJSON uses Sonic to unmarshal JSON bytes to an object
Types ΒΆ
type AdaptiveNonBlockingMetrics ΒΆ
type AdaptiveNonBlockingMetrics struct {
DiodeMetrics
MinSize int
MaxSize int
CurrentSize int
ResizeCount int64
LastResize time.Time
LoadAverage int64
}
AdaptiveNonBlockingMetrics provides extended performance statistics
type AdaptiveSampler ΒΆ
type AdaptiveSampler struct {
// contains filtered or unexported fields
}
AdaptiveSampler implements zerolog.Sampler with adaptive rate adjustment
type AlertFunc ΒΆ
AlertFunc defines a function that is called when alerts occur (e.g., buffer overflow)
type BatchManager ΒΆ
type BatchManager struct {
// contains filtered or unexported fields
}
BatchManager manages batches of Data objects for analytics
func NewBatchManager ΒΆ
func NewBatchManager(batchSize int, interval time.Duration, flushFn func([]*Data)) *BatchManager
NewBatchManager creates a new batch manager for processing Data in batches
func (*BatchManager) Add ΒΆ
func (bm *BatchManager) Add(data *Data)
Add adds a Data object to the batch
func (*BatchManager) Flush ΒΆ
func (bm *BatchManager) Flush()
Flush manually flushes the current batch
type ContextValue ΒΆ
type ContextValue interface {
// AsZerologField adds this value to a zerolog Context
AsZerologField(e *zerolog.Context, key string)
}
ContextValue represents a value that can be safely serialized
type Data ΒΆ
type Data struct {
RequestID string // Unique request identifier
ChainErr error // Error from the middleware chain
Start time.Time // Request start time
Stop time.Time // Request completion time
Timestamp atomic.Value // Current formatted timestamp (updated periodically)
Latency time.Duration // Request processing duration
StatusCode int // HTTP status code
BytesSent int // Response body size
BytesReceived int // Request body size
// Optional fields that may be populated based on usage
Path string // Request path (optional cache)
Method string // HTTP method (optional cache)
QueryString string // Query string (optional cache)
IP string // Client IP (optional cache)
// contains filtered or unexported fields
}
Data holds request-specific data for logging. It's designed to be reused through a sync.Pool to reduce allocations.
func AcquireData ΒΆ
func AcquireData() *Data
AcquireData gets a Data object from the pool and initializes it. The returned object should be released with ReleaseData when no longer needed.
func (*Data) CalculateLatency ΒΆ
func (d *Data) CalculateLatency()
CalculateLatency computes and sets the latency between start and stop times.
func (*Data) Clone ΒΆ
Clone creates a copy of the Data that can be used independently. This is useful when the Data needs to persist beyond the request lifecycle.
func (*Data) GetDurationMs ΒΆ
GetDurationMs returns the latency in milliseconds.
func (*Data) GetTimestamp ΒΆ
GetTimestamp returns the stored timestamp value.
func (*Data) IsReleased ΒΆ
IsReleased returns whether this Data object has been released.
func (*Data) SetTimestamp ΒΆ
SetTimestamp is a helper to set the timestamp atomic value.
type DiodeConfig ΒΆ
type DiodeConfig struct {
BufferSize int
PollInterval time.Duration
Discard bool
AlertFn AlertFunc
Adaptive bool
MinSize int
MaxSize int
ScaleFactor float64
DropThresh int64 // Threshold for drops triggering resize
UtilLow float64 // Low utilization threshold for downsizing
UtilHigh float64 // High utilization threshold (optional)
}
DiodeConfig represents configuration for a diode (non-blocking) writer
type DiodeMetrics ΒΆ
type DiodeMetrics struct {
DroppedMessages int64
WrittenMessages int64
BytesWritten int64
BufferSize int
FlushCount int64
}
DiodeMetrics contains writer performance statistics
type DiodeOption ΒΆ
type DiodeOption func(*DiodeConfig)
DiodeOption defines a function that configures diode settings
func WithAdaptiveBuffer ΒΆ
func WithAdaptiveBuffer(minSize, maxSize int, scaleFactor float64) DiodeOption
WithAdaptiveBuffer enables automatic buffer resizing based on traffic patterns
func WithAlertFunction ΒΆ
func WithAlertFunction(fn AlertFunc) DiodeOption
WithAlertFunction sets a custom function to call when messages are dropped
func WithBufferSize ΒΆ
func WithBufferSize(size int) DiodeOption
WithBufferSize sets the diode buffer size
func WithDiscard ΒΆ
func WithDiscard(discard bool) DiodeOption
WithDiscard configures whether to discard messages when buffer is full
func WithPollInterval ΒΆ
func WithPollInterval(interval time.Duration) DiodeOption
WithPollInterval sets the diode polling interval
func WithStaticBuffer ΒΆ
func WithStaticBuffer() DiodeOption
WithStaticBuffer creates a diode option to disable adaptive sizing
type ErrorCategory ΒΆ
type ErrorCategory string
ErrorCategory defines the general category of an error
const ( ErrCategoryConfiguration ErrorCategory = "configuration" // Configuration-related errors ErrCategoryIO ErrorCategory = "io" // I/O operation errors ErrCategoryTemplate ErrorCategory = "template" // Template parsing/execution errors ErrCategoryMiddleware ErrorCategory = "middleware" // Middleware-related errors ErrCategoryDiode ErrorCategory = "diode" // Diode buffer errors ErrCategoryInternal ErrorCategory = "internal" // Internal library errors ErrCategoryExternal ErrorCategory = "external" // External dependency errors )
Standard error categories for better organization
type Float64Value ΒΆ
type Float64Value float64
Float64Value is a float64 context value
func (Float64Value) AsZerologField ΒΆ
func (f Float64Value) AsZerologField(e *zerolog.Context, key string)
type FormatType ΒΆ
type FormatType string
FormatType defines the output format for logging
const ( // FormatJSON outputs logs in JSON format FormatJSON FormatType = "json" // FormatPretty outputs logs in human-readable format FormatPretty FormatType = "pretty" )
type LogFunc ΒΆ
type LogFunc func(*bytebufferpool.ByteBuffer, *fiber.Ctx, *Data, string) (int, error)
LogFunc defines a function to generate custom log values for middleware.
type Logger ΒΆ
type Logger struct {
*zerolog.Logger // Embedded zerolog.Logger for direct access to logging methods
// contains filtered or unexported fields
}
Logger is a wrapper around zerolog.Logger with additional methods and resource management.
func DefaultLogger ΒΆ
func DefaultLogger() *Logger
DefaultLogger returns a global default logger instance. The logger is created with the configured options or sensible defaults.
func NewAPILogger ΒΆ
NewAPILogger creates a logger optimized for API services with request tracing and context information.
Features: - Trace level logging for detailed diagnostics - Request ID tracking - Service and version context
func NewConsoleLogger ΒΆ
NewConsoleLogger creates a simple console logger optimized for local development
func NewDebugLogger ΒΆ
NewDebugLogger creates a logger optimized for debugging with detailed output
func NewDevelopmentLogger ΒΆ
NewDevelopmentLogger creates a logger optimized for development environments with pretty console output and detailed logging.
Features: - Console output with pretty formatting and colors - Debug level logging - No file output (console only) - Synchronous logging (no diode buffer) NewDevelopmentLogger creates a logger optimized for development environments
func NewHighPerformanceLogger ΒΆ
NewHighPerformanceLogger creates a logger optimized for high-throughput environments with sampling, non-blocking writes, and minimal overhead.
Features: - JSON output (faster than pretty printing) - Sampling to reduce log volume - Large diode buffers for non-blocking writes - Batched file writes - Adaptive diode sizing
func NewHighThroughputLogger ΒΆ
NewHighThroughputLogger creates a logger optimized for extremely high throughput
func NewLogger ΒΆ
func NewLogger(options ...LoggerOption) *Logger
NewLogger creates a new Logger instance based on the provided options. The logger must be closed with logger.Close() when no longer needed.
Example:
logger := fiberlog.NewLogger(
fiberlog.WithServiceName("api-service"),
fiberlog.WithConsoleOutput(
fiberlog.WithFormat(fiberlog.FormatPretty),
fiberlog.WithColors(true),
),
fiberlog.WithStringLevel("debug"),
)
defer logger.Close()
func NewMetricsLogger ΒΆ
NewMetricsLogger creates a logger designed for metrics collection with a focus on machine-readable output and performance.
Features: - JSON output for machine readability - Non-blocking writes with large buffer - Context fields for common metrics
func NewMinimalLogger ΒΆ
NewMinimalLogger creates a simple, minimal logger for basic use cases with no special features.
Features: - Console output only - No special configuration - Synchronous logging
func NewProductionLogger ΒΆ
NewProductionLogger creates a logger optimized for production environments with file output, rotation, and appropriate log levels.
Features: - Console output with JSON formatting (no colors) - File output with JSON formatting and compression - Info level logging - File rotation and compression - Non-blocking I/O with diode writer
func NewRESTAPILogger ΒΆ
NewRESTAPILogger creates a logger optimized for REST API services
func (*Logger) FromContext ΒΆ
FromContext extracts a logger from the context or returns the default
func (*Logger) Middleware ΒΆ
func (l *Logger) Middleware(opts ...MiddlewareOption) fiber.Handler
Middleware creates a Fiber middleware that logs requests using this logger
func (*Logger) ReplaceOutput ΒΆ
ReplaceOutput replaces all output writers with a new one, properly handling diode and other writer transformations
func (*Logger) WithContext ΒΆ
WithContext creates a child logger with request context from a Fiber context
func (*Logger) WithFields ΒΆ
WithFields adds multiple fields to the logger instance
func (*Logger) WithSonicJSON ΒΆ
WithSonicJSON configures the logger to use Sonic for JSON serialization
type LoggerConfig ΒΆ
type LoggerConfig struct {
// Core settings
ServiceName string // Name of the service used in logs and filename
Level zerolog.Level // Log level threshold
TypedContext map[string]ContextValue // Typed context for better serialization
UseSonicJSON bool // Use Bytedance Sonic for faster JSON processing
// Output configurations
Outputs map[OutputType]*OutputConfig // Configurations for different output types
// Sampling settings
Sampling *SamplingConfig // Sampling configuration, nil if disabled
// Alert settings
AlertLogLevel zerolog.Level // Log level for alerts
AlertToStderr bool // Whether to also write alerts to stderr
}
LoggerConfig represents the core configuration for a logger instance.
func NewLoggerConfig ΒΆ
func NewLoggerConfig() LoggerConfig
NewLoggerConfig creates a LoggerConfig with sensible default values. These defaults are optimized for development environments. NewLoggerConfig creates a LoggerConfig with sensible default values.
type LoggerError ΒΆ
type LoggerError struct {
Category ErrorCategory // Error category for grouping
Code string // Error code for programmatic identification
Message string // Human-readable error message
Cause error // Underlying error that caused this one
Timestamp time.Time // When the error occurred
Recoverable bool // Whether the error is recoverable
Context map[string]interface{} // Additional context for debugging
}
LoggerError provides structured error information with context
func CloseError ΒΆ
func CloseError(resource string, cause error) *LoggerError
CloseError creates a standardized error for resource closing issues
func DiodeBufferOverflowError ΒΆ
func DiodeBufferOverflowError(source string, missed int) *LoggerError
DiodeBufferOverflowError creates a standardized error for diode buffer overflow
func FileOpenError ΒΆ
func FileOpenError(filename string, cause error) *LoggerError
FileOpenError creates a standardized error for file access issues
func FormatError ΒΆ
func FormatError(format string, cause error) *LoggerError
FormatError creates a standardized error for format-related issues
func InvalidConfigError ΒΆ
func InvalidConfigError(component string, details string, cause error) *LoggerError
InvalidConfigError creates a standardized error for invalid configuration
func MissingDirectoryError ΒΆ
func MissingDirectoryError(dir string, cause error) *LoggerError
MissingDirectoryError creates a standardized error for missing directories
func NewConfigError ΒΆ
func NewConfigError(code, message string, cause error) *LoggerError
NewConfigError creates an error related to configuration
func NewDiodeError ΒΆ
func NewDiodeError(code, message string, cause error) *LoggerError
NewDiodeError creates an error related to diode operations
func NewIOError ΒΆ
func NewIOError(code, message string, cause error) *LoggerError
NewIOError creates an error related to I/O operations
func NewInternalError ΒΆ
func NewInternalError(code, message string, cause error) *LoggerError
NewInternalError creates an error related to internal operations
func NewLoggerError ΒΆ
func NewLoggerError(category ErrorCategory, code, message string, cause error) *LoggerError
NewLoggerError creates a new standardized error with the given attributes
func NewMiddlewareError ΒΆ
func NewMiddlewareError(code, message string, cause error) *LoggerError
NewMiddlewareError creates an error related to middleware
func NewTemplateError ΒΆ
func NewTemplateError(code, message string, cause error) *LoggerError
NewTemplateError creates an error related to templates
func TemplateParseError ΒΆ
func TemplateParseError(format string, position int, cause error) *LoggerError
TemplateParseError creates a standardized error for template parsing issues
func (*LoggerError) Error ΒΆ
func (e *LoggerError) Error() string
Error implements the error interface
func (*LoggerError) Unwrap ΒΆ
func (e *LoggerError) Unwrap() error
Unwrap implements error unwrapping for compatibility with errors.Is/As
func (*LoggerError) WithContext ΒΆ
func (e *LoggerError) WithContext(key string, value interface{}) *LoggerError
WithContext adds context information to the error
func (*LoggerError) WithRecoverable ΒΆ
func (e *LoggerError) WithRecoverable(recoverable bool) *LoggerError
WithRecoverable sets whether the error is recoverable
type LoggerOption ΒΆ
type LoggerOption func(*LoggerConfig)
LoggerOption defines a function that configures a LoggerConfig.
func WithAlertLogLevel ΒΆ
func WithAlertLogLevel(level zerolog.Level) LoggerOption
WithAlertLogLevel sets the log level for alert messages
func WithAlertToStderr ΒΆ
func WithAlertToStderr(enabled bool) LoggerOption
WithAlertToStderr controls whether alert messages are also written to stderr
func WithBoolValue ΒΆ
func WithBoolValue(key string, value bool) LoggerOption
WithBoolValue adds a boolean value to the global context.
func WithConsoleOutput ΒΆ
func WithConsoleOutput(opts ...OutputOption) LoggerOption
WithConsoleOutput is a convenience function for WithOutput(ConsoleOutput, ...)
func WithContextValue ΒΆ
func WithContextValue(key string, value ContextValue) LoggerOption
WithContextValue adds a single typed key-value pair to the global context.
func WithFileOutput ΒΆ
func WithFileOutput(opts ...OutputOption) LoggerOption
WithFileOutput is a convenience function for WithOutput(FileOutput, ...)
func WithFloat64Value ΒΆ
func WithFloat64Value(key string, value float64) LoggerOption
WithFloat64Value adds a float64 value to the global context.
func WithIntValue ΒΆ
func WithIntValue(key string, value int) LoggerOption
WithIntValue adds an integer value to the global context.
func WithLevel ΒΆ
func WithLevel(level string) LoggerOption
WithStringLevel sets the minimum log level as a string (e.g., "debug", "info").
func WithOutput ΒΆ
func WithOutput(outputType OutputType, opts ...OutputOption) LoggerOption
WithOutput configures a specific output type with the provided options.
func WithSampling ΒΆ
func WithSampling(opts ...SamplingOption) LoggerOption
WithSampling enables log sampling with custom settings
func WithServiceName ΒΆ
func WithServiceName(name string) LoggerOption
WithServiceName sets the service name, used in logs and filename construction.
func WithSonicJSON ΒΆ
func WithSonicJSON() LoggerOption
WithSonicJSON enables Bytedance Sonic for faster JSON processing.
func WithStringValue ΒΆ
func WithStringValue(key string, value string) LoggerOption
WithStringValue adds a string value to the global context.
func WithTimeValue ΒΆ
func WithTimeValue(key string, value time.Time) LoggerOption
WithTimeValue adds a time.Time value to the global context.
func WithTypedContext ΒΆ
func WithTypedContext(context map[string]ContextValue) LoggerOption
WithTypedContext adds global typed key-value pairs to all log entries.
type MiddlewareConfig ΒΆ
type MiddlewareConfig struct {
// Core configuration
Format string // Log format string with tags
TimeFormat string // Time format for middleware logs
TimeZone string // Time zone for middleware timestamps
TimeInterval time.Duration // Interval for updating timestamps
EnableColors bool // Enable colored output in middleware logs
SkipPaths []string // Paths to skip logging
// Log levels
LogLevel zerolog.Level // Log level to use for normal requests
ErrorLogLevel zerolog.Level // Log level to use for error requests
// Custom tags and extensions
CustomTags map[string]LogFunc // Custom tag functions for middleware
// Performance settings
UsePooling bool // Use object pooling for better performance
MinLatency time.Duration // Only log requests with latency above this threshold
// Request body handling
LogRequestBody bool // Whether to log request bodies
MaxRequestBodySize int // Maximum request body size to log
RequestBodyLogLevel zerolog.Level // Level to log request bodies at
// Response body handling
LogResponseBody bool // Whether to log response bodies
MaxResponseBodySize int // Maximum response body size to log
ResponseBodyLogLevel zerolog.Level // Level to log response bodies at
// Request/Response header handling
LogHeaders bool // Whether to log headers
HeadersLogLevel zerolog.Level // Level to log headers at
HeadersFilter []string // Headers to include or exclude (prefixed with + or -)
}
MiddlewareConfig defines settings for the Fiber middleware logger.
func NewMiddlewareConfig ΒΆ
func NewMiddlewareConfig() MiddlewareConfig
NewMiddlewareConfig creates a MiddlewareConfig with default values.
type MiddlewareFactory ΒΆ
type MiddlewareFactory struct {
// contains filtered or unexported fields
}
MiddlewareFactory produces various middleware configurations
func NewFactory ΒΆ
func NewFactory(logger *Logger) *MiddlewareFactory
NewFactory creates a middleware factory for the given logger
func NewMiddlewareFactory ΒΆ
func NewMiddlewareFactory(logger *Logger) *MiddlewareFactory
NewMiddlewareFactory creates a factory for middleware configurations
func (*MiddlewareFactory) API ΒΆ
func (f *MiddlewareFactory) API() fiber.Handler
API returns a middleware configuration optimized for APIs
func (*MiddlewareFactory) Custom ΒΆ
func (f *MiddlewareFactory) Custom(opts ...MiddlewareOption) fiber.Handler
Custom creates a middleware with the given options
func (*MiddlewareFactory) Debug ΒΆ
func (f *MiddlewareFactory) Debug() fiber.Handler
Debug returns a comprehensive middleware for debugging
func (*MiddlewareFactory) Minimal ΒΆ
func (f *MiddlewareFactory) Minimal() fiber.Handler
Minimal returns a minimal middleware configuration for high-performance scenarios
func (*MiddlewareFactory) Standard ΒΆ
func (f *MiddlewareFactory) Standard() fiber.Handler
Standard returns a standard middleware configuration for web applications
type MiddlewareOption ΒΆ
type MiddlewareOption func(*MiddlewareConfig)
MiddlewareOption defines a function that modifies MiddlewareConfig.
func WithCustomTag ΒΆ
func WithCustomTag(name string, fn LogFunc) MiddlewareOption
WithCustomTag adds a custom tag function to the middleware.
func WithErrorLogLevel ΒΆ
func WithErrorLogLevel(level zerolog.Level) MiddlewareOption
WithErrorLogLevel sets the log level for error requests.
func WithHeaderLogging ΒΆ
func WithHeaderLogging(enable bool, level zerolog.Level, filters []string) MiddlewareOption
WithHeaderLogging configures header logging.
func WithLogLevel ΒΆ
func WithLogLevel(level zerolog.Level) MiddlewareOption
WithLogLevel sets the log level for normal requests.
func WithMiddlewareColors ΒΆ
func WithMiddlewareColors(enable bool) MiddlewareOption
WithMiddlewareColors enables/disables colors in middleware logs.
func WithMiddlewareFormat ΒΆ
func WithMiddlewareFormat(format string) MiddlewareOption
WithFormat sets the log format for the middleware.
func WithMiddlewareTimeFormat ΒΆ
func WithMiddlewareTimeFormat(format string) MiddlewareOption
WithMiddlewareTimeFormat sets the time format for the middleware.
func WithMinLatency ΒΆ
func WithMinLatency(minLatency time.Duration) MiddlewareOption
WithMinLatency sets the minimum latency threshold for logging requests.
func WithPooling ΒΆ
func WithPooling(enable bool) MiddlewareOption
WithPooling enables or disables object pooling for better performance.
func WithPresetFormat ΒΆ
func WithPresetFormat(preset string) MiddlewareOption
WithPresetFormat sets a middleware format to a predefined preset. This simplifies configuration for common use cases.
func WithRequestBodyLogging ΒΆ
func WithRequestBodyLogging(enable bool, maxSize int, level zerolog.Level) MiddlewareOption
WithRequestBodyLogging configures request body logging.
func WithResponseBodyLogging ΒΆ
func WithResponseBodyLogging(enable bool, maxSize int, level zerolog.Level) MiddlewareOption
WithResponseBodyLogging configures response body logging.
func WithSkipPaths ΒΆ
func WithSkipPaths(paths []string) MiddlewareOption
WithSkipPaths sets paths to skip logging.
func WithTimeInterval ΒΆ
func WithTimeInterval(interval time.Duration) MiddlewareOption
WithTimeInterval sets the interval for updating timestamps.
func WithTimeZone ΒΆ
func WithTimeZone(zone string) MiddlewareOption
WithTimeZone sets the time zone for the middleware.
type OutputConfig ΒΆ
type OutputConfig struct {
Enabled bool // Whether this output is enabled
Format FormatType // Format type for this output (json or pretty)
TimeFormat string // Timestamp format for this output
// Console-specific settings
Colors bool // Whether to use colors (console only)
// File-specific settings
Directory string // Directory for log files (file only)
MaxSizeMB int // Maximum file size in megabytes before rotation (file only)
MaxBackups int // Maximum number of backup files to keep (file only)
MaxAgeDays int // Maximum age of backup files in days (file only)
Compression bool // Whether to compress rotated log files (file only)
// Batching settings (file only)
BatchEnabled bool // Enable batched writes
BatchSize int // Buffer size in bytes before flushing
BatchInterval time.Duration // Maximum time between flushes
// Diode (non-blocking) configuration
Diode *DiodeConfig // Diode configuration, nil if disabled
}
OutputConfig represents configuration for a specific output target
type OutputOption ΒΆ
type OutputOption func(*OutputConfig)
OutputOption defines a function that configures output-specific settings
func WithBatchedWrites ΒΆ
func WithBatchedWrites(batchSize int, flushInterval time.Duration) OutputOption
WithBatchedWrites enables batched writes for file output with custom settings
func WithColors ΒΆ
func WithColors(enabled bool) OutputOption
WithColors enables or disables colored output for console logging
func WithCompression ΒΆ
func WithCompression(enabled bool) OutputOption
WithCompression enables compression for rotated log files
func WithDiode ΒΆ
func WithDiode(opts ...DiodeOption) OutputOption
WithDiode enables non-blocking writes with a diode buffer
func WithDirectory ΒΆ
func WithDirectory(dir string) OutputOption
WithDirectory sets the directory where log files are stored
func WithFormat ΒΆ
func WithFormat(format FormatType) OutputOption
WithFormat sets the output format (JSON or pretty)
func WithRotation ΒΆ
func WithRotation(maxSizeMB, maxBackups, maxAgeDays int) OutputOption
WithRotation configures log file rotation settings
func WithTimeFormat ΒΆ
func WithTimeFormat(format string) OutputOption
WithTimeFormat sets the timestamp format (e.g., time.RFC3339)
type OutputType ΒΆ
type OutputType string
OutputType defines the type of output target
const ( // ConsoleOutput for logging to console (stdout) ConsoleOutput OutputType = "console" // FileOutput for logging to files with rotation FileOutput OutputType = "file" )
type SamplingConfig ΒΆ
type SamplingConfig struct {
Burst uint32 // Initial burst size before sampling kicks in
Period time.Duration // Time period for sampling
Rates map[string]uint32 // Sampling rates per log level
Adaptive bool // Whether to use adaptive sampling
LoadThreshold float64 // System load threshold for adaptive sampling
}
SamplingConfig represents configuration for log sampling
type SamplingOption ΒΆ
type SamplingOption func(*SamplingConfig)
SamplingOption defines a function that configures sampling settings
func WithAdaptiveSampling ΒΆ
func WithAdaptiveSampling(loadThreshold float64) SamplingOption
WithAdaptiveSampling enables automatic adjustment of sampling rates based on system load (requires monitoring integration)
func WithSamplingBurst ΒΆ
func WithSamplingBurst(size uint32) SamplingOption
WithSamplingBurst sets the initial burst size before sampling kicks in
func WithSamplingPeriod ΒΆ
func WithSamplingPeriod(period time.Duration) SamplingOption
WithSamplingPeriod sets the time period for sampling
func WithSamplingRate ΒΆ
func WithSamplingRate(level string, rate uint32) SamplingOption
WithSamplingRate sets the sampling rate for a specific log level
type SonicJSONConfig ΒΆ
type SonicJSONConfig struct {
CompactMarshaler bool
EscapeHTML bool
NoQuoteTextMarshaler bool
SortMapKeys bool
}
For backwards compatibility
func DefaultSonicConfig ΒΆ
func DefaultSonicConfig() SonicJSONConfig
DefaultSonicConfig returns the default configuration (for backward compatibility)
type SonicJSONWriter ΒΆ
type SonicJSONWriter struct {
// contains filtered or unexported fields
}
SonicJSONWriter is an optimized writer that uses Bytedance Sonic for high-performance JSON serialization
func (*SonicJSONWriter) Close ΒΆ
func (w *SonicJSONWriter) Close() error
Close flushes any buffered data and releases resources
func (*SonicJSONWriter) Flush ΒΆ
func (w *SonicJSONWriter) Flush() error
Flush writes any buffered data to the underlying writer
func (*SonicJSONWriter) GetMetrics ΒΆ
func (w *SonicJSONWriter) GetMetrics() SonicWriterMetrics
GetMetrics returns performance statistics if metrics are enabled
func (*SonicJSONWriter) Write ΒΆ
func (w *SonicJSONWriter) Write(p []byte) (n int, err error)
Write implements the io.Writer interface with optimized performance
func (*SonicJSONWriter) WriteLevel ΒΆ
WriteLevel implements zerolog.LevelWriter interface
type SonicWriterConfig ΒΆ
type SonicWriterConfig struct {
// EnableMetrics determines whether to collect performance metrics
EnableMetrics bool
// BufferSize determines the size of the write buffer (0 disables buffering)
BufferSize int
// FlushInterval is the maximum time between flushes when buffering is enabled
FlushInterval time.Duration
// SortMapKeys determines whether to sort JSON map keys
SortMapKeys bool
// EscapeHTML determines whether to escape HTML characters
EscapeHTML bool
// CompactOutput determines whether to produce compact JSON output
CompactOutput bool
}
SonicWriterConfig holds configuration for the Sonic JSON writer
func DefaultSonicWriterConfig ΒΆ
func DefaultSonicWriterConfig() SonicWriterConfig
DefaultSonicWriterConfig returns the default configuration for Sonic writer
type SonicWriterMetrics ΒΆ
type SonicWriterMetrics struct {
BytesWritten int64
WriteCount int64
ErrorCount int64
FlushCount int64
}
SonicWriterMetrics contains performance statistics
type StringValue ΒΆ
type StringValue string
StringValue is a simple string context value
func (StringValue) AsZerologField ΒΆ
func (s StringValue) AsZerologField(e *zerolog.Context, key string)
type Template ΒΆ
type Template struct {
// contains filtered or unexported fields
}
Template represents a log format template parser and executor.
func NewTemplate ΒΆ
func NewTemplate(cfg MiddlewareConfig) *Template
NewTemplate creates a new template with the given configuration. It immediately parses the format for better performance.
func (*Template) Execute ΒΆ
func (t *Template) Execute(buf *bytebufferpool.ByteBuffer, c *fiber.Ctx, data *Data) (err error)
Execute processes the template against the given context and data.