Documentation
¶
Overview ¶
Package gourdianlogger provides a high-performance, feature-rich logging utility for Go applications.
GourdianLogger supports the following features:
- Multiple log levels (DEBUG, INFO, WARN, ERROR, FATAL)
- Structured logging with custom fields
- Configurable log formats (plain text or JSON)
- Asynchronous logging with worker pools
- Log file rotation by size or time
- Gzip compression of rotated logs
- Rate limiting (max logs per second)
- Sampling (log 1 in N messages)
- Caller tracing (file:line:function)
- Environment-based overrides
- Pluggable error handling and dynamic log level control
GourdianLogger is designed for production use, with thread-safe operations and high configurability.
Basic Usage ¶
import "github.com/your/module/gourdianlogger"
func main() {
logger, err := gourdianlogger.NewGourdianLogger(gourdianlogger.DefaultConfig())
if err != nil {
log.Fatal(err)
}
defer logger.Close()
logger.Info("App started")
logger.Warnf("Using fallback value: %s", fallback)
}
JSON Configuration ¶
You can configure the logger via JSON string using `WithConfig`:
jsonCfg := `{
"filename": "app",
"log_level": "info",
"format": "json",
"max_bytes": 1048576,
"compress_backups": true
}`
logger, err := gourdianlogger.WithConfig(jsonCfg)
Environment Overrides ¶
The following environment variables can override config values:
- LOG_LEVEL → replaces LogLevelStr
- LOG_FORMAT → replaces FormatStr
- LOG_DIR → replaces LogsDir
- LOG_RATE → replaces MaxLogRate
Example:
// Will override log level even if LoggerConfig.LogLevelStr is set to "debug"
os.Setenv("LOG_LEVEL", "error")
Log Levels ¶
Log levels filter what gets output. For example, setting `LogLevel = INFO` will ignore all DEBUG logs.
Constants:
- gourdianlogger.DEBUG
- gourdianlogger.INFO
- gourdianlogger.WARN
- gourdianlogger.ERROR
- gourdianlogger.FATAL
Example:
logger.SetLogLevel(gourdianlogger.WARN)
logger.Debug("This will be skipped")
logger.Warn("This will be printed")
Log Formats ¶
Log output can be formatted as plain text or JSON.
Example JSON log:
{
"timestamp": "2025-04-18 17:00:00.123456",
"level": "INFO",
"message": "Server started",
"service": "api"
}
Use `FormatConfig.PrettyPrint = true` for indented JSON.
Rotation ¶
Supports both size-based and time-based rotation.
- Size-based: when the log file exceeds `MaxBytes`
- Time-based: rotates every `RotationTime` (e.g., `time.Hour`)
Rotated files follow the pattern: `filename_YYYYMMDD_HHMMSS.log` If `CompressBackups` is true, they are compressed as `.log.gz`
Structured Logging ¶
You can attach custom fields using `WithFields` or `*fWithFields` variants:
logger.InfofWithFields(map[string]interface{}{
"user_id": uid,
"event": "login",
}, "User authenticated")
Asynchronous Logging ¶
Enable async logging by setting `BufferSize > 0`. This uses a buffered channel + worker pool for non-blocking writes.
logger := gourdianlogger.LoggerConfig{
BufferSize: 500,
AsyncWorkers: 3,
}
Ensure `logger.Flush()` is called before shutdown to prevent log loss.
Sampling ¶
Sampling logs 1 in N messages (useful in high-frequency systems). Example:
logger.SampleRate = 10 // log 1 of every 10 messages
Rate Limiting ¶
`MaxLogRate` limits logs per second. Useful for spammy components.
logger.MaxLogRate = 100 // max 100 logs/sec
Custom Error Handler ¶
Customize what happens when logging errors occur:
logger.ErrorHandler = func(err error) {
metrics.Increment("log_error")
fallbackLogger.Error("Logging failed: ", err)
}
Dynamic Log Level ¶
You can change the active log level dynamically:
logger.SetDynamicLevelFunc(func() gourdianlogger.LogLevel {
if os.Getenv("DEBUG_MODE") == "true" {
return gourdianlogger.DEBUG
}
return gourdianlogger.INFO
})
Shutdown ¶
Always call `logger.Close()` before your application exits to flush logs:
defer logger.Close()
Testing Tip ¶
To disable file output during unit tests:
config := gourdianlogger.DefaultConfig()
config.Outputs = []io.Writer{gourdianlogger.StdoutOnly()} // or custom buffer
config.Filename = ""
config.LogsDir = ""
Index ¶
- Variables
- type FormatConfig
- type LogFormat
- type LogLevel
- type Logger
- func (l *Logger) AddOutput(output io.Writer)
- func (l *Logger) Close() error
- func (l *Logger) Debug(v ...interface{})
- func (l *Logger) DebugWithFields(fields map[string]interface{}, v ...interface{})
- func (l *Logger) Debugf(format string, v ...interface{})
- func (l *Logger) DebugfWithFields(fields map[string]interface{}, format string, v ...interface{})
- func (l *Logger) Error(v ...interface{})
- func (l *Logger) ErrorWithFields(fields map[string]interface{}, v ...interface{})
- func (l *Logger) Errorf(format string, v ...interface{})
- func (l *Logger) ErrorfWithFields(fields map[string]interface{}, format string, v ...interface{})
- func (l *Logger) Fatal(v ...interface{})
- func (l *Logger) FatalWithFields(fields map[string]interface{}, v ...interface{})
- func (l *Logger) Fatalf(format string, v ...interface{})
- func (l *Logger) FatalfWithFields(fields map[string]interface{}, format string, v ...interface{})
- func (l *Logger) Flush()
- func (l *Logger) GetLogLevel() LogLevel
- func (l *Logger) Info(v ...interface{})
- func (l *Logger) InfoWithFields(fields map[string]interface{}, v ...interface{})
- func (l *Logger) Infof(format string, v ...interface{})
- func (l *Logger) InfofWithFields(fields map[string]interface{}, format string, v ...interface{})
- func (l *Logger) IsClosed() bool
- func (l *Logger) RemoveOutput(output io.Writer)
- func (l *Logger) SetDynamicLevelFunc(fn func() LogLevel)
- func (l *Logger) SetLogLevel(level LogLevel)
- func (l *Logger) Warn(v ...interface{})
- func (l *Logger) WarnWithFields(fields map[string]interface{}, v ...interface{})
- func (l *Logger) Warnf(format string, v ...interface{})
- func (l *Logger) WarnfWithFields(fields map[string]interface{}, format string, v ...interface{})
- type LoggerConfig
Constants ¶
This section is empty.
Variables ¶
var Version = "v0.0.2"
Functions ¶
This section is empty.
Types ¶
type FormatConfig ¶
type FormatConfig struct {
PrettyPrint bool `json:"pretty_print"` // For human-readable JSON
CustomFields map[string]interface{} `json:"custom_fields"` // Custom fields to include
}
FormatConfig contains additional formatting options.
Fields:
PrettyPrint - Whether to pretty-print JSON output with indentation CustomFields - Additional key-value pairs to include in every log message
Example:
FormatConfig{
PrettyPrint: true,
CustomFields: map[string]interface{}{
"app": "myapp",
"env": "production",
},
}
type LogFormat ¶
type LogFormat int
LogFormat specifies the output format for log messages.
Supported formats:
FormatPlain - Human-readable text format with timestamp, level, message FormatJSON - Structured JSON format with additional metadata
Example:
config := DefaultConfig() config.Format = gourdianlogger.FormatJSON
type LogLevel ¶
type LogLevel int32
LogLevel represents the severity levels for log messages in increasing order of severity. The logger will only output messages at or above the currently set log level.
Levels:
DEBUG - Detailed debug information (most verbose) INFO - General operational messages about application flow WARN - Potentially harmful situations that aren't errors ERROR - Error events that might still allow the application to continue FATAL - Severe errors that will prevent the application from continuing (will call os.Exit(1))
Example:
logger.SetLogLevel(gourdianlogger.INFO) // Will log INFO, WARN, ERROR, FATAL
func ParseLogLevel ¶
ParseLogLevel converts a string representation to a LogLevel. Case-insensitive. Supports both full names and abbreviations.
Parameters:
level: String representation ("DEBUG", "INFO", "WARN", "ERROR", "FATAL")
Returns:
LogLevel: Corresponding log level constant error: If the string doesn't match any level
Example:
level, err := ParseLogLevel("info")
if err != nil {
return fmt.Errorf("invalid log level: %w", err)
}
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is the main logging instance that provides thread-safe logging capabilities. It supports both synchronous and asynchronous logging, log rotation, multiple output destinations, and structured logging.
Create an instance using:
- NewGourdianLogger()
- NewGourdianLoggerWithDefault()
- WithConfig()
func NewGourdianLogger ¶
func NewGourdianLogger(config LoggerConfig) (*Logger, error)
NewGourdianLogger creates a new logger instance with the specified configuration.
Parameters:
config: Logger configuration (see LoggerConfig)
Returns:
*Logger: The created logger instance error: Any error that occurred during initialization
Example:
config := LoggerConfig{
Filename: "myapp",
LogLevel: gourdianlogger.INFO,
}
logger, err := NewGourdianLogger(config)
if err != nil {
log.Fatal("Failed to create logger:", err)
}
defer logger.Close()
func NewGourdianLoggerWithDefault ¶
NewGourdianLoggerWithDefault creates a new logger with default configuration. This is a convenience function for quick initialization.
Returns:
*Logger: Logger instance with default settings error: Any initialization error
Example:
logger, err := NewGourdianLoggerWithDefault()
if err != nil {
log.Fatal(err)
}
defer logger.Close()
func WithConfig ¶
WithConfig creates a logger from a JSON configuration string. Useful for loading configuration from files or environment variables.
Parameters:
jsonConfig: JSON string containing logger configuration
Returns:
*Logger: New logger instance error: Any parsing or initialization error
Example:
const configJSON = `{
"filename": "myapp",
"log_level": "info",
"max_bytes": 5000000,
"format": "json"
}`
logger, err := WithConfig(configJSON)
func (*Logger) AddOutput ¶
AddOutput adds an additional output destination for log messages. Supports any io.Writer such as files, network connections, etc.
Parameters:
output: The io.Writer to add as output
Example:
// Log to both console and file
file, _ := os.Create("app.log")
logger.AddOutput(file)
func (*Logger) Close ¶
Close gracefully shuts down the logger, ensuring all buffered logs are written. Should be called before application exit to prevent log loss.
Returns:
error: Any error that occurred during shutdown
Example:
defer logger.Close()
func (*Logger) Debug ¶
func (l *Logger) Debug(v ...interface{})
Debug logs a message at DEBUG level. Use for detailed debug information that is typically only needed during development. Messages are concatenated with spaces like fmt.Sprint.
Parameters:
v: Values to log (any number of parameters, concatenated with spaces)
Example:
logger.Debug("Current state:", state, "value:", value)
Output: "Current state: running value: 42"
func (*Logger) DebugWithFields ¶
DebugWithFields logs a message with additional structured fields at DEBUG level. Fields are included in both plain and JSON formats.
Parameters:
fields: Key-value pairs of additional context (map[string]interface{})
v: Values to log (concatenated with spaces)
Example:
logger.DebugWithFields(map[string]interface{}{
"user": "john",
"action": "login",
"success": true,
}, "Authentication attempt")
func (*Logger) Debugf ¶
Debugf logs a formatted message at DEBUG level. Supports all formatting verbs from fmt.Sprintf.
Parameters:
format: Format string (supports %v, %s, %d etc.) v: Values to interpolate into the format string
Example:
logger.Debugf("User %s (ID: %d) logged in", username, userID)
func (*Logger) DebugfWithFields ¶
DebugfWithFields combines formatted messages with structured logging at DEBUG level.
Parameters:
fields: Additional context as key-value pairs format: Format string (supports %v, %s etc.) v: Values to interpolate into format string
Example:
logger.DebugfWithFields(map[string]interface{}{
"duration_ms": 45,
"method": "GET",
}, "Request processed in %dms", 45)
func (*Logger) Error ¶
func (l *Logger) Error(v ...interface{})
Error logs a message at ERROR level. Use for error events that might still allow the application to continue.
Parameters:
v: Values to log (concatenated with spaces)
Example:
logger.Error("Failed to connect to database:", err)
func (*Logger) ErrorWithFields ¶
ErrorWithFields logs a message with additional fields at ERROR level.
Parameters:
fields: Additional context v: Values to log
Example:
logger.ErrorWithFields(map[string]interface{}{
"function": "processPayment",
"order_id": orderID,
}, "Payment processing failed")
func (*Logger) Errorf ¶
Errorf logs a formatted message at ERROR level.
Parameters:
format: Format string v: Values to interpolate
Example:
logger.Errorf("Failed to process request: %v", err)
func (*Logger) ErrorfWithFields ¶
ErrorfWithFields combines formatted messages with structured logging at ERROR level.
Parameters:
fields: Additional context format: Format string v: Values to interpolate
Example:
logger.ErrorfWithFields(map[string]interface{}{
"request_id": reqID,
}, "Failed to process request %s", reqID)
func (*Logger) Fatal ¶
func (l *Logger) Fatal(v ...interface{})
Fatal logs a message at FATAL level and exits the program with status 1. Use for severe errors that prevent the application from continuing. Automatically flushes any buffered logs before exiting.
Parameters:
v: Values to log (concatenated with spaces)
Example:
logger.Fatal("Cannot start - required service unavailable")
func (*Logger) FatalWithFields ¶
FatalWithFields logs a message with additional fields at FATAL level and exits. Automatically flushes any buffered logs before exiting.
Parameters:
fields: Additional context v: Values to log
Example:
logger.FatalWithFields(map[string]interface{}{
"error_code": 5001,
"component": "database",
}, "Critical database failure")
func (*Logger) Fatalf ¶
Fatalf logs a formatted message at FATAL level and exits the program. Automatically flushes any buffered logs before exiting.
Parameters:
format: Format string v: Values to interpolate
Example:
logger.Fatalf("Critical error: %v - shutting down", criticalErr)
func (*Logger) FatalfWithFields ¶
FatalfWithFields combines formatted messages with structured logging at FATAL level and exits. Automatically flushes any buffered logs before exiting.
Parameters:
fields: Additional context format: Format string v: Values to interpolate
Example:
logger.FatalfWithFields(map[string]interface{}{
"error_code": 5001,
}, "Critical error %d occurred", errCode)
func (*Logger) Flush ¶
func (l *Logger) Flush()
Flush ensures all buffered logs are written to output. Only needed when using async logging (BufferSize > 0). Automatically called by Close().
Example:
// Before exiting ensure all logs are written logger.Flush()
func (*Logger) GetLogLevel ¶
GetLogLevel returns the current minimum log level.
Returns:
LogLevel: The current minimum log level
Example:
if logger.GetLogLevel() == gourdianlogger.DEBUG {
// Perform debug-specific actions
}
func (*Logger) Info ¶
func (l *Logger) Info(v ...interface{})
Info logs a message at INFO level. Use for general operational messages about application flow.
Parameters:
v: Values to log (concatenated with spaces)
Example:
logger.Info("Server started on port", port)
func (*Logger) InfoWithFields ¶
InfoWithFields logs a message with additional fields at INFO level.
Parameters:
fields: Additional context as key-value pairs v: Values to log
Example:
logger.InfoWithFields(map[string]interface{}{
"request_id": reqID,
"duration": duration,
}, "Request processed")
func (*Logger) Infof ¶
Infof logs a formatted message at INFO level.
Parameters:
format: Format string v: Values to interpolate
Example:
logger.Infof("Processing %d records took %v", count, duration)
func (*Logger) InfofWithFields ¶
InfofWithFields combines formatted messages with structured logging at INFO level.
Parameters:
fields: Additional context format: Format string v: Values to interpolate
Example:
logger.InfofWithFields(map[string]interface{}{
"user_count": count,
}, "Processed %d users", count)
func (*Logger) IsClosed ¶
IsClosed checks if the logger has been closed.
Returns:
bool: true if the logger is closed, false otherwise
Example:
if !logger.IsClosed() {
logger.Info("Application shutting down")
logger.Close()
}
func (*Logger) RemoveOutput ¶
RemoveOutput removes an output destination from the logger.
Parameters:
output: The io.Writer to remove
Example:
logger.RemoveOutput(os.Stdout) // Stop logging to console
func (*Logger) SetDynamicLevelFunc ¶
SetDynamicLevelFunc sets a function that dynamically determines the log level. The function is called for each log message to check if it should be logged. Useful for implementing runtime log level changes without locks.
Parameters:
fn: Function that returns the current log level
Example:
logger.SetDynamicLevelFunc(func() gourdianlogger.LogLevel {
if isDebugMode() {
return gourdianlogger.DEBUG
}
return gourdianlogger.INFO
})
func (*Logger) SetLogLevel ¶
SetLogLevel dynamically changes the minimum log level at runtime. Messages below this level will be ignored.
Parameters:
level: New minimum log level (DEBUG, INFO, WARN, ERROR, FATAL)
Example:
// Only log warnings and above in production
if isProduction() {
logger.SetLogLevel(gourdianlogger.WARN)
}
func (*Logger) Warn ¶
func (l *Logger) Warn(v ...interface{})
Warn logs a message at WARN level. Use for potentially harmful situations that aren't errors.
Parameters:
v: Values to log (concatenated with spaces)
Example:
logger.Warn("Disk space below 10%")
func (*Logger) WarnWithFields ¶
WarnWithFields logs a message with additional fields at WARN level.
Parameters:
fields: Additional context v: Values to log
Example:
logger.WarnWithFields(map[string]interface{}{
"threshold": 90,
"current": usage,
}, "Resource usage high")
func (*Logger) Warnf ¶
Warnf logs a formatted message at WARN level.
Parameters:
format: Format string v: Values to interpolate
Example:
logger.Warnf("High latency detected: %.2fms", latencyMs)
func (*Logger) WarnfWithFields ¶
WarnfWithFields combines formatted messages with structured logging at WARN level.
Parameters:
fields: Additional context format: Format string v: Values to interpolate
Example:
logger.WarnfWithFields(map[string]interface{}{
"threshold": 90,
}, "CPU usage at %d%%", usage)
type LoggerConfig ¶
type LoggerConfig struct {
Filename string `json:"filename"` // Base filename for logs
MaxBytes int64 `json:"max_bytes"` // Max file size before rotation
BackupCount int `json:"backup_count"` // Number of backups to keep
LogLevelStr string `json:"log_level"` // Log level as string (for config)
TimestampFormat string `json:"timestamp_format"` // Custom timestamp format
LogsDir string `json:"logs_dir"` // Directory for log files
EnableCaller bool `json:"enable_caller"` // Include caller info
BufferSize int `json:"buffer_size"` // Buffer size for async logging
AsyncWorkers int `json:"async_workers"` // Number of async workers
FormatStr string `json:"format"` // Format as string (for config)
FormatConfig FormatConfig `json:"format_config"` // Format-specific config
EnableFallback bool `json:"enable_fallback"` // Whether to use fallback logging
MaxLogRate int `json:"max_log_rate"` // Max logs per second (0 for unlimited)
CompressBackups bool `json:"compress_backups"` // Whether to gzip rotated logs
RotationTime time.Duration `json:"rotation_time"` // Time-based rotation interval
SampleRate int `json:"sample_rate"` // Log sampling rate (1 in N)
CallerDepth int `json:"caller_depth"` // How many stack frames to skip
LogLevel LogLevel `json:"-"` // Minimum log level (internal use)
Outputs []io.Writer `json:"-"` // Additional outputs
Format LogFormat `json:"-"` // Log message format (internal use)
ErrorHandler func(error) `json:"-"` // Custom error handler
}
LoggerConfig contains all configurable parameters for the logger. Used when creating a new logger instance via NewGourdianLogger().
Fields:
Filename - Base name for log files (without extension) MaxBytes - Maximum log file size in bytes before rotation (default 10MB) BackupCount - Number of rotated log files to keep (default 5) LogLevel - Minimum log level to output (default DEBUG) TimestampFormat - Custom timestamp format (default "2006-01-02 15:04:05.000000") LogsDir - Directory to store log files (default "logs") EnableCaller - Whether to include caller information (file:line:function) BufferSize - Size of async buffer (0 for synchronous logging) AsyncWorkers - Number of async worker goroutines (default 1) Format - Output format (plain or JSON) FormatConfig - Format-specific configuration EnableFallback - Whether to use stderr fallback on write errors MaxLogRate - Maximum logs per second (0 for unlimited) CompressBackups - Whether to gzip rotated log files RotationTime - Time-based rotation interval (0 to disable) SampleRate - Log sampling rate (1 logs every N messages) CallerDepth - Number of stack frames to skip for caller info
Example:
config := LoggerConfig{
Filename: "myapp",
MaxBytes: 50 * 1024 * 1024, // 50MB
LogLevel: gourdianlogger.INFO,
Format: gourdianlogger.FormatJSON,
FormatConfig: FormatConfig{
PrettyPrint: true,
},
}
func DefaultConfig ¶
func DefaultConfig() LoggerConfig
DefaultConfig returns a LoggerConfig with sensible default values.
Default values:
Filename: "app" MaxBytes: 10MB BackupCount: 5 LogLevel: DEBUG TimestampFormat: "2006-01-02 15:04:05.000000" LogsDir: "logs" EnableCaller: true BufferSize: 0 (synchronous) AsyncWorkers: 1 Format: FormatPlain EnableFallback: true MaxLogRate: 0 (unlimited) CompressBackups: false RotationTime: 0 (disabled) SampleRate: 1 (no sampling) CallerDepth: 3
Example:
config := DefaultConfig() config.Filename = "myapp" logger, err := NewGourdianLogger(config)
func (*LoggerConfig) ApplyEnvOverrides ¶
func (lc *LoggerConfig) ApplyEnvOverrides()
ApplyEnvOverrides applies environment variable overrides to the config
func (*LoggerConfig) UnmarshalJSON ¶
func (lc *LoggerConfig) UnmarshalJSON(data []byte) error
func (*LoggerConfig) Validate ¶
func (lc *LoggerConfig) Validate() error
Validate checks the LoggerConfig for valid values