xlogger

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: MIT Imports: 13 Imported by: 0

README

go-xlogger

A lightweight Go logging SDK with JSON/text output, configurable log levels, and seamless integration with Zap for high-performance structured logging.

Installation

go get github.com/hotfixfirst/go-xlogger

Or with a specific version:

go get github.com/hotfixfirst/go-xlogger@v1.0.0

Quick Start

package main

import (
    "github.com/hotfixfirst/go-xlogger"
    "go.uber.org/zap/zapcore"
)

func main() {
    // Using default config (JSON format, INFO level)
    logger, err := xlogger.NewZapLogger(xlogger.DefaultLoggerConfig())
    if err != nil {
        panic(err)
    }
    defer logger.Sync()

    logger.Info("Hello, World!")
    logger.Info("User action", xlogger.String("user_id", "12345"))
}

Features

Feature Description
Multiple Formats JSON and Text output formats
Log Levels Debug, Info, Warn, Error, Panic, Fatal
Structured Logging Type-safe field constructors
Trace Context Request/Correlation ID tracking
GORM Integration Database query logging
Fx Integration Uber Fx dependency injection support

Packages

Package Description Documentation
Config Logger configuration Examples
Logger Core logging interface Examples
Trace Request tracking Examples

Config

LogFormat
// Available formats
xlogger.FormatJSON  // JSON output (default)
xlogger.FormatText  // Human-readable text output
Config Struct
type Config struct {
    Level             zapcore.Level // Minimum log level
    Format            LogFormat     // Log format: FormatJSON or FormatText
    Development       bool          // Development mode (pretty printing)
    DisableCaller     bool          // Disable caller information
    DisableStacktrace bool          // Disable stacktrace in errors
    TimeFormat        string        // Time format (empty for default)
    CallerSkip        int           // Number of caller frames to skip
}
Config Functions
Function Description
DefaultLoggerConfig() Returns default config (INFO, JSON)
NewLoggerConfig(opts...) Creates config with functional options
Option Functions
Function Description
WithLevel(level) Set log level (zapcore.Level)
WithLevelString(level) Set log level from string ("debug", "info", etc.)
WithFormat(format) Set output format (JSON/Text)
WithDevelopment(bool) Enable development mode
WithDisableCaller(bool) Disable caller info
WithDisableStacktrace(bool) Disable stacktrace
WithTimeFormat(format) Set time format
WithCallerSkip(skip) Set caller skip frames
Config Example
// Default config
cfg := xlogger.DefaultLoggerConfig()

// Custom config with functional options
cfg := xlogger.NewLoggerConfig(
    xlogger.WithLevel(zapcore.DebugLevel),
    xlogger.WithFormat(xlogger.FormatText),
    xlogger.WithDevelopment(true),
)

Logger

Creating Logger
logger, err := xlogger.NewZapLogger(cfg)
if err != nil {
    panic(err)
}
defer logger.Sync()
Logging Methods
logger.Debug("Debug message", xlogger.String("key", "value"))
logger.Info("Info message", xlogger.Int("count", 42))
logger.Warn("Warning message", xlogger.Bool("active", true))
logger.Error("Error occurred", xlogger.Error(err))
Field Constructors
Function Type Example
String(key, value) string xlogger.String("name", "John")
Int(key, value) int xlogger.Int("count", 42)
Int64(key, value) int64 xlogger.Int64("id", 123456)
Float64(key, value) float64 xlogger.Float64("price", 99.99)
Bool(key, value) bool xlogger.Bool("active", true)
Error(err) error xlogger.Error(err)
Duration(key, value) time.Duration xlogger.Duration("elapsed", time.Second)
Time(key, value) time.Time xlogger.Time("created", time.Now())
Any(key, value) any xlogger.Any("data", obj)
Contextual Logger
// Add persistent fields
contextLogger := logger.With(
    xlogger.String("service", "api"),
    xlogger.String("version", "1.0.0"),
)

contextLogger.Info("Request received")  // Includes service and version

