turbolog

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2025 License: MIT Imports: 19 Imported by: 0

README ΒΆ

⚑ TurboLog

High-Performance Structured Logger for Go

Go Version License Go Report Card

Zero-allocation logging with enterprise-grade features
Built on zerolog β€’ Production-ready β€’ Secure by default

Features β€’ Installation β€’ Quick Start β€’ Performance β€’ Documentation


🎯 Why TurboLog?

TurboLog is a production-ready logging library that combines blazing-fast performance with enterprise security features. Perfect for high-throughput microservices requiring zero-latency logging with automatic sensitive data protection.

Performance at a Glance
TurboLog Basic:      202.6 ns/op    0 B/op    0 allocs/op  ⚑
TurboLog WithFields: 381.1 ns/op    0 B/op    0 allocs/op
TurboLog Disabled:     2.1 ns/op    0 B/op    0 allocs/op  πŸš€ Fastest!
TurboLog Concurrent:  39.9 ns/op    0 B/op    0 allocs/op

vs Zerolog:           71.1 ns/op    0 B/op    0 allocs/op  (raw baseline)
vs Zap:              401.5 ns/op    0 B/op    0 allocs/op  (2x slower)
vs Logrus:          1191  ns/op  412 B/op   13 allocs/op  (6x slower)

TurboLog is 2x faster than Zap and 6x faster than Logrus while maintaining full CloudWeGo Hertz compatibility and enterprise features.


✨ Features

Feature Description
⚑ Zero Allocations 202ns/op with 0 heap allocations on hot path
πŸ”’ Auto Scrubbing Built-in protection for passwords, tokens, API keys, PII
πŸš€ Hertz Compatible Drop-in replacement for CloudWeGo Hertz hlog
πŸ“ Structured Logging Native key-value pair support with zero allocations (v1.0.9+)
🎯 Context-Aware Context-based structured logging for request tracing (v1.0.9+)
πŸ“Š Metrics Ready Pluggable interface for Prometheus/OpenTelemetry
πŸ“‚ Production Features File rotation, batching, diode buffers, graceful shutdown
🎯 Type-Optimized Fast paths for string, int, int64, float64, bool, error
🌊 Non-Blocking Diode ring buffer pattern (100-100K configurable)
πŸ›‘οΈ Thread-Safe Zero race conditions (verified with -race detector)
Security Features

Auto-scrubs sensitive data:

  • πŸ” Passwords, secrets, passphrases
  • πŸ”‘ API keys, access tokens, bearer tokens
  • 🎫 JWT tokens, session IDs
  • ☁️ AWS credentials (AKIA*, SECRET_KEY)
  • πŸ’³ Credit card numbers
  • πŸ“§ Email addresses (partial masking)
  • πŸ—„οΈ Database connection strings

πŸ“¦ Installation

go get github.com/a-issaoui/turbolog

Requirements: Go 1.24.0+


πŸš€ Quick Start

Basic Usage
package main

import (
    "context"
    "time"
    "github.com/a-issaoui/turbolog"
)

func main() {
    log := turbolog.Init()
    defer log.Shutdown()

    // Simple logging
    log.Info("Application started")
    log.Warn("This is a warning")
    log.Error("This is an error")

    // Structured logging with key-value pairs (NEW in v1.0.9!)
    log.Info("HTTP request", "method", "GET", "path", "/api/users", "status", 200)

    // Context-aware structured logging (NEW in v1.0.9!)
    ctx := context.Background()
    turbolog.CtxInfo(ctx, "Database query", "table", "users", "duration_ms", 45)

    // Structured logging with Event API
    log.InfoEvent().
        Str("user_id", "user-123").
        Int("count", 42).
        Dur("latency", 15*time.Millisecond).
        Msg("Request processed")

    // Formatted logging
    log.Infof("Processing item %d of %d", 5, 10)
}
Hertz Framework Integration
import (
    "github.com/a-issaoui/turbolog"
    "github.com/cloudwego/hertz/pkg/common/hlog"
)

func main() {
    // Set TurboLog as Hertz logger
    turbolog.SetHertzLogger()

    // Structured logging with key-value pairs (v1.0.9+)
    hlog.Info("HTTP request", "method", "GET", "status", 200, "path", "/api/users")

    // Context-aware logging
    hlog.CtxInfof(ctx, "Request processed: %s", path)

    // Traditional formatted logging
    hlog.Info("Server started")
}
Production Configuration
config := turbolog.NewConfig()

// Core settings
config.Level = turbolog.LevelInfo
config.Format = "json"
config.Environment = "production"

// Performance
config.UseDialode = true
config.DiodeBufferSize = 5000

// Security
config.ScrubSensitiveData = true

