fiberlog

package module
v0.0.0-...-77e2280 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2025 License: MIT Imports: 21 Imported by: 0

README ΒΆ

πŸš€ FiberLog

Go Reference Go Report Card Coverage Status License Version

High-Performance Structured Logging for Fiber Applications

πŸ“‹ Overview

FiberLog is a feature-rich, high-performance structured logging package specifically designed for Fiber applications. Built on top of zerolog, it provides significant performance optimizations and developer-friendly features that make logging both efficient and powerful.

✨ Features

  • πŸ“Š Structured JSON Logging: Leverages zerolog's structured logging approach.
  • 🌈 Multiple Output Formats: Console output with pretty printing and colors or JSON for machine readability.
  • πŸ“ File Output with Rotation: Log to files with automatic rotation, compression, and retention policies.
  • ⚑ Non-Blocking I/O: Super-fast logging with diode buffer that doesn't slow down your application.
  • 🧠 Adaptive Buffer Sizing: Automatically adjusts buffer sizes based on traffic patterns.
  • πŸ” Request-Scoped Logging: Comprehensive middleware for HTTP request logging.
  • 🎯 Log Sampling: Configurable sampling for high-volume environments.
  • πŸ”§ Highly Configurable: Flexible options for customizing every aspect of logging.
  • πŸ“¦ Presets for Common Scenarios: Ready-to-use configurations for development, production, and other environments.
  • πŸš„ Bytedance Sonic Integration: Optional ultra-fast JSON serialization.

πŸ“ˆ Performance

FiberLog is designed to be extremely fast. Recent benchmarks show:

  • 17M+ operations/second with optimized configurations
  • 2.7x faster for simple data vs complex structured data
  • 1.4x faster with Sonic JSON vs standard encoding/json
  • 2.1x faster with non-blocking writers
  • 2.7x faster with adaptive buffer sizing

Performance Chart

πŸ› οΈ Installation

go get github.com/abdel-issaoui/fiberlog

πŸš€ Quick Start

package main

import (
	"github.com/abdel-issaoui/fiberlog"
	"github.com/gofiber/fiber/v2"
)

func main() {
	// Create a new logger with development preset
	logger := fiberlog.NewDevelopmentLogger("my-service")
	defer logger.Close()

	// Create a Fiber app with logger middleware
	app := fiber.New()
	app.Use(logger.Middleware())

	// Add a simple route
	app.Get("/", func(c *fiber.Ctx) error {
		// Get logger from context
		log := c.Locals("logger").(*zerolog.Logger)
		log.Info().Msg("Hello world request received")

		return c.SendString("Hello, World!")
	})

	app.Listen(":3000")
}

βš™οΈ Configuration

FiberLog uses a flexible functional options pattern for configuration:

// Create a production-ready logger with file output
logger := fiberlog.NewLogger(
	fiberlog.WithServiceName("api-service"),
	fiberlog.WithLevel("info"),
	fiberlog.WithConsoleOutput(
		fiberlog.WithFormat(fiberlog.FormatJSON),
		fiberlog.WithColors(false),
	),
	fiberlog.WithFileOutput(
		fiberlog.WithDirectory("./logs"),
		fiberlog.WithRotation(100, 10, 30), // 100MB, 10 backups, 30 days
		fiberlog.WithCompression(true),
		fiberlog.WithDiode(
			fiberlog.WithBufferSize(50000),
			fiberlog.WithDiscard(true),
			fiberlog.WithAdaptiveBuffer(5000, 100000, 1.5),
		),
	),
	fiberlog.WithSonicJSON(),
)
defer logger.Close()
Presets

FiberLog comes with ready-to-use presets for common scenarios:

// Development preset - pretty console output, debug level
logger := fiberlog.NewDevelopmentLogger("my-service")

// Production preset - file output with rotation, info level
logger := fiberlog.NewProductionLogger("my-service", "./logs")

// High-performance preset - optimized for throughput
logger := fiberlog.NewHighPerformanceLogger("my-service", "./logs")

