abslog

package module
v3.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: GPL-3.0 Imports: 9 Imported by: 0

README

abslog

Go Reference Go Version CodeQL Dependabot Ask DeepWiki Contributing

A modern Go logging abstraction library that provides a unified API over multiple logging backends. It ships with built-in support for popular libraries like Zap and Logrus, enabling seamless switching between them without code changes. Additionally, it allows integration of any custom logging library through its adapter pattern. Includes powerful context-aware logging for enhanced traceability in distributed systems.

Features

  • Built-in Backends: Ready-to-use integration with Zap and Logrus
  • Extensible Design: Add any logging library via the LoggerAdapter interface
  • Unified API: Consistent logging interface across all backends
  • Backend Flexibility: Switch between supported loggers without code modifications
  • Context Logging: Embed contextual information (e.g., transaction IDs, user data) in logs for traceability
  • Builder Pattern: Fluent configuration API for logger setup
  • Multiple Output Formats: Support for console and JSON encoding
  • Global Functions: Ready-to-use global logging functions with context support

Installation

go get github.com/RajulSahu/abslog/v3

Quick Start

package main

import (
    "github.com/RajulSahu/abslog/v3"
)

func main() {
    abslog.Info("Application started")
    abslog.Error("An error occurred")
}

Usage

Basic Logging

abslog provides global logging functions at all standard levels:

abslog.Debug("Debug message")
abslog.Info("Info message")
abslog.Warn("Warning message")
abslog.Error("Error message")
abslog.Fatal("Fatal message") // Exits the program
abslog.Panic("Panic message") // Panics the program

Formatted logging is also supported:

abslog.Infof("User %s logged in at %s", username, time.Now())
Switching Backends

Change the underlying logging library without modifying your logging code:

// Switch to Logrus
abslog.SetLoggerType(abslog.LogrusLogger)

// Switch back to Zap (default)
abslog.SetLoggerType(abslog.ZapLogger)
Context Logging

abslog's context logging enables powerful traceability features, particularly useful in microservices and distributed systems. By embedding contextual information in the context.Context, you can correlate logs across request lifecycles.

Setting Context Values

At the start of a request or operation, set contextual data:

ctx := context.Background()

// Using a map for structured context
ctxValues := map[string]any{
    "transaction_id": "txn-12345",
    "user_id":        "user-67890",
    "service":        "auth-service",
}
ctx = context.WithValue(ctx, abslog.GetCtxKey(), ctxValues)

// Or using a slice of strings
ctx = context.WithValue(ctx, abslog.GetCtxKey(), []string{"txn-12345", "user-67890"})

// Or a simple string
ctx = context.WithValue(ctx, abslog.GetCtxKey(), "txn-12345")
Logging with Context

Use context-aware logging functions to include the embedded data in your logs:

abslog.InfoCtx(ctx, "Processing user authentication")
abslog.WarnCtx(ctx, "Invalid credentials provided")
abslog.ErrorCtx(ctx, "Authentication failed")

Output Example:

[transaction_id=txn-12345, user_id=user-67890, service=auth-service] -> Processing user authentication
[transaction_id=txn-12345, user_id=user-67890, service=auth-service] -> Invalid credentials provided

This allows you to trace all logs related to a specific transaction or user across your entire application, making debugging and monitoring significantly easier.

Advanced Configuration

Use the builder pattern for detailed logger configuration:

// BuildAndSetAsGlobal: Creates the logger and sets it as the global logger
logger := abslog.GetAbsLogBuilder().
    LoggerType(abslog.LogrusLogger).
    LogLevel(abslog.DebugLevel).
    EncoderType(abslog.JSONEncoder).
    ContextKey("custom-key").
    BuildAndSetAsGlobal()

// Build: Creates the logger instance without setting it as global
customLogger := abslog.GetAbsLogBuilder().
    LoggerType(abslog.ZapLogger).
    LogLevel(abslog.InfoLevel).
    Build()

// Use the custom logger directly (not affecting global functions)
customLogger.Info("This uses the custom logger instance")