// File rotation
config.FileEnabled = true
config.FilePath = "/var/log/app/app.log"
config.FileMaxSize = 100    // MB
config.FileMaxAge = 30      // days
config.FileCompress = true

log := turbolog.InitWithConfig(config)
defer log.Shutdown()

⚑ Performance

Benchmark Results

System: Linux 6.12.0, Intel Core i7-10750H @ 2.60GHz, Go 1.25.3

Benchmark                         | Time        | Memory    | Allocations
----------------------------------|-------------|-----------|-------------
BenchmarkTurbologBasic            | 202.6 ns/op | 0 B/op    | 0 allocs/op
BenchmarkTurbologWithFields       | 381.1 ns/op | 0 B/op    | 0 allocs/op
BenchmarkStructuredLogging (NEW)  | 395.2 ns/op | 0 B/op    | 0 allocs/op
BenchmarkCtxStructuredLogging     | 388.5 ns/op | 0 B/op    | 0 allocs/op
BenchmarkTurbologDisabled         |   2.1 ns/op | 0 B/op    | 0 allocs/op
BenchmarkTurbologConcurrent       |  39.9 ns/op | 0 B/op    | 0 allocs/op

BenchmarkZerologBasic             |  71.1 ns/op | 0 B/op    | 0 allocs/op
BenchmarkZerologWithFields        | 255.0 ns/op | 0 B/op    | 0 allocs/op
BenchmarkZerologConcurrent        |  30.6 ns/op | 0 B/op    | 0 allocs/op

BenchmarkZapBasic                 | 401.5 ns/op | 0 B/op    | 0 allocs/op
BenchmarkZapWithFields            | 760.0 ns/op | 256 B/op  | 1 allocs/op

BenchmarkLogrusBasic              |  1191 ns/op | 412 B/op  | 13 allocs/op
BenchmarkLogrusWithFields         |  3044 ns/op | 1285 B/op | 20 allocs/op

Key Achievements:

  • βœ… Zero allocations maintained
  • βœ… 2x faster than Zap
  • βœ… 6x faster than Logrus
  • βœ… Fastest disabled check (2.1ns)
  • βœ… Excellent concurrent performance (39.9ns)
Why Not Match Zerolog's 71ns?

TurboLog adds 130ns overhead for CloudWeGo Hertz hlog compatibility:

  • ~70ns: Interface conversion (formatArgs)
  • ~20ns: Wrapper function calls
  • ~10ns: Metric recording
  • ~30ns: Other compatibility overhead

This is architectural - the cost of 100% hlog compatibility. You cannot eliminate it without breaking the API.


πŸ“š Documentation

Log Levels
turbolog.LevelTrace   // Detailed debugging
turbolog.LevelDebug   // Debugging information
turbolog.LevelInfo    // General information (default)
turbolog.LevelNotice  // Normal but significant
turbolog.LevelWarn    // Warning messages
turbolog.LevelError   // Error messages
turbolog.LevelFatal   // Fatal errors (exits program)
Logging Methods

Simple:

log.Info("message")
log.Warn("warning")
log.Error("error")

Formatted:

log.Infof("Processing %d items", count)
log.Errorf("Failed: %v", err)

Structured (Zero Allocations):

log.InfoEvent().
    Str("user_id", "123").
    Int("count", 42).
    Dur("latency", 15*time.Millisecond).
    Msg("Request processed")

Context-Aware:

log.CtxInfof(ctx, "Processing user %s", userID)
Specialized Logging
// HTTP request logging
log.LogHTTPRequest("GET", "/api/users", 200, 45*time.Millisecond, "192.168.1.1")

// Database query logging
log.LogDatabaseQuery("SELECT * FROM users", 12*time.Millisecond, nil)

// Cache operation logging
log.LogCacheOperation("get", "user:456", true, 2*time.Millisecond)

πŸ” Sensitive Data Scrubbing

config := turbolog.NewConfig()
config.ScrubSensitiveData = true
log := turbolog.InitWithConfig(config)

// Input
log.Info("User login: password=secret123, token=eyJhbGc...")

// Output (automatically scrubbed)
// {"level":"info","message":"User login: password=[REDACTED], token=[JWT_REDACTED]"}

What Gets Scrubbed:

  • Passwords, API keys, bearer tokens
  • JWT tokens, session IDs
  • AWS credentials (AKIA*, SECRET_KEY)
  • Credit card numbers
  • Email addresses (partial: us**@example.com)
  • Database connection strings

πŸ“Š Metrics Integration

type PrometheusRecorder struct {
    logsTotal *prometheus.CounterVec
}

func (p *PrometheusRecorder) IncLog(level turbolog.Level) {
    p.logsTotal.WithLabelValues(level.String()).Inc()
}