// Minimal preset - basic configuration
logger := fiberlog.NewMinimalLogger("my-service")

🌐 Middleware Usage

FiberLog provides powerful middleware for HTTP request logging:

// Basic middleware
app.Use(logger.Middleware())

// Customized middleware
app.Use(logger.Middleware(
	fiberlog.WithMiddlewareFormat("${time} | ${status} | ${latency} | ${method} ${path} | ${ip} | ${error}"),
	fiberlog.WithLogLevel(zerolog.InfoLevel),
	fiberlog.WithErrorLogLevel(zerolog.ErrorLevel),
	fiberlog.WithHeaderLogging(true, zerolog.DebugLevel, []string{
		"-Authorization", // Exclude Authorization header
		"-Cookie",        // Exclude Cookie header
		"+Content-Type",  // Include Content-Type header
		"+Accept",        // Include Accept header
	}),
	fiberlog.WithRequestBodyLogging(true, 4096, zerolog.DebugLevel),
))

// Middleware presets
app.Use(fiberlog.StandardMiddleware(logger))  // Standard web app logging
app.Use(fiberlog.APIMiddleware(logger))       // API-optimized logging
app.Use(fiberlog.RESTfulAPIMiddleware(logger)) // RESTful API logging
app.Use(fiberlog.GraphQLMiddleware(logger))   // GraphQL-specific logging
app.Use(fiberlog.DebugMiddleware(logger))     // Detailed debug information

πŸ“Š Performance Optimization

Based on benchmark results, here are recommended configurations for different scenarios:

For Highest Throughput
logger := fiberlog.NewLogger(
	fiberlog.WithServiceName("high-throughput-service"),
	fiberlog.WithLevel("info"),
	fiberlog.WithSonicJSON(),
	fiberlog.WithSampling(
		fiberlog.WithSamplingBurst(1000),
		fiberlog.WithSamplingRate("info", 5),
	),
	fiberlog.WithConsoleOutput(
		fiberlog.WithFormat(fiberlog.FormatJSON),
		fiberlog.WithDiode(
			fiberlog.WithBufferSize(100000),
			fiberlog.WithDiscard(true),
			fiberlog.WithAdaptiveBuffer(10000, 500000, 2.0),
		),
	),
)
For Minimal Allocations
logger := fiberlog.NewLogger(
	fiberlog.WithServiceName("low-alloc-service"),
	fiberlog.WithLevel("info"),
	fiberlog.WithSonicJSON(),
	fiberlog.WithConsoleOutput(
		fiberlog.WithFormat(fiberlog.FormatJSON),
		fiberlog.WithDiode(
			fiberlog.WithBufferSize(10000),
			fiberlog.WithDiscard(true),
		),
	),
)
For File Logging
logger := fiberlog.NewLogger(
	fiberlog.WithServiceName("file-logging-service"),
	fiberlog.WithLevel("info"),
	fiberlog.WithSonicJSON(),
	fiberlog.WithFileOutput(
		fiberlog.WithDirectory("./logs"),
		fiberlog.WithFormat(fiberlog.FormatJSON),
		fiberlog.WithRotation(200, 5, 14),
		fiberlog.WithCompression(true),
		fiberlog.WithDiode(
			fiberlog.WithBufferSize(50000),
			fiberlog.WithAdaptiveBuffer(10000, 200000, 1.5),
			fiberlog.WithDiscard(true),
		),
	),
)

πŸ” Advanced Usage

Request-Scoped Logging
app.Get("/api/items/:id", func(c *fiber.Ctx) error {
	// Get request-scoped logger from context
	log := c.Locals("logger").(*zerolog.Logger)

	itemID := c.Params("id")

	log.Info().
		Str("item_id", itemID).
		Str("user_agent", c.Get("User-Agent")).
		Msg("Item requested")

	// ... handler logic

	return c.JSON(/* ... */)
})
Structured Event Logging
// Business event logging
logger.Info().
	Str("event", "user_registered").
	Str("user_id", userID).
	Str("email", email).
	Int("age", age).
	Bool("marketing_opt_in", marketingOptIn).
	Msg("New user registration")

