logger

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 10 Imported by: 1

README

Go Structured Logger

Go Reference Go Report Card License Release

A structured logging package for Go applications built on top of the standard library's slog package.

Features

  • Built on Go's standard library: Uses slog from Go 1.21+
  • Structured logging: Key-value pairs for better log filtering and analysis
  • Multiple output formats: JSON for production, text for development
  • Colored console output: Improves readability during local development
  • Customizable log levels: debug, info, warn, error
  • Source information: Automatically includes caller information (file:line)
  • Global logger: Convenient access throughout your application
  • Testing support: Mock logger for easy testing

Installation

go get github.com/legrch/logger

Quick Start

package main

import (
	"github.com/legrch/logger"
	"os"
)

func main() {
	// Initialize logger with default configuration
	cfg := &logger.Config{
		Level:           "info",
		Format:          "text",
		EnableColors:    true,
		EnableCaller:    true,
		CallerSkipFrame: 1,
	}
	
	log := logger.New(cfg)
	
	// Use the logger
	log.Info("application started", "version", "1.0.0")
	log.Debug("debug message") // Won't be shown with info level
	log.Error("something went wrong", "error", "connection refused", "retry", true)
	
	// With structured fields
	log.With("request_id", "abc123").Info("processing request")
	
	// Set as global logger
	logger.SetGlobal(log)
	
	// Use global logger elsewhere
	globalLogger := logger.Global()
	globalLogger.Info("using global logger")
}

Documentation

For detailed documentation, examples, and API reference, please visit:

License

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

Documentation

Index

Constants

View Source
const (
	FormatJSON    = "json"
	FormatConsole = "console"
)

Format constants

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, args ...any)

Debug logs a debug message using the default logger

func Default

func Default() *slog.Logger

Default returns the default logger instance

func Error

func Error(msg string, args ...any)

Error logs an error message using the default logger

func Info

func Info(msg string, args ...any)

Info logs an info message using the default logger

func Init

func Init(cfg *Config) error

Init initializes the logger with the given configuration and sets it as the default logger

func InitFromEnv

func InitFromEnv(env string) error

InitFromEnv initializes the logger from environment variables

func New

func New(cfg *Config) (*slog.Logger, error)

New creates a new slog.Logger with the given configuration

func NewMockLogger

func NewMockLogger() *slog.Logger

NewMockLogger creates a new mock logger

func SetDefault

func SetDefault(logger *slog.Logger)

SetDefault sets the default logger instance

func Warn

func Warn(msg string, args ...any)

Warn logs a warning message using the default logger

func With

func With(key string, value any) *slog.Logger

With adds structured context to the default logger

Types

type ColoredHandler

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

ColoredHandler is a slog.Handler that writes colored logs to an io.Writer.

func NewColoredHandler

func NewColoredHandler(w io.Writer, opts *slog.HandlerOptions, useJSON bool) *ColoredHandler

NewColoredHandler creates a new ColoredHandler that writes to w.

func (*ColoredHandler) Enabled

func (h *ColoredHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*ColoredHandler) Handle

func (h *ColoredHandler) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler.

func (*ColoredHandler) WithAttrs

func (h *ColoredHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*ColoredHandler) WithGroup

func (h *ColoredHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.

type Config

type Config struct {
	// Level is the minimum enabled logging level
	Level string `envconfig:"LEVEL" default:"info"`

	// Format is the log format ("json" or "console")
	Format string `envconfig:"FORMAT" default:"json"`

	// EnableCaller adds the file:line caller info to log output
	EnableCaller bool `envconfig:"ENABLE_CALLER" default:"true"`

	// EnableStacktrace enables automatic stacktrace capturing
	EnableStacktrace bool `envconfig:"ENABLE_STACKTRACE" default:"true"`

	// EnableColors enables colored output for console format
	EnableColors bool `envconfig:"ENABLE_COLORS" default:"false"`

	// Environment is the current environment (development, staging, production)
	Environment string `envconfig:"ENVIRONMENT" default:"production"`
}

Config holds all the logger-related configuration

type LegacyAdapter

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

LegacyAdapter adapts a *slog.Logger to the LegacyLogger interface

func (*LegacyAdapter) Debug

func (l *LegacyAdapter) Debug(args ...any)

Debug logs a debug message

func (*LegacyAdapter) Error

func (l *LegacyAdapter) Error(args ...any)

Error logs an error message

func (*LegacyAdapter) Info

func (l *LegacyAdapter) Info(args ...any)

Info logs an info message

func (*LegacyAdapter) Warn

func (l *LegacyAdapter) Warn(args ...any)

Warn logs a warning message

func (*LegacyAdapter) With

func (l *LegacyAdapter) With(key string, value any) LegacyLogger

With adds structured context to the logger

type LegacyLogger

type LegacyLogger interface {
	// Debug logs a debug message
	Debug(args ...any)
	// Info logs an info message
	Info(args ...any)
	// Warn logs a warning message
	Warn(args ...any)
	// Error logs an error message
	Error(args ...any)
	// With adds structured context to the logger
	With(key string, value any) LegacyLogger
}

LegacyLogger is the old logger interface, kept for backward compatibility

func NewLegacyAdapter

func NewLegacyAdapter(logger *slog.Logger) LegacyLogger

NewLegacyAdapter creates a new LegacyAdapter

type LogEntry

type LogEntry struct {
	Level   slog.Level
	Message string
	Attrs   []slog.Attr
}

LogEntry represents a log entry

type MockLogger

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

MockLogger is a mock implementation of slog.Handler for testing

func (*MockLogger) Clear

func (l *MockLogger) Clear()

Clear clears all log entries

func (*MockLogger) Enabled

func (*MockLogger) Enabled(_ context.Context, _ slog.Level) bool

Enabled implements slog.Handler.

func (*MockLogger) GetLogs

func (l *MockLogger) GetLogs() []LogEntry

GetLogs returns all log entries

func (*MockLogger) GetLogsByLevel

func (l *MockLogger) GetLogsByLevel(level slog.Level) []LogEntry

GetLogsByLevel returns log entries filtered by level

func (*MockLogger) Handle

func (l *MockLogger) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler.

func (*MockLogger) String

func (l *MockLogger) String() string

String returns a string representation of the log entries

func (*MockLogger) WithAttrs

func (l *MockLogger) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*MockLogger) WithGroup

func (l *MockLogger) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.

Directories

Path Synopsis
examples
colored command
formatting command

Jump to

Keyboard shortcuts

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