Skip to content

refactorroom/pim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎨 pim - Professional Go Logging Package

Go Reference Go Report Card License: MIT Go Version

✨ A modern, extensible logging package for Go with beautiful output, structured logging, and enterprise features

πŸ“– Documentation β€’ πŸš€ Examples β€’ πŸ”§ API Reference β€’ πŸ“š Contributing


🌟 Features

🎨 Beautiful Output πŸ”§ Structured Logging ⚑ High Performance πŸ›‘οΈ Enterprise Ready
Colored themes & icons JSON & key-value fields Async buffered logging Log rotation & retention
Custom templates Context propagation Zero-allocation paths Multi-writer support
Rich formatting Error wrapping Graceful shutdown Hooks & filtering

🎯 Core Capabilities

  • 🌈 Colored & Themed Output - Customizable color themes, icons, and templates for beautiful terminal logs
  • πŸ“Š Multiple Log Levels - Panic, Error, Warning, Info, Success, Debug, Trace, and custom levels
  • πŸ”— Structured Logging - Arbitrary key-value/context fields, JSON logs, and context propagation
  • ⚑ Async/Buffered Logging - High-performance, non-blocking logging with background flush
  • πŸ“ Log Rotation & Retention - File size/time-based rotation, compression, and cleanup
  • πŸ–₯️ Multi-Writer Support - Log to stdout, stderr, files, memory, remote endpoints, syslog
  • 🎣 Hooks & Filtering - Pre-output hooks for filtering, redaction, enrichment, metrics
  • πŸ“ Caller/Source Info - Configurable file, line, function, package, and stack traces
  • 🌍 Localization - Multi-language log messages, locale detection, and extensible catalogs
  • πŸ“ˆ Metrics & Analytics - Log counts, error rates, and monitoring capabilities
  • πŸ”„ Graceful Shutdown - Ensures all logs are flushed on exit, panic, or signals

πŸš€ Quick Start

Installation

go get github.com/refactorrom/pim

Basic Usage

package main

import "github.com/refactorrom/pim"

func main() {
    // 🎯 Simple logging
    pim.Info("Hello, world!")
    pim.Success("Operation completed!")
    pim.Error("Something went wrong: %v", err)

    // 🎨 Create a custom logger with beautiful output
    config := pim.LoggerConfig{
        Level:         pim.InfoLevel,
        EnableConsole: true,
        EnableColors:  true,
        Async:         true,
        BufferSize:    1000,
        FlushInterval: 2 * time.Second,
        ThemeName:     "monokai",
    }
    logger := pim.NewLoggerCore(config)
    defer logger.Close()

    // πŸ“Š Structured logging
    logger.Info("User login", pim.Fields{"user": "alice", "ip": "1.2.3.4"})
}

🎨 Modern Usage Examples

πŸ“Š Structured & Context Logging

// Key-value logging
logger.InfoKV("Order placed", "order_id", 123, "amount", 99.99)

// Structured fields
logger.InfoWithFields("User login", map[string]interface{}{
    "user": "alice",
    "ip":   "1.2.3.4",
    "time": time.Now(),
})

πŸŽ›οΈ Dynamic Log Level Control

// Set levels programmatically
logger.SetLevel(pim.DebugLevel)
logger.SetLevelFromString("trace")

// From environment
logger.SetLevelFromEnv("LOG_LEVEL")

⚑ Async Logging & Graceful Shutdown

// Install exit handler for graceful shutdown
pim.InstallExitHandler()

// Create async logger
logger := pim.NewLoggerCore(pim.LoggerConfig{
    Async:         true,
    BufferSize:    1000,
    FlushInterval: 2 * time.Second,
})
defer logger.Close()

πŸ“ Log Rotation & Retention

rotation := pim.RotationConfig{
    MaxSize:   10 * 1024 * 1024, // 10MB
    MaxFiles:  5,
    Compress:  true,
    Retention: 30 * 24 * time.Hour, // 30 days
}

fileWriter, _ := pim.NewFileWriter("app.log", config, rotation)
logger.AddWriter(fileWriter)

πŸ–₯️ Multi-Writer & Custom Outputs