// Error logging with context
logger.Error().
	Err(err).
	Str("user_id", userID).
	Str("operation", "payment_process").
	Int("attempt", attempt).
	Msg("Payment processing failed")
Adding Fields to Logger
// Create a logger with additional fields
userLogger := logger.WithFields(map[string]interface{}{
	"user_id": userID,
	"session_id": sessionID,
	"ip_address": ipAddress,
})

userLogger.Info().Msg("User logged in")
userLogger.Debug().Str("section", "profile").Msg("Profile viewed")

πŸ”§ Configuration Reference

Core Options
Option Description
WithServiceName(name string) Sets the service name for logs
WithLevel(level string) Sets logging level (trace, debug, info, warn, error, fatal)
WithTypedContext(context map[string]ContextValue) Adds global context to all log entries
WithStringValue(key, value string) Adds a string value to the global context
WithIntValue(key string, value int) Adds an integer value to the global context
WithBoolValue(key string, value bool) Adds a boolean value to the global context
WithTimeValue(key string, value time.Time) Adds a time value to the global context
WithSonicJSON() Enables Bytedance Sonic for faster JSON processing
Output Options
Option Description
WithConsoleOutput(opts ...OutputOption) Configures console output
WithFileOutput(opts ...OutputOption) Configures file output
WithFormat(format FormatType) Sets output format (JSON or pretty)
WithColors(enabled bool) Enables/disables colored output (console only)
WithTimeFormat(format string) Sets timestamp format
WithDirectory(dir string) Sets directory for log files
WithRotation(maxSizeMB, maxBackups, maxAgeDays int) Configures log rotation
WithCompression(enabled bool) Enables compressed log archives
WithBatchedWrites(batchSize int, flushInterval time.Duration) Enables batched writes for I/O efficiency
Diode Options
Option Description
WithDiode(opts ...DiodeOption) Enables non-blocking writes with diode buffer
WithBufferSize(size int) Sets diode buffer size
WithPollInterval(interval time.Duration) Sets diode polling interval
WithDiscard(discard bool) Controls whether to discard logs when buffer is full
WithAdaptiveBuffer(minSize, maxSize int, scaleFactor float64) Enables automatic buffer resizing
WithAlertFunction(fn AlertFunc) Sets handler for buffer overflow alerts
Sampling Options
Option Description
WithSampling(opts ...SamplingOption) Enables log sampling
WithSamplingBurst(size uint32) Sets burst size before sampling kicks in
WithSamplingPeriod(period time.Duration) Sets sampling period
WithSamplingRate(level string, rate uint32) Sets sampling rate for specific log level
WithAdaptiveSampling(loadThreshold float64) Enables automatic sampling rate adjustment
Middleware Options
Option Description
WithMiddlewareFormat(format string) Sets log format for middleware
WithMiddlewareTimeFormat(format string) Sets time format for middleware logs
WithTimeZone(zone string) Sets time zone for middleware timestamps
WithMiddlewareColors(enable bool) Enables/disables colors in middleware logs
WithSkipPaths(paths []string) Sets paths to skip logging
WithLogLevel(level zerolog.Level) Sets log level for normal requests
WithErrorLogLevel(level zerolog.Level) Sets log level for error requests
WithPooling(enable bool) Enables/disables object pooling
WithMinLatency(minLatency time.Duration) Only logs requests with latency above threshold
WithRequestBodyLogging(enable bool, maxSize int, level zerolog.Level) Configures request body logging
WithResponseBodyLogging(enable bool, maxSize int, level zerolog.Level) Configures response body logging
WithHeaderLogging(enable bool, level zerolog.Level, filters []string) Configures header logging

πŸ“š Examples

Basic Logging
package main