// Configure logger with metrics
config := turbolog.NewConfig()
config.MetricsRecorder = NewPrometheusRecorder()
log := turbolog.InitWithConfig(config)

Full example: examples/metrics/prometheus_example.go


πŸ§ͺ Testing

# Run all tests
go test -v ./...

# Run with race detector
go test -race ./...

# Run benchmarks
go test -bench=. -benchmem ./...

Test Coverage:

  • βœ… Zero race conditions (verified with -race)
  • βœ… Concurrent stress tests
  • βœ… Hertz hlog compatibility tests
  • βœ… Production simulation tests

πŸ—οΈ Architecture

Application Code
       ↓
TurboLog Logger (hlog compatible)
       ↓
Zerolog Core (zero-allocation)
       ↓
Optional: Scrubber / Diode / Batching
       ↓
Output: Console / File / Centralized

πŸ’‘ Examples

  • Basic: examples/basic/main.go
  • Advanced: examples/advanced/main.go (production features)
  • HTTP Server: examples/production/main.go
  • Hertz Integration: examples/hlog/main.go
  • Metrics: examples/metrics/prometheus_example.go
cd examples/basic && go run main.go

πŸ“„ License

MIT License - see LICENSE file for details.


πŸ™ Acknowledgments

Built on:

Special thanks to CloudWeGo for Hertz.


πŸ“ž Support


Made with ❀️ for production systems

⭐ Star this repo if TurboLog helped you!

Report Bug β€’ Request Feature

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const Version = "1.0.9"

Version of the turbolog package

Variables ΒΆ

This section is empty.

Functions ΒΆ

func CtxDebug ΒΆ added in v1.0.9

func CtxDebug(c context.Context, v ...interface{})

func CtxDebugf ΒΆ added in v1.0.2

func CtxDebugf(c context.Context, f string, v ...interface{})

func CtxError ΒΆ added in v1.0.9

func CtxError(c context.Context, v ...interface{})

func CtxErrorf ΒΆ added in v1.0.2

func CtxErrorf(c context.Context, f string, v ...interface{})

func CtxFatal ΒΆ added in v1.0.9

func CtxFatal(c context.Context, v ...interface{})

func CtxFatalf ΒΆ added in v1.0.2

func CtxFatalf(c context.Context, f string, v ...interface{})

func CtxInfo ΒΆ added in v1.0.9

func CtxInfo(c context.Context, v ...interface{})

func CtxInfof ΒΆ added in v1.0.2

func CtxInfof(c context.Context, f string, v ...interface{})

func CtxNotice ΒΆ added in v1.0.9

func CtxNotice(c context.Context, v ...interface{})

func CtxNoticef ΒΆ added in v1.0.2

func CtxNoticef(c context.Context, f string, v ...interface{})

func CtxTrace ΒΆ added in v1.0.9

func CtxTrace(c context.Context, v ...interface{})

func CtxTracef ΒΆ added in v1.0.2

func CtxTracef(c context.Context, f string, v ...interface{})

func CtxWarn ΒΆ added in v1.0.9

func CtxWarn(c context.Context, v ...interface{})

func CtxWarnf ΒΆ added in v1.0.2

func CtxWarnf(c context.Context, f string, v ...interface{})

func Debug ΒΆ

func Debug(v ...interface{})

func DebugEvent ΒΆ added in v1.0.2

func DebugEvent() *zerolog.Event

func Debugf ΒΆ added in v1.0.2

func Debugf(f string, v ...interface{})

func Error ΒΆ

func Error(v ...interface{})

func ErrorEvent ΒΆ added in v1.0.2

func ErrorEvent() *zerolog.Event

func Errorf ΒΆ added in v1.0.2

func Errorf(f string, v ...interface{})

func Fatal ΒΆ

func Fatal(v ...interface{})

func FatalEvent ΒΆ added in v1.0.2

func FatalEvent() *zerolog.Event

func Fatalf ΒΆ added in v1.0.2

func Fatalf(f string, v ...interface{})

func Info ΒΆ

func Info(v ...interface{})

func InfoEvent ΒΆ added in v1.0.2

func InfoEvent() *zerolog.Event

func Infof ΒΆ added in v1.0.2

func Infof(f string, v ...interface{})

func InitLogger ΒΆ

func InitLogger(_, _, _ string)

func NewHlogAdapter ΒΆ added in v1.0.2

func NewHlogAdapter(logger *Logger) hlog.FullLogger

NewHlogAdapter creates a new adapter for Hertz hlog compatibility

func Notice ΒΆ added in v1.0.2

func Notice(v ...interface{})

func Noticef ΒΆ added in v1.0.2

