dslogger

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License: MIT Imports: 10 Imported by: 0

README

dslogger

dslogger is a lightweight logger that uses zap for fast, structured logging and lumberjack for efficient log rotation.

Usage

Simple Console Logger

Use NewSimpleConsoleLogger to quickly create a console-only logger:

package main

import (
  "github.com/K4rian/dslogger"
)

func main() {
    // Create a console-only logger with default configuration at "info" level
    logger, err := dslogger.NewSimpleConsoleLogger("info")
    if err != nil {
        log.Fatalf("Error creating console logger: %v", err)
    }

    // Log an informational message
    logger.Info("This is an info message from the simple console logger!")
    logger.Warn("Unusual activity detected", "ip", "X.X.X.X")
    logger.Error("Error processing request", "requestID", "abc123")
}
Simple Logger (Console and File)

Use NewSimpleLogger to create a logger that writes to both the console and a file (using default configuration):

package main

import (
  "github.com/K4rian/dslogger"
)

func main() {
    // Create a logger that outputs to both console and file at "debug" level
    logger, err := dslogger.NewSimpleLogger("debug")
    if err != nil {
        log.Fatalf("Error creating logger: %v", err)
    }

    // Log messages at various levels
    logger.Debug("Debug message", "user", "james")
    logger.Info("Info message", "action", "login")
    logger.Warn("Warning message", "ip", "X.X.X.X")
    logger.Error("Error message", "error", "file not found", "file", "/opt/files/myfile.txt")
}
Service-Specific Logger

This example shows how to derive a service-specific logger from a base logger using the WithService method.
The derived logger automatically attaches a "service": "AuthService" field to every log entry, making it easier to distinguish logs for different services in your application (especially when using JSON file format for logs):

package main

import (
  "github.com/K4rian/dslogger"
)

func main() {
    // Create a console-only logger with default configuration at "info" level
    logger, err := dslogger.NewSimpleConsoleLogger("info")
    if err != nil {
        log.Fatalf("Error creating console logger: %v", err)
    }
	logger.Debug("You shouldn't be able to see this message")
	logger.Info("A simple info message from the base logger!")

    // Derive a logger for a specific service
    authLogger := logger.WithService("AuthService")

    // Logs will include the "service" field when using JSON file format
    authLogger.Info("Authentication successful", "user", "james")
}
Advanced Console-Only Logger

This example demonstrates how to create an advanced console-only logger with a custom configuration and options.
It customizes the encoder settings and sets a custom service name using a functional option:

package main

import (
  "github.com/K4rian/dslogger"
)

func main() {
    // Define a custom configuration for console logging
    customConfig := &dslogger.Config{
        Level:                 "debug",
        ConsoleConfig:         dslogger.DefaultConsoleEncoderConfig,
        FieldSeparator:        ": ",
        ConsoleSeparator:      " | ",
        ServiceNameDecorators: [2]string{"[", "]"},
    }

    // Create a console-only logger with custom configuration and a functional option to set the service name
	logger, err := NewConsoleLogger("debug", customConfig, dslogger.WithServiceName("MyService"), dslogger.WithCallerSkip(1))
	if err != nil {
		log.Fatalf("Failed to create advanced console logger: %v", err)
	}

    logger.Info("This is a custom advanced console-only logger", "count", 14)
}
Advanced Logger (Console and File)

Create an advanced logger with custom configuration and options that writes to both console and file.
This example shows how to configure the file output format (JSON or Text) by setting the LogFileFormat and corresponding encoder configuration:

package main

import (
  "github.com/K4rian/dslogger"
)

func main() {
    // Define a custom configuration for the full logger
	customConfig := &dslogger.Config{
		LogFile:               "./full.log",
		LogFileFormat:         dslogger.LogFormatJSON, // Either LogFormatJSON or LogFormatText
		MaxSize:               50,
		MaxBackups:            7,
		MaxAge:                60,
		Compress:              true,
		Level:                 "debug",
		ConsoleConfig:         dslogger.DefaultConsoleEncoderConfig,
		FileConfig:            dslogger.DefaultJSONEncoderConfig, // For JSON output, use DefaultJSONEncoderConfig; for text, use DefaultTextEncoderConfig
		FieldSeparator:        "=",
		ConsoleSeparator:      "    ",
		ServiceNameDecorators: [2]string{"(", ")"},
	}

	// Create a logger that writes to both console and file, with a custom "branch" and "creation_time" fields
	logger, err := NewLogger("debug", customConfig, WithCustomFields("branch", "dev", "creation_time", time.Now()))
    if err != nil {
        log.Fatalf("Failed to create full logger: %v", err)
    }

    // Log messages at various levels.
    logger.Debug("Debug message with full logger", "user", "bob")
    logger.Info("Info message with full logger", "operation", "data_import")
    logger.Warn("Warning message", "warning", "low disk space")
    logger.Error("Error message", "error", "failed to connect to database")
}