Trace Context

Track requests across function calls using goroutine-local storage.

Trace Functions
Function Description
RunWithTrace(requestID, correlationID, fn) Execute function with trace context
RunWithTraceVoid(requestID, correlationID, fn) Execute void function with trace context
TraceRequestID() Get current request ID
TraceCorrelationID() Get current correlation ID
Trace Example
err := xlogger.RunWithTrace("req-123", "corr-456", func() error {
    // Trace IDs are automatically added to logs
    logger.Info("Processing request")

    // Access trace IDs anywhere in this scope
    fmt.Println(xlogger.TraceRequestID())      // "req-123"
    fmt.Println(xlogger.TraceCorrelationID())  // "corr-456"

    return nil
})

GORM Integration

gormLogger := logger.ForGORM()

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    Logger: gormLogger,
})

Fx Integration

import "go.uber.org/fx"

app := fx.New(
    fx.Provide(
        xlogger.DefaultLoggerConfig,
        xlogger.NewZapLogger,
    ),
    fx.Invoke(func(logger xlogger.Logger) {
        logger.Info("Application started")
    }),
)

Examples

See the _examples directory for runnable examples.

Example Description
basic Basic logger usage
trace Trace context for request tracking

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package xlogger provides advanced logging functionalities built on top of zap.

Index

Constants

View Source
const (
	ConsoleTimeLayout = "2006-01-02 15:04:05 -07:00"
)

Variables

This section is empty.

Functions

func NewFxEventLogger

func NewFxEventLogger(logger Logger) fxevent.Logger

NewFxEventLogger creates a new FX event logger from the provided logger

func RunWithTrace

func RunWithTrace(requestID, correlationID string, fn func() error) error

RunWithTrace executes fn within a goroutine-local context that stores request and correlation identifiers for later retrieval.

func RunWithTraceVoid

func RunWithTraceVoid(requestID, correlationID string, fn func())

RunWithTraceVoid executes fn within the trace context when no error propagation is required.

func TraceCorrelationID

func TraceCorrelationID() string

TraceCorrelationID returns the goroutine-local correlation identifier.

func TraceRequestID

func TraceRequestID() string

TraceRequestID returns the goroutine-local request identifier.

Types

type Config

type Config struct {
	Level             zapcore.Level // Minimum log level
	Format            LogFormat     // Log format: FormatJSON or FormatText
	Development       bool          // Development mode (pretty printing)
	DisableCaller     bool          // Disable caller information
	DisableStacktrace bool          // Disable stacktrace in errors
	TimeFormat        string        // Time format (empty for default)
	CallerSkip        int           // Number of caller frames to skip
}

Config represents logger configuration options.

func DefaultLoggerConfig

func DefaultLoggerConfig() *Config

DefaultLoggerConfig returns default logger configuration with INFO level and JSON format.

Default values:

  • Level: INFO
  • Format: FormatJSON
  • Development: false
  • DisableCaller: false
  • DisableStacktrace: true
  • CallerSkip: 1

Example:

cfg := xlogger.DefaultLoggerConfig()
logger, err := xlogger.NewZapLogger(cfg)

func NewLoggerConfig

func NewLoggerConfig(opts ...Option) *Config

NewLoggerConfig creates logger configuration with functional options. Starts with DefaultLoggerConfig and applies each option in order.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithLevel(zapcore.DebugLevel),
    xlogger.WithFormat(xlogger.FormatText),
    xlogger.WithDevelopment(true),
)
logger, err := xlogger.NewZapLogger(cfg)

func (*Config) GetFormat

func (c *Config) GetFormat() string

GetFormat returns normalized log format in lowercase.

func (*Config) GetLevel

func (c *Config) GetLevel() string

GetLevel returns the log level as string.

func (*Config) IsDebugLevel

func (c *Config) IsDebugLevel() bool

IsDebugLevel returns true if the log level is debug.

func (*Config) IsDevelopment

func (c *Config) IsDevelopment() bool