func Noticef(f string, v ...interface{})

func PanicEvent ΒΆ added in v1.0.2

func PanicEvent() *zerolog.Event

func SetHertzLogger ΒΆ added in v1.0.2

func SetHertzLogger(logger *Logger)

SetHertzLogger sets the logger for Hertz framework Usage: hlog.SetLogger(turbolog.NewHlogAdapter(logger))

func SetLevel ΒΆ added in v1.0.2

func SetLevel(level Level)

SetLevel sets the log level for the default logger

func SetOutput ΒΆ added in v1.0.2

func SetOutput(w io.Writer)

SetOutput redirects output for the default logger

func Sync ΒΆ

func Sync(w io.Writer) error

Sync flushes any buffered log entries

func Trace ΒΆ added in v1.0.2

func Trace(v ...interface{})

func Tracef ΒΆ added in v1.0.2

func Tracef(f string, v ...interface{})

func Warn ΒΆ

func Warn(v ...interface{})

func WarnEvent ΒΆ added in v1.0.2

func WarnEvent() *zerolog.Event

func Warnf ΒΆ added in v1.0.2

func Warnf(f string, v ...interface{})

func With ΒΆ added in v1.0.2

func With() zerolog.Context

func WithContext ΒΆ

func WithContext(ctx context.Context) context.Context

Types ΒΆ

type BatchStats ΒΆ

type BatchStats struct {
	TotalSent    int64
	TotalFailed  int64
	DroppedCount int64
	BufferSize   int
	LastSendTime time.Time
}

BatchStats holds statistics about the batched writer

type BatchedCentralizedWriter ΒΆ

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

BatchedCentralizedWriter buffers log entries and sends them in batches

func NewBatchedCentralizedWriter ΒΆ

func NewBatchedCentralizedWriter(url string, batchSize int, timeout time.Duration, retries int, scrubber *SensitiveDataScrubber) *BatchedCentralizedWriter

NewBatchedCentralizedWriter creates a new batched centralized writer

func (*BatchedCentralizedWriter) Close ΒΆ

func (w *BatchedCentralizedWriter) Close() error

Close flushes remaining logs and stops the background flusher

func (*BatchedCentralizedWriter) GetStats ΒΆ

func (w *BatchedCentralizedWriter) GetStats() BatchStats

GetStats returns current statistics

func (*BatchedCentralizedWriter) Health ΒΆ added in v1.0.2

func (w *BatchedCentralizedWriter) Health() error

Health checks the health of the batch writer

func (*BatchedCentralizedWriter) Write ΒΆ

func (w *BatchedCentralizedWriter) Write(p []byte) (n int, err error)

Write implements io.Writer

type Config ΒΆ

type Config struct {
	// General settings
	Level  Level      `json:"level"`
	Format string     `json:"format"`
	Output OutputType `json:"output"`

	// File logging settings
	FileEnabled    bool   `json:"file_enabled"`
	FilePath       string `json:"file_path"`
	FileMaxSize    int    `json:"file_max_size"`
	FileMaxAge     int    `json:"file_max_age"`
	FileMaxBackups int    `json:"file_max_backups"`
	FileCompress   bool   `json:"file_compress"`

	// Centralized logging
	CentralizedEnabled bool   `json:"centralized_enabled"`
	CentralizedURL     string `json:"centralized_url"`

	// Performance settings
	UseDialode           bool          `json:"use_diode"`
	DiodeBufferSize      int           `json:"diode_buffer_size"`      // Buffer size for diode (default: 1000)
	DiodePollingInterval time.Duration `json:"diode_polling_interval"` // Polling interval for diode (default: 10ms)
	SamplingEnabled      bool          `json:"sampling_enabled"`
	SampleRate           int           `json:"sample_rate"`
	SamplingBurst        int           `json:"sampling_burst"`
	SamplingPeriod       time.Duration `json:"sampling_period"`

	// Development features
	CallerEnabled bool `json:"caller_enabled"`
	ColorEnabled  bool `json:"color_enabled"`
	PrettyPrint   bool `json:"pretty_print"`

	// Security features
	ScrubSensitiveData bool `json:"scrub_sensitive_data"`

	// Batching settings for centralized logging
	BatchEnabled bool          `json:"batch_enabled"`
	BatchSize    int           `json:"batch_size"`
	BatchTimeout time.Duration `json:"batch_timeout"`
	BatchRetries int           `json:"batch_retries"`

	// Environment
	Environment string `json:"environment"`

	// Observability
	MetricsRecorder MetricsRecorder `json:"-"` // Metrics backend (Prometheus, OpenTelemetry, etc.)
}

Config holds the logger configuration

func LoadConfig ΒΆ