Installation

To install dslogger, simply run the following command:

go get github.com/k4rian/dslogger

For Go modules (if you're using Go 1.11+), ensure that your project is using modules and run:

go get github.com/k4rian/dslogger@latest

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultLevelFormats = map[zapcore.Level]LevelFormat{
		zapcore.DebugLevel: {LevelStr: "DEBUG", Color: "\033[34m"},
		zapcore.InfoLevel:  {LevelStr: "INFO ", Color: "\033[36m"},
		zapcore.WarnLevel:  {LevelStr: "WARN ", Color: "\033[33m"},
		zapcore.ErrorLevel: {LevelStr: "ERROR", Color: "\033[31m"},
	}

	// DefaultConsoleEncoderConfig defines the default encoder configuration for console output.
	// It uses ISO8601 for time encoding, a fixed-width colored encoder for log levels,
	// and a short caller encoder to show the file and line number.
	DefaultConsoleEncoderConfig = zapcore.EncoderConfig{
		TimeKey:      "timestamp",
		LevelKey:     "level",
		MessageKey:   "message",
		EncodeTime:   zapcore.ISO8601TimeEncoder,
		EncodeCaller: zapcore.ShortCallerEncoder,
	}

	// DefaultTextEncoderConfig defines the default encoder configuration for plain text log output.
	// It uses ISO8601 for time encoding, a fixed-width log level encoder (without color),
	// and a short caller encoder.
	DefaultTextEncoderConfig = zapcore.EncoderConfig{
		TimeKey:      "timestamp",
		LevelKey:     "level",
		MessageKey:   "message",
		EncodeTime:   zapcore.ISO8601TimeEncoder,
		EncodeCaller: zapcore.ShortCallerEncoder,
	}

	// DefaultJSONEncoderConfig defines the default encoder configuration for JSON log output.
	// It uses ISO8601 for time encoding, a capitalized log level encoder,
	// and a short caller encoder to include caller information.
	DefaultJSONEncoderConfig = zapcore.EncoderConfig{
		TimeKey:      "timestamp",
		LevelKey:     "level",
		MessageKey:   "message",
		EncodeTime:   zapcore.ISO8601TimeEncoder,
		EncodeLevel:  zapcore.CapitalLevelEncoder,
		EncodeCaller: zapcore.ShortCallerEncoder,
	}

	// DefaultLoggerConfig provides the default configuration for a dslogger.Logger instance.
	// It sets default values for the log file path, file format, rotation policies,
	// encoder configurations for both console and file outputs, and other display options.
	DefaultLoggerConfig = Config{
		LogFile:               "app.log",
		LogFileFormat:         LogFormatText,
		MaxSize:               10,
		MaxBackups:            5,
		MaxAge:                28,
		Compress:              true,
		Level:                 "info",
		ConsoleConfig:         DefaultConsoleEncoderConfig,
		FileConfig:            DefaultTextEncoderConfig,
		FieldSeparator:        ": ",
		ConsoleSeparator:      " | ",
		ServiceNameDecorators: [2]string{"[", "]"},
		LevelFormats:          DefaultLevelFormats,
	}
)

Functions

func FixedWidthCapitalColorLevelEncoder added in v0.2.1

func FixedWidthCapitalColorLevelEncoder(cfg *Config) zapcore.LevelEncoder

FixedWidthCapitalColorLevelEncoder encodes the log level as a colored, fixed-width string. It uses ANSI escape codes to colorize the output.

func FixedWidthCapitalLevelEncoder added in v0.2.1

func FixedWidthCapitalLevelEncoder(cfg *Config) zapcore.LevelEncoder

FixedWidthCapitalLevelEncoder encodes the log level as a fixed-width string. This is used to ensure consistent alignment in console output.

Types

type Config

type Config struct {
	LogFile               string
	LogFileFormat         LogFormat
	MaxSize               int
	MaxBackups            int
	MaxAge                int
	Compress              bool
	Level                 string
	ConsoleConfig         zapcore.EncoderConfig
	FileConfig            zapcore.EncoderConfig
	ConsoleSeparator      string
	FieldSeparator        string
	ServiceNameDecorators [2]string
	LevelFormats          map[zapcore.Level]LevelFormat
}

Config holds configuration options for the Logger.

type LevelFormat added in v0.2.0

