Documentation
¶
Overview ¶
Package loggergo provides a lightweight, customizable logging library for Go applications.
LoggerGo is built on top of Go's standard log/slog package and provides:
- Multiple output modes (console, OpenTelemetry, fanout)
- Multiple log formats (JSON, text, OTEL)
- Development mode with different flavors (tint, slogor, devslog)
- Context-aware logging with automatic value extraction
- OpenTelemetry integration with trace/span ID injection
- Dynamic log level adjustment
- Thread-safe configuration management
- Comprehensive error handling with graceful degradation
Quick Start:
import (
"context"
"log/slog"
"github.com/wasilak/loggergo"
)
func main() {
ctx := context.Background()
config := loggergo.Config{
Level: slog.LevelInfo,
Format: loggergo.LogFormatJSON,
Output: loggergo.OutputConsole,
}
ctx, logger, err := loggergo.Init(ctx, config)
if err != nil {
panic(err)
}
logger.Info("Hello, LoggerGo!")
}
For more examples, see the examples/ directory in the repository.
Index ¶
- Variables
- func GetConfig() types.Config
- func GetLogLevelAccessor() *slog.LevelVar
- func Init(ctx context.Context, config types.Config, additionalAttrs ...any) (retCtx context.Context, retLogger *slog.Logger, retErr error)
- func Shutdown() error
- type Config
- type CustomContextAttributeHandler
- func (h *CustomContextAttributeHandler) Enabled(ctx context.Context, level slog.Level) bool
- func (h *CustomContextAttributeHandler) Handle(ctx context.Context, record slog.Record) (err error)
- func (h *CustomContextAttributeHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *CustomContextAttributeHandler) WithGroup(name string) slog.Handler
Constants ¶
This section is empty.
Variables ¶
var Types = struct { AllDevFlavors func() []types.DevFlavor DevFlavorFromString func(string) types.DevFlavor DevFlavorTint types.DevFlavor DevFlavorSlogor types.DevFlavor DevFlavorDevslog types.DevFlavor AllLogFormats func() []types.LogFormat LogFormatFromString func(string) types.LogFormat LogFormatText types.LogFormat LogFormatJSON types.LogFormat LogFormatOtel types.LogFormat AllLogLevels func() []slog.Level LogLevelFromString func(string) slog.Level AllOutputTypes func() []types.OutputType OutputTypeFromString func(string) types.OutputType OutputConsole types.OutputType OutputOtel types.OutputType OutputFanout types.OutputType }{ AllDevFlavors: types.AllDevFlavors, DevFlavorFromString: types.DevFlavorFromString, DevFlavorTint: types.DevFlavorTint, DevFlavorSlogor: types.DevFlavorSlogor, DevFlavorDevslog: types.DevFlavorDevslog, AllLogFormats: types.AllLogFormats, LogFormatFromString: types.LogFormatFromString, LogFormatText: types.LogFormatText, LogFormatJSON: types.LogFormatJSON, LogFormatOtel: types.LogFormatOtel, AllLogLevels: types.AllLogLevels, LogLevelFromString: types.LogLevelFromString, AllOutputTypes: types.AllOutputTypes, OutputTypeFromString: types.OutputTypeFromString, OutputConsole: types.OutputConsole, OutputOtel: types.OutputOtel, OutputFanout: types.OutputFanout, }
Types provides access to all type constants, enums, and conversion functions.
This struct exports all the type-related functionality from the internal types package, making it easy to access log formats, output types, dev flavors, and their conversion functions.
Example usage:
// Using constants
config := loggergo.Config{
Format: loggergo.Types.LogFormatJSON,
Output: loggergo.Types.OutputConsole,
DevFlavor: loggergo.Types.DevFlavorTint,
}
// Using conversion functions
format := loggergo.Types.LogFormatFromString("json")
output := loggergo.Types.OutputTypeFromString("console")
// Getting all available values
allFormats := loggergo.Types.AllLogFormats()
for _, format := range allFormats {
fmt.Println(format)
}
Functions ¶
func GetConfig ¶ added in v1.8.0
GetConfig returns the current logger configuration. This function is thread-safe and returns a copy of the configuration.
func GetLogLevelAccessor ¶ added in v1.5.5
GetLogLevelAccessor returns the log level accessor for dynamic level changes.
Thread-Safety Guarantees: This function is safe for concurrent use. The returned *slog.LevelVar uses atomic operations internally, making it safe to call Set() and Level() methods from multiple goroutines simultaneously without additional synchronization.
Example usage:
levelVar := loggergo.GetLogLevelAccessor() levelVar.Set(slog.LevelDebug) // Thread-safe level change
func Init ¶ added in v1.6.0
func Init(ctx context.Context, config types.Config, additionalAttrs ...any) (retCtx context.Context, retLogger *slog.Logger, retErr error)
Init initializes a logger with the provided configuration and additional attributes.
It validates the configuration, creates the appropriate handler based on the output mode, and returns the updated context, configured logger, and any error encountered.
The logger is automatically set as slog.Default() if Config.SetAsDefault is true (default).
Parameters:
- ctx: The context to use for initialization and OTEL setup
- config: The logger configuration (see Config for details)
- additionalAttrs: Optional additional attributes to add to all log entries
Returns:
- context.Context: Updated context (may include OTEL trace context)
- *slog.Logger: Configured logger instance
- error: InitError if initialization fails, nil on success
Error Handling:
Init never panics. All panics are recovered and returned as InitError with stage "panic_recovery". If OTEL mode fails, Init gracefully degrades to console mode with a warning to stderr.
Thread Safety:
Init is safe to call concurrently from multiple goroutines. However, only one initialization should typically be performed per application.
Example:
config := loggergo.Config{
Level: slog.LevelInfo,
Format: loggergo.LogFormatJSON,
Output: loggergo.OutputConsole,
}
ctx, logger, err := loggergo.Init(ctx, config)
if err != nil {
log.Fatalf("Failed to initialize logger: %v", err)
}
logger.Info("Logger initialized successfully")
func Shutdown ¶ added in v1.8.0
func Shutdown() error
Shutdown performs cleanup of all registered resources.
This function should be called when the application is shutting down to ensure proper cleanup of resources like OTEL providers, file handles, etc.
Cleanup functions are called in reverse order of registration (LIFO). If any cleanup function returns an error, Shutdown continues with remaining cleanup functions and returns a combined error at the end.
Thread Safety:
Shutdown is safe to call concurrently, but should typically only be called once during application shutdown.
Example:
ctx, logger, err := loggergo.Init(ctx, config)
if err != nil {
panic(err)
}
defer loggergo.Shutdown()
// Use logger...
Types ¶
type Config ¶ added in v1.2.4
Config represents the configuration options for the logger. It is an alias for types.Config and is exported for external usage.
See types.Config for detailed field documentation and usage examples.
type CustomContextAttributeHandler ¶ added in v1.6.0
type CustomContextAttributeHandler struct {
ContextKeysDefault interface{}
// contains filtered or unexported fields
}
CustomContextAttributeHandler wraps an existing slog.Handler and automatically extracts values from context.Context to add as attributes to all log records.
This handler enables context-aware logging by extracting specified keys from the context and including them in every log entry. It handles nil contexts, missing keys, and type conversion gracefully.
Thread Safety:
CustomContextAttributeHandler is safe for concurrent use. Multiple goroutines can call Handle, Enabled, WithAttrs, and WithGroup simultaneously without additional synchronization.
func NewCustomContextAttributeHandler ¶ added in v1.6.0
func NewCustomContextAttributeHandler(handler slog.Handler, keys []interface{}, contextKeysDefault interface{}) *CustomContextAttributeHandler
NewCustomContextAttributeHandler creates a new handler that wraps the given handler and automatically extracts context values.
Parameters:
- handler: The underlying slog.Handler to wrap
- keys: Slice of context keys to extract from context.Context
- contextKeysDefault: Default value to use when a key is not found in context (can be nil)
Returns:
- *CustomContextAttributeHandler: A new handler that extracts context values
Example:
type contextKey string
const requestIDKey contextKey = "request_id"
handler := slog.NewJSONHandler(os.Stdout, nil)
contextHandler := NewCustomContextAttributeHandler(
handler,
[]interface{}{requestIDKey},
"unknown",
)
logger := slog.New(contextHandler)
ctx := context.WithValue(context.Background(), requestIDKey, "req-123")
logger.InfoContext(ctx, "Processing request") // Will include request_id: "req-123"
func (*CustomContextAttributeHandler) Enabled ¶ added in v1.6.0
Enabled reports whether the handler handles records at the given level. It delegates the check to the inner handler.
func (*CustomContextAttributeHandler) Handle ¶ added in v1.6.0
Handle processes a log record by extracting context values and delegating to the inner handler.
It extracts values for all configured keys from the context and adds them as attributes to the log record. If a key is not found, it uses the default value (if configured) or omits the field.
Error Handling:
Handle never panics. All panics are recovered and returned as errors. If the context is nil, context.Background() is used as a fallback.
Thread Safety:
Handle is safe to call concurrently from multiple goroutines.