log

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 6 Imported by: 0

README

Log Package

Clean, pluggable logging package with dependency injection support.

Architecture

This package follows proper dependency injection principles:

  • logger.go - Core interface and field helpers
  • consoleLogger.go - Console output implementation
  • fileLogger.go - File output with rotation implementation
  • multiLogger.go - Combines multiple loggers

Configuration-driven (Primary approach):

// ✅ RECOMMENDED: Use viper configuration for logger creation
import (
    "scaffold/pkg/config"
    "github.com/spf13/viper"
)

// Load configuration and create logger
conf := config.NewConfig()  // Loads from config files
logger := config.CreateLoggerFromConfig(conf)

// Use the logger
logger.Info("Application started", log.String("env", "production"))

Configuration Format:

log:
  level: "debug"                    # debug, info, warn, error, fatal, panic
  console_logger:
    enabled: true
    colors: true                    # Enable colored output
    json_format: false              # Use structured JSON format
  file_logger:
    enabled: true
    directory: "logs"               # Directory for log files
    filename: "app.log"             # Log file name
    json_format: true               # JSON format for file logs
    max_size: 100                   # Max size in MB before rotation
    max_backups: 3                  # Number of backup files to keep
    max_age: 7                      # Days to keep old log files
    compress: true                  # Compress rotated files

Direct creation (Testing/Special cases only):

// Only use direct constructors for testing or special cases
logger := log.NewConsoleLogger(log.InfoLevel)

fileLogger := log.NewFileLogger(log.InfoLevel, &log.FileLoggerConfig{
    Filename:   "app.log",
    MaxSize:    100,
    MaxBackups: 3,
    MaxAge:     7,
    Compress:   true,
    JsonFormat: true,
})

multiLogger := log.NewMultiLogger(consoleLogger, fileLogger)

Structured Logging

// Use field helpers for structured logging
logger.Info("User logged in",
    log.String("user_id", "123"),
    log.String("ip", "192.168.1.1"),
    log.Duration("response_time", time.Millisecond*150),
    log.Any("metadata", map[string]string{"browser": "chrome"}),
)

// Create logger with persistent context
contextLogger := logger.WithFields(
    log.String("request_id", "req-456"),
    log.String("component", "auth"),
)
contextLogger.Error("Authentication failed", log.Error(err))

Benefits

  • Configuration-driven: Logger behavior controlled by config files
  • Pluggable: Easy to swap implementations
  • Framework-agnostic: No external framework dependencies
  • Clean interfaces: Simple dependency injection
  • Type-safe fields: Structured logging with helpers
  • Extensible: Easy to add new logger types (DataDog, LogDNA, etc.)
  • Zero allocations: Efficient logging with minimal overhead

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConsoleLogger

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

ConsoleLogger implements Logger interface for console output

func (*ConsoleLogger) Debug

func (l *ConsoleLogger) Debug(msg string, fields ...Field)

Debug logs a debug message

func (*ConsoleLogger) Error

func (l *ConsoleLogger) Error(msg string, fields ...Field)

Error logs an error message

func (*ConsoleLogger) Fatal