Difference between Build and BuildAndSetAsGlobal:

  • Build(): Returns a configured AbsLog instance that you can use directly, but doesn't affect the global logging functions
  • BuildAndSetAsGlobal(): Configures the logger and sets it as the global logger, updating all global abslog.Info(), abslog.Debug(), etc. functions to use this configuration
Custom Context Key

Customize the context key used for storing values:

abslog.SetCtxKey("my-custom-key")

Note on Type Safety: SetCtxKey automatically converts the string parameter to ContextKeyType to avoid Go's static analysis warning SA1029: "should not use built-in type string as key for value; define your own type to avoid collisions". This ensures safe usage with context.WithValue() as recommended by Go's context package documentation, which states that context keys should be comparable and not of built-in types to prevent collisions between packages.

Adding Custom Logging Libraries

abslog is designed to be extensible. You can integrate any logging library that provides the standard logging methods. The process involves creating a generator function and using the LoggerAdapter.

Implementation Steps
  1. Create a Generator Function: Implement a function that takes LogLevel and EncoderType and returns an AbsLog:

    func getCustomLogger(logLevel LogLevel, encoder EncoderType) AbsLog {
        // Create your custom logger instance
        customLogger := // ... initialize your logger
    
        // Configure log level
        customLogger.SetLevel(convertToCustomLevel(logLevel))
    
        // Configure encoding if supported
        switch encoder {
        case JSONEncoder:
            // Set JSON formatter
        case ConsoleEncoder:
            // Set console formatter
        }
    
        // Wrap in LoggerAdapter
        return NewLoggerAdapter(customLogger)
    }
    
  2. Level Conversion: Create a helper function to convert abslog levels to your library's levels:

    func convertToCustomLevel(logLevel LogLevel) CustomLevel {
        switch logLevel {
        case DebugLevel:
            return CustomDebug
        case InfoLevel:
            return CustomInfo
        // ... other levels
        default:
            return CustomInfo
        }
    }
    
  3. Use with Builder: Set your custom generator and build the logger:

logger := abslog.GetAbsLogBuilder().
    LoggerGen(getCustomLogger).
    LogLevel(abslog.DebugLevel).
    BuildAndSetAsGlobal()
Examples

See logrus.go and zap.go for complete implementations of Logrus and Zap integrations. These files demonstrate:

  • Logger initialization and configuration
  • Level conversion functions
  • Encoder setup for console and JSON output
  • Proper wrapping with NewLoggerAdapter

The LoggerAdapter requires your logger to implement methods: Debug/Info/Warn/Error/Fatal/Panic and their formatted variants (Debugf/Infof/etc.).

API Overview

Global Functions
  • Debug/Info/Warn/Error/Fatal/Panic(args ...any)
  • Debugf/Infof/Warnf/Errorf/Fatalf/Panicf(format string, args ...any)
  • DebugCtx/InfoCtx/WarnCtx/ErrorCtx/FatalCtx/PanicCtx(ctx context.Context, args ...any)
  • DebugCtxf/InfoCtxf/WarnCtxf/ErrorCtxf/FatalCtxf/PanicCtxf(ctx context.Context, format string, args ...any)
Configuration
  • SetLoggerType(LoggerType)
  • SetLogger(AbsLog)
  • GetAbsLogBuilder() AbsLogBuilder
Context Management
  • SetCtxKey(key string)
  • GetCtxKey() ContextKeyType
  • SetCtxSeparator(separator string)
Types
  • LoggerType: ZapLogger, LogrusLogger
  • LogLevel: DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel
  • EncoderType: ConsoleEncoder, JSONEncoder
  • ContextKeyType: Custom type for context keys to avoid Go's SA1029 static analysis warning when using with context.WithValue()

Contributing

  • 🤝 Contributing Guide - How to contribute code, report issues, and help improve abslog

License

GPL v3 - see LICENSE for details.

Documentation

Overview

Package abslog provides an abstraction layer for logging libraries, allowing seamless switching between different logging backends (Zap, Logrus) while maintaining a consistent API.

Index

Constants

This section is empty.

Variables

View Source
var Debug func(args ...any)