import (
	"github.com/abdel-issaoui/fiberlog"
	"github.com/gofiber/fiber/v2"
)

func main() {
	// Create a development logger
	logger := fiberlog.NewDevelopmentLogger("example-service")
	defer logger.Close()

	// Log messages at different levels
	logger.Trace().Msg("This is a trace message")
	logger.Debug().Msg("This is a debug message")
	logger.Info().Msg("This is an info message")
	logger.Warn().Msg("This is a warning message")
	logger.Error().Msg("This is an error message")

	// Log with structured data
	logger.Info().
		Str("user", "john").
		Int("age", 30).
		Bool("active", true).
		Msg("User profile")
}
HTTP API Server with Request Logging
package main

import (
	"github.com/abdel-issaoui/fiberlog"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"
)

func main() {
	// Create a logger for API usage
	logger := fiberlog.NewAPILogger("api-service", "v1.0.0")
	defer logger.Close()

	// Create Fiber app
	app := fiber.New()

	// Use the API-optimized middleware
	app.Use(fiberlog.APIMiddleware(logger))

	// Routes
	app.Get("/api/users", func(c *fiber.Ctx) error {
		// Get logger from context
		log := c.Locals("logger").(*zerolog.Logger)

		// Log the request with context
		log.Info().
			Int("limit", c.QueryInt("limit", 10)).
			Int("page", c.QueryInt("page", 1)).
			Str("sort", c.Query("sort", "id")).
			Msg("Listing users")

		// Return dummy data
		return c.JSON(fiber.Map{
			"success": true,
			"data": []fiber.Map{
				{"id": 1, "name": "John Doe"},
				{"id": 2, "name": "Jane Smith"},
			},
		})
	})

	app.Listen(":3000")
}
Advanced Multi-Logger Setup
package main

import (
	"github.com/abdel-issaoui/fiberlog"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"
	"time"
)

func main() {
	// Create specialized loggers for different purposes
	accessLogger := fiberlog.NewLogger(
		fiberlog.WithServiceName("http-access"),
		fiberlog.WithLevel("info"),
		fiberlog.WithFileOutput(
			fiberlog.WithDirectory("./logs"),
			fiberlog.WithFormat(fiberlog.FormatJSON),
			fiberlog.WithRotation(100, 10, 30),
		),
	)

	errorLogger := fiberlog.NewLogger(
		fiberlog.WithServiceName("errors"),
		fiberlog.WithLevel("error"),
		fiberlog.WithConsoleOutput(
			fiberlog.WithFormat(fiberlog.FormatPretty),
			fiberlog.WithColors(true),
		),
		fiberlog.WithFileOutput(
			fiberlog.WithDirectory("./logs"),
			fiberlog.WithFormat(fiberlog.FormatJSON),
			fiberlog.WithRotation(100, 20, 60),
		),
	)

	businessLogger := fiberlog.NewLogger(
		fiberlog.WithServiceName("business-events"),
		fiberlog.WithLevel("info"),
		fiberlog.WithFileOutput(
			fiberlog.WithDirectory("./logs"),
			fiberlog.WithFormat(fiberlog.FormatJSON),
		),
		fiberlog.WithSonicJSON(),
	)

	// Create Fiber app with access logger middleware
	app := fiber.New()
	app.Use(accessLogger.Middleware())

	// Handle errors with error logger
	app.Use(func(c *fiber.Ctx) error {
		// Store business logger in context
		c.Locals("businessLogger", businessLogger)

		// Error handling
		err := c.Next()
		if err != nil {
			// Log error with context
			errorLogger.Error().
				Err(err).
				Str("path", c.Path()).
				Str("method", c.Method()).
				Str("ip", c.IP()).
				Msg("Request error")

			// Send error response
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"error": err.Error(),
			})
		}

		return nil
	})

	// Add routes
	app.Get("/api/order", func(c *fiber.Ctx) error {
		// Get business logger from context
		blog := c.Locals("businessLogger").(*fiberlog.Logger)

		// Log business event
		blog.Info().
			Str("event", "order_created").
			Str("order_id", "ORD-1234").
			Float64("amount", 99.99).
			Str("customer_id", "CUST-5678").
			Time("created_at", time.Now()).
			Msg("New order created")

		return c.JSON(fiber.Map{
			"success": true,
			"order_id": "ORD-1234",
		})
	})

	// Clean up on shutdown
	defer func() {
		accessLogger.Close()
		errorLogger.Close()
		businessLogger.Close()
	}()

	app.Listen(":3000")
}