func LoadConfig() *Config

LoadConfig loads logger configuration from environment variables Starts with NewConfig() defaults and overrides with env vars

func NewConfig ΒΆ added in v1.0.8

func NewConfig() *Config

NewConfig returns a new config with sensible defaults Users should customize this based on their needs

func (*Config) IsDevelopment ΒΆ

func (c *Config) IsDevelopment() bool

IsDevelopment checks if the environment is development

func (*Config) IsProduction ΒΆ

func (c *Config) IsProduction() bool

IsProduction checks if the environment is production

func (*Config) IsStaging ΒΆ

func (c *Config) IsStaging() bool

IsStaging checks if the environment is staging

func (*Config) ShouldUseCentralizedWriter ΒΆ

func (c *Config) ShouldUseCentralizedWriter() bool

ShouldUseCentralizedWriter checks if centralized writer should be used

func (*Config) ShouldUseConsoleWriter ΒΆ

func (c *Config) ShouldUseConsoleWriter() bool

ShouldUseConsoleWriter checks if console writer should be used

func (*Config) ShouldUseFileWriter ΒΆ

func (c *Config) ShouldUseFileWriter() bool

ShouldUseFileWriter checks if file writer should be used

func (*Config) Validate ΒΆ

func (c *Config) Validate() error

Validate performs comprehensive validation of the configuration

func (*Config) ValidateOrPanic ΒΆ

func (c *Config) ValidateOrPanic()

ValidateOrPanic validates the configuration and panics if invalid

type Control ΒΆ added in v1.0.2

type Control interface {
	SetLevel(level Level)
	SetOutput(writer io.Writer)
}

Control provides methods to config a logger

type CtxLogger ΒΆ added in v1.0.2

type CtxLogger interface {
	CtxTracef(ctx context.Context, format string, v ...interface{})
	CtxDebugf(ctx context.Context, format string, v ...interface{})
	CtxInfof(ctx context.Context, format string, v ...interface{})
	CtxNoticef(ctx context.Context, format string, v ...interface{})
	CtxWarnf(ctx context.Context, format string, v ...interface{})
	CtxErrorf(ctx context.Context, format string, v ...interface{})
	CtxFatalf(ctx context.Context, format string, v ...interface{})
}

CtxLogger is a logger interface that provides context-aware logging

type FormatLogger ΒΆ added in v1.0.2

type FormatLogger interface {
	Tracef(format string, v ...interface{})
	Debugf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Noticef(format string, v ...interface{})
	Warnf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Fatalf(format string, v ...interface{})
}

FormatLogger is a logger interface that provides formatted logging

type FullLogger ΒΆ added in v1.0.2

type FullLogger interface {
	LoggerInterface
	FormatLogger
	CtxLogger
	Control
}

FullLogger is the combination of Logger, FormatLogger, CtxLogger and Control This interface is 100% compatible with Hertz's hlog.FullLogger

type HlogAdapter ΒΆ added in v1.0.2

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

HlogAdapter adapts turbolog.Logger to work with Hertz's hlog interface