type LevelFormat struct {
	LevelStr string // e.g. "DEBUG", "INFO", etc.
	Color    string // e.g. "\033[34m" for blue; empty string if no color.
}

LevelFormat holds the fixed-width text representation for a log level, as well as an optional ANSI color escape sequence.

type LogFormat

type LogFormat string

LogFormat defines the output format for log files.

const (
	LogFormatText LogFormat = "text"
	LogFormatJSON LogFormat = "json"
)

Supported log file formats.

type Logger

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

Logger is a configurable logger that supports output to console and file. It uses zap for logging and lumberjack for file rotation.

func NewConsoleLogger

func NewConsoleLogger(level string, config *Config, opts ...Option) (*Logger, error)

NewConsoleLogger creates a new logger that outputs only to the console. It applies any provided functional options for additional configuration.

func NewLogger

func NewLogger(level string, config *Config, opts ...Option) (*Logger, error)

NewLogger creates a new logger that outputs to both the console and a file. It uses the provided configuration and applies any functional options.

func NewSimpleConsoleLogger

func NewSimpleConsoleLogger(level string) (*Logger, error)

NewSimpleConsoleLogger creates a logger that outputs only to the console using default configuration.

func NewSimpleLogger

func NewSimpleLogger(level string) (*Logger, error)

NewSimpleLogger creates a logger that outputs to both console and a text file using default configuration.

func (*Logger) ClearFields added in v0.2.0

func (l *Logger) ClearFields()

ClearFields clears all custom zap fields.

func (*Logger) Config

func (l *Logger) Config() *Config

Config returns the current logger configuration.

func (*Logger) ConsoleLogger

func (l *Logger) ConsoleLogger() *zap.SugaredLogger

ConsoleLogger returns the underlying console logger instance.

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...any)

Debug logs a debug-level message along with optional structured fields.

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...any)

Error logs an error message along with optional structured fields.

func (*Logger) Fields added in v0.2.0

func (l *Logger) Fields() []zap.Field

Fields retrieves the custom zap fields.

func (*Logger) FileLogger

func (l *Logger) FileLogger() *zap.SugaredLogger

FileLogger returns the underlying file logger instance.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...any)

Info logs an informational message along with optional structured fields.

func (*Logger) Level added in v0.2.0

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

Level retrieves the current logging level (atomic).

func (*Logger) LumberjackLogger

func (l *Logger) LumberjackLogger() *lumberjack.Logger

func (*Logger) ServiceName

func (l *Logger) ServiceName() string

ServiceName returns the name of the service associated with the logger.

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(level string) error

SetLogLevel updates the log level for both console and file loggers. It returns an error if updating any of the loggers fails.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...any)

Warn logs a warning message along with optional structured fields.

func (*Logger) WithContext added in v0.2.0

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext returns a new logger instance that attaches common fields (request_id, trace_id) extracted from the provided context.

func (*Logger) WithFields added in v0.2.0

func (l *Logger) WithFields(fields ...any) *Logger

WithFields returns a new logger instance with the specified structured fields attached.

func (*Logger) WithService

func (l *Logger) WithService(serviceName string, options ...zap.Option) *Logger

WithService creates a new logger instance that includes a "service" field in its log entries. Additional zap.Options can be provided to customize the underlying logger.

type Option added in v0.2.0

type Option func(*Logger) error

Option represents a functional option for configuring a Logger.

func WithCallerSkip added in v0.2.0

func WithCallerSkip(skip int) Option

WithCallerSkip adjusts the caller skip level for accurate file/line reporting.

func WithConsoleEncoder added in v0.2.0

func WithConsoleEncoder(encoder zapcore.Encoder) Option

WithConsoleEncoder sets a custom zapcore.Encoder for the console logger.

func WithCustomField added in v0.2.0

func WithCustomField(key string, value any) Option

WithCustomField is an option to attach a custom field to every log.

func WithCustomFields added in v0.2.0

func WithCustomFields(fields ...any) Option

WithCustomFields attaches multiple custom fields to every log entry.

func WithCustomLevelFormats added in v0.2.0

func WithCustomLevelFormats(formats map[zapcore.Level]LevelFormat) Option

WithCustomLevelFormats is an option that sets custom level formats on the logger's config.

func WithFileEncoder added in v0.2.0

func WithFileEncoder(encoder zapcore.Encoder) Option

WithFileEncoder sets a custom zapcore.Encoder for the file logger.

func WithServiceName added in v0.2.0

func WithServiceName(name string) Option

WithServiceName is an option to set the service name.

Jump to

Keyboard shortcuts

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