Documentation
¶
Overview ¶
Package slog provides structured logging with asynchronous output and flexible configuration.
This package wraps Go's standard log/slog with additional features including asynchronous logging, file rotation, multiple output destinations, and caller information tracking.
Features:
- Structured logging with key-value pairs
- Multiple log levels (Trace, Debug, Info, Warn, Error, Fatal)
- Asynchronous logging with queue-based buffering
- Output to stdout, stderr, or files
- Daily log file rotation
- Caller information tracking
- Thread-safe operations
Example:
var logger slog.Log
logger.SetLevel(slog.LevelInfo)
logger.SetOutputToFile("app", "log", true)
logger.Info("Server started", "port", 8080)
logger.Flush()
Index ¶
- Constants
- type Level
- type Log
- func (l *Log) Debug(message string, arguments ...any)
- func (l *Log) Error(message string, arguments ...any)
- func (l *Log) Fatal(message string, arguments ...any)
- func (l *Log) Flush()
- func (l *Log) GetLevel() Level
- func (l *Log) Info(message string, arguments ...any)
- func (l *Log) SetLevel(level Level)
- func (l *Log) SetOutputToFile(fileName, fileExtensionName string, addDate bool)
- func (l *Log) SetOutputToStderr()
- func (l *Log) SetOutputToStdout()
- func (l *Log) SetWithCallerInfo(withCallerInfo bool)
- func (l *Log) Trace(message string, arguments ...any)
- func (l *Log) Warn(message string, arguments ...any)
Constants ¶
const ( LevelTrace = Level(-8) LevelDebug = Level(slog.LevelDebug) LevelInfo = Level(slog.LevelInfo) LevelWarn = Level(slog.LevelWarn) LevelError = Level(slog.LevelError) LevelFatal = Level(12) )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Log ¶
type Log struct {
// contains filtered or unexported fields
}
Log is struct that provides log related methods.
func (*Log) Debug ¶
Debug logs a message at debug level with optional key-value pairs.
Debug level is used for detailed diagnostic information useful during development and troubleshooting.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
Example:
var logger slog.Log
logger.Debug("Query executed", "sql", "SELECT * FROM users", "duration", 45)
Example with error context:
logger.Debug("Retrying connection",
"attempt", 2,
"maxAttempts", 3,
"error", lastErr.Error(),
)
func (*Log) Error ¶
Error logs a message at error level with optional key-value pairs.
Error level is used for errors that prevent specific operations from completing successfully but don't crash the application.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
Example:
var logger slog.Log
logger.Error("Failed to save user", "userID", 123, "error", err.Error())
Example with context:
logger.Error("API request failed",
"endpoint", "/api/users",
"method", "POST",
"statusCode", 500,
"error", err.Error(),
)
func (*Log) Fatal ¶
Fatal logs a message at fatal level with optional key-value pairs.
Fatal level indicates critical errors that require immediate attention. Note: Unlike some logging libraries, this does NOT terminate the application.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
Example:
var logger slog.Log
logger.Fatal("Database connection lost", "error", err.Error())
Example for critical failures:
logger.Fatal("Configuration file corrupt",
"file", "config.yaml",
"error", err.Error(),
"action", "manual intervention required",
)
func (*Log) Flush ¶
func (l *Log) Flush()
Flush blocks until all queued log entries are written.
This method ensures all pending asynchronous log writes are completed before returning. It's essential to call this before application shutdown to ensure no logs are lost.
Behavior:
- Blocks the calling goroutine until all queued logs are written
- Processes the internal logging queue completely
- Thread-safe and can be called concurrently
Example at application shutdown:
var logger slog.Log
defer logger.Flush()
logger.Info("Application starting")
// ... application logic ...
logger.Info("Application shutting down")
// Flush ensures shutdown message is written
Example in tests:
func TestLogging(t *testing.T) {
var logger slog.Log
logger.SetOutputToFile("test", "log", false)
logger.Info("Test message")
logger.Flush() // Ensure log is written before test ends
// Verify log file contents
}
func (*Log) GetLevel ¶
GetLevel returns the current minimum log level.
Returns:
- Level: Current log level threshold
Only log messages at or above this level will be written. The returned value is one of: LevelTrace, LevelDebug, LevelInfo, LevelWarn, LevelError, or LevelFatal.
Example:
var logger slog.Log
currentLevel := logger.GetLevel()
if currentLevel == slog.LevelDebug {
fmt.Println("Debug logging is enabled")
}
Example for conditional logging:
if logger.GetLevel() <= slog.LevelDebug {
// Perform expensive debug data collection
debugData := collectDebugInfo()
logger.Debug("Debug info", "data", debugData)
}
func (*Log) Info ¶
Info logs a message at info level with optional key-value pairs.
Info level is used for general informational messages about application operation, such as startup, shutdown, and significant state changes.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
Example:
var logger slog.Log
logger.Info("Server started", "port", 8080, "environment", "production")
Example for lifecycle events:
logger.Info("Database connection established",
"host", "localhost",
"database", "myapp",
"poolSize", 10,
)
func (*Log) SetLevel ¶
SetLevel sets the minimum log level threshold.
Parameters:
- level: New minimum log level (LevelTrace, LevelDebug, LevelInfo, LevelWarn, LevelError, LevelFatal)
Only log messages at or above this level will be written. This operation is asynchronous and queued for processing.
Example:
var logger slog.Log
logger.SetLevel(slog.LevelInfo)
logger.Debug("This will not be logged")
logger.Info("This will be logged")
Example for dynamic level adjustment:
if os.Getenv("DEBUG") == "true" {
logger.SetLevel(slog.LevelDebug)
} else {
logger.SetLevel(slog.LevelInfo)
}
Example for production:
logger.SetLevel(slog.LevelWarn) // Only warnings and errors in production
func (*Log) SetOutputToFile ¶
SetOutputToFile configures logging output to a file.
Parameters:
- fileName: Base name of the log file (without extension)
- fileExtensionName: File extension (e.g., "log", "txt")
- addDate: If true, appends current date (YYYYMMDD) to filename
Behavior:
- Creates or appends to the specified file
- If addDate is true, filename becomes: fileName_YYYYMMDD.extension
- If addDate is false, filename becomes: fileName.extension
- Automatic daily rotation when addDate is true
- Falls back to stdout if file cannot be opened
- Logs are written in JSON format
Example without date:
var logger slog.Log
logger.SetOutputToFile("application", "log", false)
// Writes to: application.log
Example with daily rotation:
logger.SetOutputToFile("app", "log", true)
// Writes to: app_20231218.log
// Automatically creates new file next day: app_20231219.log
Example for different environments:
env := os.Getenv("ENV")
logger.SetOutputToFile(env+"-app", "log", true)
// production-app_20231218.log or development-app_20231218.log
func (*Log) SetOutputToStderr ¶
func (l *Log) SetOutputToStderr()
SetOutputToStderr configures logging output to standard error.
All subsequent log messages will be written to stderr (os.Stderr). This operation is asynchronous and queued for processing.
Behavior:
- Switches output destination to stderr
- Maintains current log level
- Logs are written in JSON format
Example:
var logger slog.Log
logger.SetOutputToStderr()
logger.Error("This goes to stderr")
Example for error-only logging:
errorLogger := &slog.Log{}
errorLogger.SetOutputToStderr()
errorLogger.SetLevel(slog.LevelError)
func (*Log) SetOutputToStdout ¶
func (l *Log) SetOutputToStdout()
SetOutputToStdout configures logging output to standard output.
All subsequent log messages will be written to stdout (os.Stdout). This operation is asynchronous and queued for processing.
Behavior:
- Switches output destination to stdout
- Maintains current log level
- Logs are written in JSON format
Example:
var logger slog.Log
logger.SetOutputToStdout()
logger.Info("This goes to stdout")
Example for development:
if os.Getenv("ENV") == "development" {
logger.SetOutputToStdout()
} else {
logger.SetOutputToFile("app", "log", true)
}
func (*Log) SetWithCallerInfo ¶
SetWithCallerInfo enables or disables caller information in log entries.
Parameters:
- withCallerInfo: If true, includes file name, line number, and function name in logs
When enabled, each log entry will include a "CallerInfo" field with:
- File: Source file name
- Line: Line number
- Function: Function name
This operation is asynchronous and queued for processing.
Example:
var logger slog.Log
logger.SetWithCallerInfo(true)
logger.Info("User logged in", "userID", 123)
// Log includes: {"CallerInfo":{"File":"main.go","Line":45,"Function":"handleLogin"},...}
Example for debugging:
if os.Getenv("DEBUG") == "true" {
logger.SetWithCallerInfo(true) // Enable in debug mode
} else {
logger.SetWithCallerInfo(false) // Disable in production for performance
}
func (*Log) Trace ¶
Trace logs a message at trace level with optional key-value pairs.
Trace is the lowest log level, typically used for very detailed debugging information that is rarely needed in production.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
The arguments are interpreted as alternating keys and values. Keys should be strings, values can be any type.
Example:
var logger slog.Log
logger.Trace("Function entered", "function", "processData", "params", 3)
Example with multiple pairs:
logger.Trace("Processing request",
"requestID", "req-123",
"userID", 456,
"timestamp", time.Now(),
)
func (*Log) Warn ¶
Warn logs a message at warning level with optional key-value pairs.
Warn level indicates potentially harmful situations that don't prevent the application from functioning but should be investigated.
Parameters:
- message: The log message
- arguments: Optional key-value pairs (must be even number of arguments)
Example:
var logger slog.Log
logger.Warn("High memory usage", "used", "85%", "threshold", "80%")
Example for degraded performance:
logger.Warn("Slow query detected",
"query", "SELECT * FROM large_table",
"duration", "5.2s",
"threshold", "1s",
)