// Multiple output destinations
logger.AddWriter(pim.NewConsoleWriter(config))
logger.AddWriter(pim.NewStderrWriter(config))
logger.AddWriter(pim.NewFileWriter("app.log", config, nil))
logger.AddWriter(pim.NewRemoteWriter(config, remoteCfg))

🎨 Theming & Formatting

// Use built-in themes
logger.SetTheme("monokai")
logger.SetTheme("dracula")
logger.SetTheme("nord")

// Custom theme
customTheme := &pim.Theme{
    InfoColor:    pim.Color{Red: 0, Green: 255, Blue: 0},
    ErrorColor:   pim.Color{Red: 255, Green: 0, Blue: 0},
    WarningColor: pim.Color{Red: 255, Green: 255, Blue: 0},
}
logger.SetCustomTheme(customTheme)

// Custom templates
logger.RegisterTemplate("custom", "[{timestamp}] {level} {message}")

πŸ“ Enhanced Caller/Source Info

cfg := pim.NewCallerInfoConfig()
cfg.ShowFileLine = true
cfg.ShowFunctionName = true
cfg.ShowPackageName = true
cfg.StackDepth = 5
logger.SetCallerInfoConfig(cfg)

πŸ”— Error Wrapping & Stack Traces

// Rich error types with stack traces
err := pim.NewError("failed to process", pim.WithStack())
logger.Error("Error occurred: %v", err)

// Error with context
err = pim.WrapError(err, "additional context")

πŸ” Tracing/Telemetry Integration

// Distributed tracing support
logger.WithTrace("trace-id").WithSpan("span-id").Info("Tracing event")

// Correlation IDs
logger.WithCorrelationID("corr-123").Info("Correlated log")

🎣 Hooks & Filtering

// Add custom hooks
logger.AddHookFunc(func(entry pim.CoreLogEntry) (pim.CoreLogEntry, error) {
    // Skip debug logs in production
    if entry.Level == pim.DebugLevel {
        return entry, pim.ErrSkip
    }
    
    // Add timestamp to all logs
    entry.Fields["timestamp"] = time.Now().Unix()
    return entry, nil
})

// Metrics hook
logger.AddHookFunc(func(entry pim.CoreLogEntry) (pim.CoreLogEntry, error) {
    // Increment metrics
    metrics.Increment("logs." + entry.Level.String())
    return entry, nil
})

🌍 Localization/Internationalization

// Create localized logger
loc := pim.NewLocalizedLogger(config, pim.Locale{Language: "en", Region: "US"})

// Use translation keys
loc.TInfo("app_started") // "Application started"

// Change locale
loc.SetLocale(pim.Locale{Language: "es"})
loc.TInfo("app_started") // "AplicaciΓ³n iniciada"

// Custom messages
loc.AddCustomMessage("custom_welcome", "Welcome, {0}!")
loc.TInfo("custom_welcome", "Alice") // "Welcome, Alice!"

πŸ“ˆ Metrics & Analytics

// Get logging metrics
metrics := logger.GetMetrics()
fmt.Printf("Total logs: %d\n", metrics.TotalLogs)
fmt.Printf("Error rate: %.2f%%\n", metrics.ErrorRate)

// Reset metrics
logger.ResetMetrics()

πŸ§ͺ Testing & Examples

πŸ“ Comprehensive Examples

Example Description
Basic Logger Simple logging setup
File Logging File output with rotation
Caller Info Stack trace and caller information
JSON Logger Structured JSON logging
Theming Custom colors and themes
Localization Multi-language support
Hooks Custom hooks and filtering
Full Demo Complete feature showcase

Running Examples

# Run all examples
cd example/basic_logger && go run basic_logger.go
cd example/file_logging_demo && go run main.go
cd example/theming && go run main.go

# Run tests
go test ./...
go test -cover ./...

πŸ“š Documentation


πŸ”„ Compatibility

  • πŸš€ Modern APIs - New ergonomic, structured APIs for better developer experience
  • πŸ“¦ Easy Migration - Simple import path changes with comprehensive migration guide

🀝 Contributing

We welcome contributions! See our Contributing Guide for:


πŸ“„ License

MIT License - see LICENSE for details

Made with ❀️ by The Refactor Room community

GitHub stars GitHub forks