Debug logs a message at level Debug on the standard logger.

View Source
var DebugCtx func(ctx context.Context, args ...any)
View Source
var DebugCtxf func(ctx context.Context, format string, args ...any)
View Source
var Debugf func(format string, args ...any)
View Source
var Error func(args ...any)

Error logs a message at level Error on the standard logger.

View Source
var ErrorCtx func(ctx context.Context, args ...any)
View Source
var ErrorCtxf func(ctx context.Context, format string, args ...any)
View Source
var Errorf func(format string, args ...any)
View Source
var Fatal func(args ...any)

Fatal logs a message at level Fatal on the standard logger.

View Source
var FatalCtx func(ctx context.Context, args ...any)
View Source
var FatalCtxf func(ctx context.Context, format string, args ...any)
View Source
var Fatalf func(format string, args ...any)
View Source
var Info func(args ...any)

Info logs a message at level Info on the standard logger.

View Source
var InfoCtx func(ctx context.Context, args ...any)
View Source
var InfoCtxf func(ctx context.Context, format string, args ...any)
View Source
var Infof func(format string, args ...any)
View Source
var Panic func(args ...any)

Panic logs a message at level Panic on the standard logger.

View Source
var PanicCtx func(ctx context.Context, args ...any)
View Source
var PanicCtxf func(ctx context.Context, format string, args ...any)
View Source
var Panicf func(format string, args ...any)
View Source
var Warn func(args ...any)

Warn logs a message at level Warn on the standard logger.

View Source
var WarnCtx func(ctx context.Context, args ...any)
View Source
var WarnCtxf func(ctx context.Context, format string, args ...any)
View Source
var Warnf func(format string, args ...any)

Functions

func GetCtxSeparator

func GetCtxSeparator() string

GetCtxSeparator returns the current separator used between context values and log messages.

func ResetCtxKey

func ResetCtxKey()

ResetCtxKey resets the context key to its default value.

func ResetCtxSeparator

func ResetCtxSeparator()

ResetCtxSeparator resets the context separator to its default value.

func SetCtxKey

func SetCtxKey(key string)

SetCtxKey sets the key used to retrieve context values from context.Context. This allows customization of how context values are stored and retrieved. If key is empty or only whitespace, the default key "abslog" will be used.

func SetCtxSeparator

func SetCtxSeparator(separator string)

SetCtxSeparator sets the string used to separate context values from log messages. If separator is empty or only whitespace, the default separator " -> " will be used.

func SetLogger

func SetLogger(logger AbsLog)

SetLogger sets the provided AbsLog instance as the global logger, updating all global logging function variables.

func SetLoggerType

func SetLoggerType(typ LoggerType)

SetLoggerType configures the global logger to use the specified logger type (ZapLogger or LogrusLogger) with default settings.

Types

type AbsLog

type AbsLog interface {
	Debug(args ...any)
	Debugf(format string, args ...any)

	Info(args ...any)
	Infof(format string, args ...any)

	Warn(args ...any)
	Warnf(format string, args ...any)

	Error(args ...any)
	Errorf(format string, args ...any)

	Fatal(args ...any)
	Fatalf(format string, args ...any)

	Panic(args ...any)
	Panicf(format string, args ...any)
}

AbsLog defines the interface for abstracted logging functionality. It provides methods for logging at different levels with optional formatting.

func NewLoggerAdapter