IsDevelopment returns true if development mode is enabled.

func (*Config) IsErrorLevel

func (c *Config) IsErrorLevel() bool

IsErrorLevel returns true if the log level is error.

func (*Config) IsInfoLevel

func (c *Config) IsInfoLevel() bool

IsInfoLevel returns true if the log level is info.

func (*Config) IsJSONFormat

func (c *Config) IsJSONFormat() bool

IsJSONFormat returns true if the format is JSON.

func (*Config) IsTextFormat

func (c *Config) IsTextFormat() bool

IsTextFormat returns true if the format is text.

func (*Config) IsWarnLevel

func (c *Config) IsWarnLevel() bool

IsWarnLevel returns true if the log level is warn.

type Field

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

Field represents a structured log field with key-value pairs This abstraction allows for type-safe logging without coupling to zap

func Any

func Any(key string, value interface{}) Field

Any creates a field for any type (use sparingly for performance)

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 time.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 integer field

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field

func NamedError

func NamedError(key string, err error) Field

NamedError creates an error field with a specific name

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.Time field

func (Field) Key

func (f Field) Key() string

Key returns the field key

func (Field) Type

func (f Field) Type() FieldType

Type returns the field type

func (Field) Value

func (f Field) Value() interface{}

Value returns the field value

type FieldType

type FieldType int

FieldType represents the type of a log field for optimization

const (
	StringType FieldType = iota
	IntType
	Float64Type
	BoolType
	ErrorType
	DurationType
	TimeType
	AnyType
)

type GORMLogger

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

GORMLogger implements gorm.logger.Interface using our Logger

func NewGORMLogger

func NewGORMLogger(logger Logger) *GORMLogger

NewGORMLogger creates a new GORM logger adapter with sensible defaults

func (*GORMLogger) Error

func (l *GORMLogger) Error(_ context.Context, msg string, data ...interface{})

Error implements gorm.logger.Interface

func (*GORMLogger) Info

func (l *GORMLogger) Info(_ context.Context, msg string, data ...interface{})

Info implements gorm.logger.Interface

func (*GORMLogger) LogMode

LogMode implements gorm.logger.Interface

func (*GORMLogger) SetIgnoreRecordNotFoundError

func (l *GORMLogger) SetIgnoreRecordNotFoundError(ignore bool) *GORMLogger

SetIgnoreRecordNotFoundError configures whether to ignore ErrRecordNotFound

func (*GORMLogger) SetMaxPathLevels

func (l *GORMLogger) SetMaxPathLevels(levels int) *GORMLogger

SetMaxPathLevels configures maximum path levels to display (-1 = show "_", 0 = show full path)

func (*GORMLogger) SetSlowThreshold

func (l *GORMLogger) SetSlowThreshold(threshold time.Duration) *GORMLogger

SetSlowThreshold configures slow query threshold

func (*GORMLogger) Trace

func (l *GORMLogger) Trace(_ context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

Trace implements gorm.logger.Interface for SQL query logging

func (*GORMLogger) Warn

func (l *GORMLogger) Warn(_ context.Context, msg string, data ...interface{})

Warn implements gorm.logger.Interface

type LogFormat

type LogFormat string

LogFormat represents the log output format.

const (
	// FormatJSON outputs logs in JSON format.
	FormatJSON LogFormat = "json"
	// FormatText outputs logs in human-readable text format.
	FormatText LogFormat = "text"
)

func (LogFormat) IsValid

func (f LogFormat) IsValid() bool

IsValid returns true if the format is valid (json or text).

func (LogFormat) Normalize

func (f LogFormat) Normalize() LogFormat

Normalize returns the normalized lowercase format.

func (LogFormat) String

func (f LogFormat) String() string

String returns the string representation of LogFormat.

type Logger

type Logger interface {
	// Core logging methods for different levels
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)

	// These methods will terminate the application after logging
	Panic(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)

	// Logger enhancement methods
	With(fields ...Field) Logger

	// Infrastructure optimization methods
	ForInfra(component string) Logger
	ForFxEvent() fxevent.Logger
	ForGORM() *GORMLogger

	// Logger configuration methods
	Level() zapcore.Level

	// Utility methods
	Sync() error
}