πŸ† Best Practices

  1. Choose the Right Preset: Use presets like NewDevelopmentLogger or NewProductionLogger for quick setups.

  2. Configure for Your Environment:

    • For development: Use pretty formatting and debug/trace levels
    • For production: Use JSON formatting, info level, and file output with rotation
  3. Optimize for Performance:

    • Enable SonicJSON for high-throughput scenarios
    • Use non-blocking writers with WithDiode options
    • Consider WithSampling for very high volume logs
  4. Always Close Loggers: Use defer logger.Close() to ensure proper resource cleanup.

  5. Use Structured Logging: Add context with methods like .Str(), .Int(), rather than string formatting.

  6. Use Request-Scoped Loggers: Access the logger from Fiber context with c.Locals("logger").

  7. Set Service Name: Always set a descriptive service name with WithServiceName.

  8. Configure Log Levels Appropriately:

    • trace: Very detailed information, only for debugging complex issues
    • debug: Detailed information, useful for debugging
    • info: Normal application behavior, important events
    • warn: Potentially harmful situations
    • error: Error events that might still allow the application to continue
    • fatal: Very severe error events that will lead to application termination

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

FiberLog is built on top of several amazing open-source projects:

  • zerolog - Zero allocation JSON logger
  • Fiber - Express-inspired web framework
  • lumberjack - Rolling logger
  • Sonic - High-performance JSON library

Made with ❀️ by Abdel Issaoui

Star ⭐ this repository if you find it useful!

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 ΒΆ

View Source
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)

View Source
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

View Source
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 ΒΆ

View Source
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 ΒΆ

func APIMiddleware(logger *Logger) fiber.Handler

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 ΒΆ

func ContextWithLogger(ctx context.Context, logger *zerolog.Logger) context.Context

ContextWithLogger adds a logger to the context

func DebugMiddleware ΒΆ

func DebugMiddleware(logger *Logger) fiber.Handler

DebugMiddleware returns a detailed middleware for debugging

func GetErrorCategory ΒΆ

func GetErrorCategory(err error) string

GetErrorCategory extracts the error category from an error

func GetErrorCode ΒΆ

func GetErrorCode(err error) string

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 ΒΆ

func GraphQLMiddleware(logger *Logger) fiber.Handler

GraphQLMiddleware returns a middleware configured for GraphQL APIs

func IsRecoverable ΒΆ

func IsRecoverable(err error) bool

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 ΒΆ

func JSONMiddleware(logger *Logger) fiber.Handler

JSONMiddleware returns a middleware that logs in structured JSON format

func MarshalJSON ΒΆ

func MarshalJSON(v interface{}) ([]byte, error)

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 ΒΆ

func MinimalMiddleware(logger *Logger) fiber.Handler

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 ΒΆ

func NewBatchingWriter(w io.Writer, batchSize int, flushInterval time.Duration) io.WriteCloser

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 ΒΆ

func RESTfulAPIMiddleware(logger *Logger) fiber.Handler

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 ΒΆ

func StandardMiddleware(logger *Logger) fiber.Handler

StandardMiddleware returns a standard middleware configuration for web applications

func UnmarshalJSON ΒΆ

func UnmarshalJSON(data []byte, v interface{}) error

UnmarshalJSON uses Sonic to unmarshal JSON bytes to an object

func WrapError ΒΆ

func WrapError(err error, message string) error