func NewLoggerAdapter(logger interface {
	Debug(args ...any)
	Debugf(format string, args ...any)
	Info(args ...any)
	Infof(format string, args ...any)
	Warn(args ...any)
	Warnf(format string, args ...any)
	Error(args ...any)
	Errorf(format string, args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Panic(args ...any)
	Panicf(format string, args ...any)
}) AbsLog

NewLoggerAdapter creates a new LoggerAdapter wrapping the provided logger.

type AbsLogBuilder

type AbsLogBuilder interface {
	LogLevel(level LogLevel) AbsLogBuilder
	LoggerGen(generator LoggerGen) AbsLogBuilder
	LoggerType(loggerType LoggerType) AbsLogBuilder
	EncoderType(encoderType EncoderType) AbsLogBuilder
	ContextKey(key string) AbsLogBuilder
	BuildAndSetAsGlobal() AbsLog
	Build() AbsLog
}

AbsLogBuilder is the interface that wraps the Builder methods to create a new AbsLog.

func GetAbsLogBuilder

func GetAbsLogBuilder() AbsLogBuilder

GetAbsLogBuilder returns a new AbsLog builder.

type ContextKeyType

type ContextKeyType string

contextKey is the current key used to store context values in context.Context

func GetCtxKey

func GetCtxKey() ContextKeyType

GetCtxKey returns the current key used to retrieve context values from context.Context.

type EncoderType

type EncoderType int8

EncoderType represents the format used for log output.

const (
	// ConsoleEncoder formats logs for human-readable console output.
	ConsoleEncoder EncoderType = iota + 1
	// JSONEncoder formats logs as JSON for structured logging.
	JSONEncoder
)

Encoder type constants defining the output format for log messages.

type LogLevel

type LogLevel int8

LogLevel represents the severity level of log messages.

const (
	// DebugLevel is used for debug messages, typically only enabled during development.
	DebugLevel LogLevel = iota + 1
	// InfoLevel is used for general informational messages.
	InfoLevel
	// WarnLevel is used for warning messages that indicate potential issues.
	WarnLevel
	// ErrorLevel is used for error messages that indicate failures.
	ErrorLevel
	// PanicLevel is used for panic messages that cause the application to panic.
	PanicLevel
	// FatalLevel is used for fatal messages that cause the application to exit.
	FatalLevel
)

Log level constants defining the severity of log messages.

type LoggerAdapter

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

LoggerAdapter adapts any logger that implements the basic logging methods to the AbsLog interface. This provides a consistent abstraction layer while handling type conversions.

func (*LoggerAdapter) Debug

func (a *LoggerAdapter) Debug(args ...any)

Debug logs a message at debug level.

func (*LoggerAdapter) Debugf

func (a *LoggerAdapter) Debugf(format string, args ...any)

Debugf logs a formatted message at debug level.

func (*LoggerAdapter) Error

func (a *LoggerAdapter) Error(args ...any)

Error logs a message at error level.

func (*LoggerAdapter) Errorf

func (a *LoggerAdapter) Errorf(format string, args ...any)

Errorf logs a formatted message at error level.

func (*LoggerAdapter) Fatal

func (a *LoggerAdapter) Fatal(args ...any)

Fatal logs a message at fatal level and exits the program.

func (*LoggerAdapter) Fatalf

func (a *LoggerAdapter) Fatalf(format string, args ...any)

Fatalf logs a formatted message at fatal level and exits the program.

func (*LoggerAdapter) Info

func (a *LoggerAdapter) Info(args ...any)

Info logs a message at info level.

func (*LoggerAdapter) Infof

func (a *LoggerAdapter) Infof(format string, args ...any)

Infof logs a formatted message at info level.

func (*LoggerAdapter) Panic

func (a *LoggerAdapter) Panic(args ...any)

Panic logs a message at panic level and panics.

func (*LoggerAdapter) Panicf

func (a *LoggerAdapter) Panicf(format string, args ...any)

Panicf logs a formatted message at panic level and panics.

func (*LoggerAdapter) Warn

func (a *LoggerAdapter) Warn(args ...any)

Warn logs a message at warn level.

func (*LoggerAdapter) Warnf

func (a *LoggerAdapter) Warnf(format string, args ...any)

Warnf logs a formatted message at warn level.

type LoggerGen

type LoggerGen func(logLevel LogLevel, encoder EncoderType) AbsLog

LoggerGen is a function type that creates an AbsLog instance with the specified log level and encoder type.

type LoggerType

type LoggerType int8

LoggerType represents the underlying logging library to use.

const (
	// ZapLogger uses the Uber Zap logging library as the backend.
	ZapLogger LoggerType = iota + 1
	// LogrusLogger uses the Sirupsen Logrus logging library as the backend.
	LogrusLogger
)

Logger type constants defining which logging backend to use.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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