func (*HlogAdapter) CtxDebug ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxDebug(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxDebugf ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxDebugf(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) CtxError ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxError(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxErrorf ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxErrorf(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) CtxFatal ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxFatal(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxFatalf ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxFatalf(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) CtxInfo ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxInfo(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxInfof ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxInfof(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) CtxNotice ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxNotice(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxNoticef ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxNoticef(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) CtxTrace ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxTrace(ctx context.Context, v ...interface{})

Context-aware structured logging (non-formatted)

func (*HlogAdapter) CtxTracef ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxTracef(ctx context.Context, format string, v ...interface{})

Context-aware formatted logging

func (*HlogAdapter) CtxWarn ΒΆ added in v1.0.9

func (a *HlogAdapter) CtxWarn(ctx context.Context, v ...interface{})

func (*HlogAdapter) CtxWarnf ΒΆ added in v1.0.2

func (a *HlogAdapter) CtxWarnf(ctx context.Context, format string, v ...interface{})

func (*HlogAdapter) Debug ΒΆ added in v1.0.2

func (a *HlogAdapter) Debug(v ...interface{})

func (*HlogAdapter) Debugf ΒΆ added in v1.0.2

func (a *HlogAdapter) Debugf(format string, v ...interface{})

func (*HlogAdapter) Error ΒΆ added in v1.0.2

func (a *HlogAdapter) Error(v ...interface{})

func (*HlogAdapter) Errorf ΒΆ added in v1.0.2

func (a *HlogAdapter) Errorf(format string, v ...interface{})

func (*HlogAdapter) Fatal ΒΆ added in v1.0.2

func (a *HlogAdapter) Fatal(v ...interface{})

func (*HlogAdapter) Fatalf ΒΆ added in v1.0.2

func (a *HlogAdapter) Fatalf(format string, v ...interface{})

func (*HlogAdapter) Info ΒΆ added in v1.0.2

func (a *HlogAdapter) Info(v ...interface{})

func (*HlogAdapter) Infof ΒΆ added in v1.0.2

func (a *HlogAdapter) Infof(format string, v ...interface{})

func (*HlogAdapter) Notice ΒΆ added in v1.0.2

func (a *HlogAdapter) Notice(v ...interface{})

func (*HlogAdapter) Noticef ΒΆ added in v1.0.2

func (a *HlogAdapter) Noticef(format string, v ...interface{})

func (*HlogAdapter) SetLevel ΒΆ added in v1.0.2

func (a *HlogAdapter) SetLevel(level hlog.Level)

Control methods

func (*HlogAdapter) SetOutput ΒΆ added in v1.0.2

func (a *HlogAdapter) SetOutput(w io.Writer)

func (*HlogAdapter) Trace ΒΆ added in v1.0.2

func (a *HlogAdapter) Trace(v ...interface{})

Regular logging methods

func (*HlogAdapter) Tracef ΒΆ added in v1.0.2

func (a *HlogAdapter) Tracef(format string, v ...interface{})

Formatted logging methods

func (*HlogAdapter) Warn ΒΆ added in v1.0.2

func (a *HlogAdapter) Warn(v ...interface{})

func (*HlogAdapter) Warnf ΒΆ added in v1.0.2

func (a *HlogAdapter) Warnf(format string, v ...interface{})

type Level ΒΆ added in v1.0.2

type Level int

Level represents the logging level (hlog compatible)

const (
	LevelTrace Level = iota
	LevelDebug
	LevelInfo
	LevelNotice
	LevelWarn
	LevelError
	LevelFatal
)

func ParseLevel ΒΆ added in v1.0.2

func ParseLevel(level string) Level

ParseLevel parses a string into a Level

func (Level) String ΒΆ added in v1.0.2

func (l Level) String() string

String returns the string representation of the level

type Logger ΒΆ

type Logger struct {
	// HOT PATH (frequently accessed together - fits in single cache line)
	*zerolog.Logger // 8 bytes - pointer to logger
	// contains filtered or unexported fields
}

func FromContext ΒΆ

func FromContext(ctx context.Context) *Logger

func Get ΒΆ

func Get() *Logger

func Init ΒΆ

func Init() *Logger

func InitWithConfig ΒΆ

func InitWithConfig(cfg *Config) *Logger

func (*Logger) CtxDebug ΒΆ added in v1.0.9

func (l *Logger) CtxDebug(ctx context.Context, v ...interface{})

func (*Logger) CtxDebugf ΒΆ added in v1.0.2

func (l *Logger) CtxDebugf(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxError ΒΆ added in v1.0.9

func (l *Logger) CtxError(ctx context.Context, v ...interface{})

func (*Logger) CtxErrorf ΒΆ added in v1.0.2

func (l *Logger) CtxErrorf(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxFatal ΒΆ added in v1.0.9

func (l *Logger) CtxFatal(ctx context.Context, v ...interface{})

func (*Logger) CtxFatalf ΒΆ added in v1.0.2

func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxInfo ΒΆ added in v1.0.9

func (l *Logger) CtxInfo(ctx context.Context, v ...interface{})

func (*Logger) CtxInfof ΒΆ added in v1.0.2

func (l *Logger) CtxInfof(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxNotice ΒΆ added in v1.0.9

func (l *Logger) CtxNotice(ctx context.Context, v ...interface{})

func (*Logger) CtxNoticef ΒΆ added in v1.0.2

func (l *Logger) CtxNoticef(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxTrace ΒΆ added in v1.0.9

func (l *Logger) CtxTrace(ctx context.Context, v ...interface{})

func (*Logger) CtxTracef ΒΆ added in v1.0.2

func (l *Logger) CtxTracef(ctx context.Context, format string, v ...interface{})

func (*Logger) CtxWarn ΒΆ added in v1.0.9

func (l *Logger) CtxWarn(ctx context.Context, v ...interface{})

func (*Logger) CtxWarnf ΒΆ added in v1.0.2

func (l *Logger) CtxWarnf(ctx context.Context, format string, v ...interface{})

func (*Logger) Debug ΒΆ added in v1.0.2

func (l *Logger) Debug(v ...interface{})

func (*Logger) DebugEvent ΒΆ added in v1.0.2

func (l *Logger) DebugEvent() *zerolog.Event

func (*Logger) Debugf ΒΆ added in v1.0.2

func (l *Logger) Debugf(format string, v ...interface{})

func (*Logger) Error ΒΆ added in v1.0.2

func (l *Logger) Error(v ...interface{})

func (*Logger) ErrorEvent ΒΆ added in v1.0.2

func (l *Logger) ErrorEvent() *zerolog.Event

func (*Logger) Errorf ΒΆ added in v1.0.2

func (l *Logger) Errorf(format string, v ...interface{})

func (*Logger) Fatal ΒΆ added in v1.0.2

func (l *Logger) Fatal(v ...interface{})

func (*Logger) FatalEvent ΒΆ added in v1.0.2

func (l *Logger) FatalEvent() *zerolog.Event

func (*Logger) Fatalf ΒΆ added in v1.0.2

func (l *Logger) Fatalf(format string, v ...interface{})

func (*Logger) Info ΒΆ added in v1.0.2

func (l *Logger) Info(v ...interface{})

func (*Logger) InfoEvent ΒΆ added in v1.0.2

func (l *Logger) InfoEvent() *zerolog.Event

func (*Logger) Infof ΒΆ added in v1.0.2

func (l *Logger) Infof(format string, v ...interface{})

func (*Logger) LogCacheOperation ΒΆ

func (l *Logger) LogCacheOperation(op, key string, hit bool, dur time.Duration)

func (*Logger) LogDatabaseQuery ΒΆ

func (l *Logger) LogDatabaseQuery(q string, dur time.Duration, err error)

func (*Logger) LogHTTPRequest ΒΆ

func (l *Logger) LogHTTPRequest(method, path string, status int, dur time.Duration, ip string)

func (*Logger) Notice ΒΆ added in v1.0.2

func (l *Logger) Notice(v ...interface{})

func (*Logger) Noticef ΒΆ added in v1.0.2

func (l *Logger) Noticef(format string, v ...interface{})

func (*Logger) PanicEvent ΒΆ added in v1.0.2

func (l *Logger) PanicEvent() *zerolog.Event

func (*Logger) SetLevel ΒΆ added in v1.0.2

func (l *Logger) SetLevel(lv Level)

func (*Logger) SetOutput ΒΆ added in v1.0.2

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

func (*Logger) Shutdown ΒΆ

func (l *Logger) Shutdown() error

func (*Logger) Trace ΒΆ added in v1.0.2

func (l *Logger) Trace(v ...interface{})

func (*Logger) TraceEvent ΒΆ added in v1.0.2

func (l *Logger) TraceEvent() *zerolog.Event

func (*Logger) Tracef ΒΆ added in v1.0.2

func (l *Logger) Tracef(format string, v ...interface{})

func (*Logger) Warn ΒΆ added in v1.0.2

func (l *Logger) Warn(v ...interface{})

func (*Logger) WarnEvent ΒΆ added in v1.0.2

func (l *Logger) WarnEvent() *zerolog.Event

func (*Logger) Warnf ΒΆ added in v1.0.2

func (l *Logger) Warnf(format string, v ...interface{})

func (*Logger) With ΒΆ added in v1.0.2

func (l *Logger) With() zerolog.Context

func (*Logger) WithContext ΒΆ

func (l *Logger) WithContext(ctx context.Context) context.Context

type LoggerInterface ΒΆ added in v1.0.2

type LoggerInterface interface {
	Trace(v ...interface{})
	Debug(v ...interface{})
	Info(v ...interface{})
	Notice(v ...interface{})
	Warn(v ...interface{})
	Error(v ...interface{})
	Fatal(v ...interface{})
}

LoggerInterface is a logger interface that provides logging function with levels

type MetricsRecorder ΒΆ added in v1.0.8

type MetricsRecorder interface {
	// IncLog increments the log counter for the given level.
	// Called after each successful log write.
	//
	// Example metric: turbolog_logs_total{level="info"} 1234
	IncLog(level Level)

	// IncDropped increments the dropped message counter.
	// Called when logs are dropped due to buffer capacity.
	//
	// Parameters:
	//   - count: number of messages dropped
	//   - reason: why messages were dropped (e.g., "diode_buffer_full", "batch_buffer_full")
	//
	// Example metric: turbolog_dropped_total{reason="diode_buffer_full"} 42
	IncDropped(count int, reason string)

	// IncError increments the error counter for logging infrastructure.
	// Called when internal logging operations fail.
	//
	// Parameters:
	//   - operation: which operation failed (e.g., "batch_write", "file_write", "scrubber")
	//
	// Example metric: turbolog_errors_total{operation="batch_write"} 5
	IncError(operation string)
}

MetricsRecorder provides an interface for recording logging metrics. This allows integration with monitoring systems like Prometheus, OpenTelemetry, StatsD, etc.

The interface is designed to be: - Optional: Uses no-op implementation by default (zero overhead) - Pluggable: Easy to implement for any metrics backend - Low overhead: Counter-based operations only (no allocations) - Non-blocking: Implementations should not block logging operations

Example usage with Prometheus:

type PrometheusRecorder struct {
    logsTotal *prometheus.CounterVec
    droppedTotal *prometheus.CounterVec
    errorsTotal *prometheus.CounterVec
}

func (p *PrometheusRecorder) IncLog(level Level) {
    p.logsTotal.WithLabelValues(level.String()).Inc()
}

type NoOpMetricsRecorder ΒΆ added in v1.0.8

type NoOpMetricsRecorder struct{}

NoOpMetricsRecorder is a no-op implementation of MetricsRecorder. Used by default when metrics are not configured. All methods are empty inline functions with zero overhead.

func (*NoOpMetricsRecorder) IncDropped ΒΆ added in v1.0.8

func (n *NoOpMetricsRecorder) IncDropped(_ int, _ string)

IncDropped does nothing (no-op).

func (*NoOpMetricsRecorder) IncError ΒΆ added in v1.0.8

func (n *NoOpMetricsRecorder) IncError(_ string)

IncError does nothing (no-op).

func (*NoOpMetricsRecorder) IncLog ΒΆ added in v1.0.8

func (n *NoOpMetricsRecorder) IncLog(_ Level)

IncLog does nothing (no-op).

type OutputType ΒΆ

type OutputType string

OutputType represents where logs should be written

const (
	StdoutOutput      OutputType = "stdout"
	FileOutput        OutputType = "file"
	BothOutput        OutputType = "both"
	CentralizedOutput OutputType = "centralized"
)

type ScrubberWriter ΒΆ

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

ScrubberWriter wraps an io.Writer with sensitive data scrubbing

func NewScrubberWriter ΒΆ

func NewScrubberWriter(writer io.Writer, scrubber *SensitiveDataScrubber) *ScrubberWriter

NewScrubberWriter creates a new scrubber writer

func (*ScrubberWriter) Write ΒΆ

func (sw *ScrubberWriter) Write(p []byte) (n int, err error)

Write implements io.Writer with scrubbing

type SensitiveDataScrubber ΒΆ

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

SensitiveDataScrubber removes sensitive information from log messages

func NewSensitiveDataScrubber ΒΆ

func NewSensitiveDataScrubber(enabled bool) *SensitiveDataScrubber

NewSensitiveDataScrubber creates a new scrubber with default patterns

func (*SensitiveDataScrubber) AddPattern ΒΆ

func (s *SensitiveDataScrubber) AddPattern(name string, pattern *regexp.Regexp)

AddPattern adds a custom scrubbing pattern

func (*SensitiveDataScrubber) IsEnabled ΒΆ

func (s *SensitiveDataScrubber) IsEnabled() bool

IsEnabled returns whether the scrubber is enabled

func (*SensitiveDataScrubber) RemovePattern ΒΆ

func (s *SensitiveDataScrubber) RemovePattern(name string)

RemovePattern removes a scrubbing pattern

func (*SensitiveDataScrubber) Scrub ΒΆ

func (s *SensitiveDataScrubber) Scrub(input string) string

Scrub removes sensitive data from the input string

func (*SensitiveDataScrubber) ScrubBytes ΒΆ

func (s *SensitiveDataScrubber) ScrubBytes(input []byte) []byte

ScrubBytes scrubs sensitive data from byte slice

func (*SensitiveDataScrubber) ScrubMap ΒΆ

func (s *SensitiveDataScrubber) ScrubMap(m map[string]interface{}) map[string]interface{}

ScrubMap scrubs sensitive data from map values

func (*SensitiveDataScrubber) SetEnabled ΒΆ

func (s *SensitiveDataScrubber) SetEnabled(enabled bool)

SetEnabled enables or disables the scrubber

type SyncWriter ΒΆ

type SyncWriter interface {
	Sync() error
}

SyncWriter ensures all logs are flushed (call on shutdown)

type Writers ΒΆ

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

Writers holds all configured writers for cleanup

func CreateWriters ΒΆ

func CreateWriters(config *Config) (io.Writer, *Writers)

CreateWriters creates all configured writers based on config

func (*Writers) Close ΒΆ

func (w *Writers) Close() error

Close closes all writers and flushes buffers

func (*Writers) Health ΒΆ added in v1.0.2

func (w *Writers) Health() error

Health checks the health of all writers

Directories ΒΆ

Path Synopsis
examples
hlog command
metrics command

Jump to

Keyboard shortcuts

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