func (l *ConsoleLogger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message and exits

func (*ConsoleLogger) Info

func (l *ConsoleLogger) Info(msg string, fields ...Field)

Info logs an info message

func (*ConsoleLogger) Panic

func (l *ConsoleLogger) Panic(msg string, fields ...Field)

Panic logs a panic message and panics

func (*ConsoleLogger) Warn

func (l *ConsoleLogger) Warn(msg string, fields ...Field)

Warn logs a warning message

func (*ConsoleLogger) WithContext

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

WithContext creates a new logger with context (for future use with request tracing)

func (*ConsoleLogger) WithFields

func (l *ConsoleLogger) WithFields(fields ...Field) Logger

WithFields creates a new logger with additional context fields

type Field

type Field struct {
	Key   string
	Value any
}

Field represents a key-value pair for structured logging

func Any

func Any(key string, value any) Field

Any creates a field with any value

func Bool

func Bool(key string, value bool) Field

Bool creates a boolean field

func Duration

func Duration(key string, value time.Duration) Field

Duration creates a duration field

func Error

func Error(err error) Field

Error creates an error field

func Float64

func Float64(key string, value float64) Field

Float64 creates a float64 field

func Int

func Int(key string, value int) Field

Int creates an int field

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field

func String

func String(key, value string) Field

String creates a string field

func Time

func Time(key string, value time.Time) Field

Time creates a time field

type FileLogger

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

FileLogger implements Logger interface for file output with rotation

func (*FileLogger) Close

func (l *FileLogger) Close() error

Close closes the file logger and flushes any remaining logs

func (*FileLogger) Debug

func (l *FileLogger) Debug(msg string, fields ...Field)

Debug logs a debug message

func (*FileLogger) Error

func (l *FileLogger) Error(msg string, fields ...Field)

Error logs an error message

func (*FileLogger) Fatal

func (l *FileLogger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message and exits

func (*FileLogger) Info

func (l *FileLogger) Info(msg string, fields ...Field)

Info logs an info message

func (*FileLogger) Panic

func (l *FileLogger) Panic(msg string, fields ...Field)

Panic logs a panic message and panics

func (*FileLogger) Warn

func (l *FileLogger) Warn(msg string, fields ...Field)

Warn logs a warning message

func (*FileLogger) WithContext

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

WithContext creates a new logger with context

func (*FileLogger) WithFields

func (l *FileLogger) WithFields(fields ...Field) Logger

WithFields creates a new logger with additional context fields

type FileLoggerConfig

type FileLoggerConfig struct {
	Filename   string
	MaxSize    int  // megabytes
	MaxBackups int  // number of backups
	MaxAge     int  // days
	Compress   bool // compress rotated files
	JsonFormat bool // use JSON format
}

FileLoggerConfig contains configuration for file logging with rotation

type LogLevel

type LogLevel string

LogLevel represents different log levels

const (
	DebugLevel LogLevel = "debug"
	InfoLevel  LogLevel = "info"
	WarnLevel  LogLevel = "warn"
	ErrorLevel LogLevel = "error"
	FatalLevel LogLevel = "fatal"
	PanicLevel LogLevel = "panic"
)

type Logger

type Logger interface {
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)
	Panic(msg string, fields ...Field)

	WithFields(fields ...Field) Logger
	WithContext(ctx context.Context) Logger
}

Logger interface defines the logging contract This interface is framework-agnostic and can be implemented by any logger

func NewConsoleLogger

func NewConsoleLogger(level LogLevel) Logger

NewConsoleLogger creates a new console logger with specified level

func NewConsoleLoggerWithWriter

func NewConsoleLoggerWithWriter(level LogLevel, writer io.Writer, colorized bool) Logger

NewConsoleLoggerWithWriter creates a console logger with custom writer and colorization

func NewFileLogger

func NewFileLogger(level LogLevel, config *FileLoggerConfig) Logger

NewFileLogger creates a new file logger with rotation

func NewMultiLogger

func NewMultiLogger(loggers ...Logger) Logger

NewMultiLogger creates a new multi-logger that forwards to multiple logger implementations

type MultiLogger

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

MultiLogger implements Logger interface and forwards logs to multiple loggers This allows combining console and file logging or any other logger implementations

func (*MultiLogger) Debug

func (m *MultiLogger) Debug(msg string, fields ...Field)

Debug logs a debug message to all underlying loggers

func (*MultiLogger) Error

func (m *MultiLogger) Error(msg string, fields ...Field)

Error logs an error message to all underlying loggers

func (*MultiLogger) Fatal

func (m *MultiLogger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message to all underlying loggers and exits

func (*MultiLogger) Info

func (m *MultiLogger) Info(msg string, fields ...Field)

Info logs an info message to all underlying loggers

func (*MultiLogger) Panic

func (m *MultiLogger) Panic(msg string, fields ...Field)

Panic logs a panic message to all underlying loggers and panics

func (*MultiLogger) Warn

func (m *MultiLogger) Warn(msg string, fields ...Field)

Warn logs a warning message to all underlying loggers

func (*MultiLogger) WithContext

func (m *MultiLogger) WithContext(ctx context.Context) Logger

WithContext creates a new multi-logger with context

func (*MultiLogger) WithFields

func (m *MultiLogger) WithFields(fields ...Field) Logger

WithFields creates a new multi-logger with additional context fields

Jump to

Keyboard shortcuts

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