Logger represents the main logging interface for structured logging This interface provides both application and infrastructure logging capabilities

func NewNop

func NewNop() Logger

NewNop creates a no-operation logger for testing purposes This logger discards all log entries and has minimal overhead

type Option added in v1.1.0

type Option func(*Config)

Option is a function that modifies Config.

func WithCallerSkip added in v1.1.0

func WithCallerSkip(skip int) Option

WithCallerSkip sets the number of caller frames to skip.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithCallerSkip(2),
)

func WithDevelopment added in v1.1.0

func WithDevelopment(dev bool) Option

WithDevelopment enables or disables development mode.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithDevelopment(true),
)

func WithDisableCaller added in v1.1.0

func WithDisableCaller(disable bool) Option

WithDisableCaller disables caller information.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithDisableCaller(true),
)

func WithDisableStacktrace added in v1.1.0

func WithDisableStacktrace(disable bool) Option

WithDisableStacktrace disables stacktrace in errors.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithDisableStacktrace(false),
)

func WithFormat added in v1.1.0

func WithFormat(format LogFormat) Option

WithFormat sets the log format.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithFormat(xlogger.FormatText),
)

func WithLevel added in v1.1.0

func WithLevel(level zapcore.Level) Option

WithLevel sets the log level.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithLevel(zapcore.DebugLevel),
)

func WithLevelString added in v1.2.0

func WithLevelString(level string) Option

WithLevelString sets the log level from string. Supported values: "debug", "info", "warn", "error", "dpanic", "panic", "fatal" Invalid values are ignored and the default level (INFO) is used.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithLevelString("debug"),
)

func WithTimeFormat added in v1.1.0

func WithTimeFormat(format string) Option

WithTimeFormat sets the time format.

Example:

cfg := xlogger.NewLoggerConfig(
    xlogger.WithTimeFormat("2006-01-02 15:04:05"),
)

type ZapLogger

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

ZapLogger implements Logger interface using zap as the underlying logger

func NewZapLogger

func NewZapLogger(cfg *Config) (*ZapLogger, error)

NewZapLogger creates a ZapLogger with full configuration support

func (*ZapLogger) Debug

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

Debug logs a debug message with fields

func (*ZapLogger) Error

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

Error logs an error message with fields

func (*ZapLogger) Fatal

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

Fatal logs a fatal message with fields then calls os.Exit(1)

func (*ZapLogger) ForFxEvent

func (l *ZapLogger) ForFxEvent() fxevent.Logger

ForFxEvent returns a FX event logger that implements fxevent.Logger interface

func (*ZapLogger) ForGORM

func (l *ZapLogger) ForGORM() *GORMLogger

ForGORM returns a pre-cached logger optimized for GORM

func (*ZapLogger) ForInfra

func (l *ZapLogger) ForInfra(component string) Logger

ForInfra returns a logger optimized for infrastructure components

func (*ZapLogger) Info

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

Info logs an info message with fields

func (*ZapLogger) Level

func (l *ZapLogger) Level() zapcore.Level

Level returns the current logging level

func (*ZapLogger) Panic

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

Panic logs a panic message with fields then calls panic()

func (*ZapLogger) Sync

func (l *ZapLogger) Sync() error

Sync implements Logger interface

func (*ZapLogger) Warn

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

Warn logs a warning message with fields

func (*ZapLogger) With

func (l *ZapLogger) With(fields ...Field) Logger

With creates a new logger instance with additional fields pre-attached

Directories

Path Synopsis
_examples
basic command
Package main demonstrates the basic usage of the xlogger package.
Package main demonstrates the basic usage of the xlogger package.
trace command
Package main demonstrates trace context functionality in xlogger.
Package main demonstrates trace context functionality in xlogger.

Jump to

Keyboard shortcuts

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