WrapError wraps a standard error with additional context

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

func (*AdaptiveSampler) Sample ΒΆ

func (s *AdaptiveSampler) Sample(level zerolog.Level) bool

Sample implements zerolog.Sampler interface with adaptive behavior

type AlertFunc ΒΆ

type AlertFunc func(source string, missed int)

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) Close ΒΆ

func (bm *BatchManager) Close()

Close shuts down the batch manager

func (*BatchManager) Flush ΒΆ

func (bm *BatchManager) Flush()

Flush manually flushes the current batch

type BoolValue ΒΆ

type BoolValue bool

BoolValue is a bool context value

func (BoolValue) AsZerologField ΒΆ

func (b BoolValue) AsZerologField(e *zerolog.Context, key string)

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 ΒΆ

func (d *Data) Clone() *Data

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 ΒΆ

func (d *Data) GetDurationMs() float64

GetDurationMs returns the latency in milliseconds.

func (*Data) GetTimestamp ΒΆ

func (d *Data) GetTimestamp() string

GetTimestamp returns the stored timestamp value.

func (*Data) IsReleased ΒΆ

func (d *Data) IsReleased() bool

IsReleased returns whether this Data object has been released.

func (*Data) SetTimestamp ΒΆ

func (d *Data) SetTimestamp(timestamp string)

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 IntValue ΒΆ

type IntValue int

IntValue is a simple int context value

func (IntValue) AsZerologField ΒΆ

func (i IntValue) AsZerologField(e *zerolog.Context, key string)

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 ΒΆ

func NewAPILogger(serviceName, version string) *Logger

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 ΒΆ

func NewConsoleLogger(serviceName string, level string) *Logger

NewConsoleLogger creates a simple console logger optimized for local development

func NewDebugLogger ΒΆ

func NewDebugLogger(serviceName string) *Logger

NewDebugLogger creates a logger optimized for debugging with detailed output

func NewDevelopmentLogger ΒΆ

func NewDevelopmentLogger(serviceName string) *Logger

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 ΒΆ

func NewHighPerformanceLogger(serviceName, logDir string) *Logger

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 ΒΆ

func NewHighThroughputLogger(serviceName, logDir string) *Logger

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 ΒΆ

func NewMetricsLogger(serviceName string) *Logger

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 ΒΆ

func NewMinimalLogger(serviceName string) *Logger

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 ΒΆ

func NewProductionLogger(serviceName, logDir string) *Logger

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 ΒΆ

func NewRESTAPILogger(serviceName, version, logDir string) *Logger

NewRESTAPILogger creates a logger optimized for REST API services

func (*Logger) Close ΒΆ

func (l *Logger) Close() error

Close gracefully shuts down all logger resources

func (*Logger) FromContext ΒΆ

func (l *Logger) FromContext(ctx context.Context) *zerolog.Logger

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 ΒΆ

func (l *Logger) ReplaceOutput(w io.Writer)

ReplaceOutput replaces all output writers with a new one, properly handling diode and other writer transformations

func (*Logger) WithContext ΒΆ

func (l *Logger) WithContext(c *fiber.Ctx) *zerolog.Logger

WithContext creates a child logger with request context from a Fiber context

func (*Logger) WithField ΒΆ

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField adds a single field to the logger instance

func (*Logger) WithFields ΒΆ

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields adds multiple fields to the logger instance

func (*Logger) WithSonicJSON ΒΆ

func (l *Logger) WithSonicJSON() *Logger

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 ΒΆ

func (w *SonicJSONWriter) WriteLevel(level zerolog.Level, p []byte) (n int, err error)

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.

func (*Template) Reset ΒΆ

func (t *Template) Reset()

Reset clears the parsed template, forcing reparse on next execute.

type TimeValue ΒΆ

type TimeValue time.Time

TimeValue is a time.Time context value

func (TimeValue) AsZerologField ΒΆ

func (t TimeValue) AsZerologField(e *zerolog.Context, key string)

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

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