eslog

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: MIT Imports: 7 Imported by: 0

README

eslog : 🌈 slog.Handler that writes prettier logs

Package eslog implements a slog.Handler that writes prettier logs. Two modes are supported: pretty and json.

Supported logging levels:

  • Trace
  • Debug
  • Info
  • Warn
  • Error
  • Fatal

Pretty

Logging formatting in Pretty mode. In this mode, it's easy to navigate to the file position where the log was called.

Prettier example

JSON

Logging formatting in JSON mode.

JSON example

Installation

go get github.com/eliofery/eslog

Usage

// Configures the logger with the specified settings.
config := eslog.Config{
    Level:     "info", // trace, debug, info, warn, error, fatal (info: default)
    AddSource: true,
    JSON:      false,
}

// Sets the logging level.
lvl := new(slog.LevelVar)
lvl.Set(config.Leveler())

// Creates a new instance of eslog with the configured settings.
logger := eslog.New(pretty.NewHandler(os.Stdout, &pretty.HandlerOptions{
    SlogOptions: &slog.HandlerOptions{
        Level:     lvl,
        AddSource: config.AddSource,
    },
    JSON: config.JSON,
}), lvl)

// Overrides the logging level.
logger.SetLevel(eslog.LevelTrace)
//logger.SetLevel(slog.LevelDebug)
//logger.SetLevel(slog.LevelInfo)
//logger.SetLevel(slog.LevelWarn)
//logger.SetLevel(slog.LevelError)
//logger.SetLevel(eslog.LevelFatal)

// Logs messages at different levels.
logger.Trace("Trace example", slog.Any("message", "trace message"))
logger.Debug("Debug example", slog.Any("message", "debug message"))
logger.Info("Info example", slog.Any("message", "info message"))
logger.Warn("Warn example", slog.Any("message", "warn message"))
logger.Error("Error example", slog.Any("message", "error message"))
logger.Fatal("Fatal example", slog.Any("message", "fatal message"))
Customize Attributes

ReplaceAttr can be used to alter or drop attributes. See slog.HandlerOptions for details.

lvl := new(slog.LevelVar)
lvl.Set(slog.LevelInfo)
	
eslog.New(pretty.NewHandler(os.Stdout, &pretty.HandlerOptions{
    SlogOptions: &slog.HandlerOptions{
        ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
            switch a.Key {
            case slog.SourceKey:
                return func(a slog.Attr) slog.Attr {
                    source := a.Value.Any().(slog.Source)
    
                    pwd, err := os.Getwd()
                    if err != nil {
                        return a
                    }
    
                    relPath, err := filepath.Rel(pwd, source.File)
                    if err != nil {
                        return a
                    }
    
                    basePath := filepath.Base(relPath)
    
                    formattedPath := fmt.Sprintf("%s:%d", basePath, source.Line)
    
                    return slog.Attr{
                        Key:   a.Key,
                        Value: slog.StringValue(formattedPath),
                    }
                }(a)
            case slog.LevelKey:
                return func(a slog.Attr) slog.Attr {
                    l := a.Value.Any().(slog.Level)
                    a.Value = slog.StringValue(l.String())
    
                    return a
                }(a)
            case slog.TimeKey:
                return func(a slog.Attr) slog.Attr {
                    const timestampFormat = "2006-01-02 15:04:05.999999999 -0700 -07"
    
                    t, err := time.Parse(timestampFormat, a.Value.String())
                    if err != nil {
                        return a
                    }
    
                    formattedTime := t.Format(time.DateTime)
                    a.Value = slog.StringValue(formattedTime)
    
                    return a
                }(a)
            default:
                return a
            }
        },
    },
}), lvl)

Support for the standard package slog

You can still use methods from the standard package slog.

lvl := new(slog.LevelVar)
lvl.Set(eslog.LevelTrace)
	
// NewTextHandler
eslog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{}), lvl)

// NewJSONHandler
eslog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{}), lvl)

Inspiration

I was inspired to write this package by the slog and tint.

Documentation

Overview

Package eslog is an extension of the pkg/log/slog.Logger logging package. This package formats logging messages in a human-readable form, contains two additional logging levels Trace and Fatal.

Includes Logger that combines functionality for setting logging level.

Demonstrates how to configure and use the logger with various logging levels and message types. It sets up the logger with custom configuration, including logging level and output format. Then, it overrides the logging level for demonstration purposes. Finally, it logs messages at different levels using the configured logger.

// Configures the logger with the specified settings.
config := eslog.Config{
	Level:     "info", // trace, debug, info, warn, error, fatal (info: default)
	AddSource: true,
	JSON:      false,
}

// Sets the logging level.
lvl := new(slog.LevelVar)
lvl.Set(config.Leveler())

// Creates a new instance of eslog with the configured settings.
logger := eslog.New(pretty.NewHandler(os.Stdout, &pretty.HandlerOptions{
	SlogOptions: &slog.HandlerOptions{
		Level:     lvl,
		AddSource: config.AddSource,
	},
	JSON: config.JSON,
}), lvl)

// Overrides the logging level.
logger.SetLevel(eslog.LevelTrace)
//logger.SetLevel(slog.LevelDebug)
//logger.SetLevel(slog.LevelInfo)
//logger.SetLevel(slog.LevelWarn)
//logger.SetLevel(slog.LevelError)
//logger.SetLevel(eslog.LevelFatal)

// Logs messages at different levels.
logger.Trace("Trace example", slog.Any("message", "trace message"))
logger.Debug("Debug example", slog.Any("message", "debug message"))
logger.Info("Info example", slog.Any("message", "info message"))
logger.Warn("Warn example", slog.Any("message", "warn message"))
logger.Error("Error example", slog.Any("message", "error message"))
logger.Fatal("Fatal example", slog.Any("message", "fatal message"))

Index

Constants

View Source
const (
	LevelTrace slog.Level = -8
	LevelFatal slog.Level = 12
)

Names for common levels. Complements standard slog levels. See: https://pkg.go.dev/golang.org/x/exp/slog#Level

Variables

View Source
var Level = map[string]slog.Level{
	"trace": LevelTrace,
	"debug": slog.LevelDebug,
	"info":  slog.LevelInfo,
	"warn":  slog.LevelWarn,
	"error": slog.LevelError,
	"fatal": LevelFatal,
}

Level names for common levels.

Functions

This section is empty.

Types

type Config

type Config struct {
	Level     string `yaml:"level" env-default:"info"`
	AddSource bool   `yaml:"add-source"`
	JSON      bool   `yaml:"json"`
}

Config contains configuration options for logging.

func (*Config) Leveler

func (c *Config) Leveler() slog.Level

Leveler returns the logging level specified in the configuration.

type Leveler

type Leveler interface {
	// SetLevel sets the logging level.
	SetLevel(level slog.Level)
}

Leveler is an interface for setting the logging level.

type Logger

type Logger interface {
	// Leveler is an interface for setting the logging level.
	Leveler

	// Loggerer is an interface for logging messages at different levels.
	// Complements standard slog methods.
	Loggerer

	// Printerer is an interface for printing messages.
	Printerer

	// Slogger returns the underlying [slog.Logger].
	Slogger() *slog.Logger
}

Logger is an interface that combines functionality for setting logging level.

func New

func New(handler slog.Handler, lvl *slog.LevelVar) Logger

New creates a new instance of Logger. See: https://github.com/golang/go/issues/59145#issuecomment-1481920720

type Loggerer

type Loggerer interface {
	// Trace logs a message at trace level.
	Trace(msg string, args ...any)

	// Debug logs a message at trace level.
	Debug(msg string, args ...any)

	// Info logs a message at trace level.
	Info(msg string, args ...any)

	// Warn logs a message at trace level.
	Warn(msg string, args ...any)

	// Error logs a message at trace level.
	Error(msg string, args ...any)

	// Fatal logs a message at trace level.
	Fatal(msg string, args ...any)
}

Loggerer is an interface for logging messages at different levels. Complements standard slog methods.

type Printerer

type Printerer interface {
	// Sprintf formats according to a format specifier and returns the resulting string.
	Sprintf(msg string, args ...any) string

	// Fatalf formats according to a format specifier and prints the resulting string,
	// then exits the program with a non-zero exit status.
	Fatalf(msg string, args ...any)

	// Print prints the message.
	Print(msg string, args ...any)

	// Printf formats according to a format specifier and prints the resulting string.
	Printf(msg string, args ...any)
}

Printerer is an interface for printing messages.

Directories

Path Synopsis
Package pretty is a handler for slog that formats messages beautifully.
Package pretty is a handler for slog that formats messages beautifully.

Jump to

Keyboard shortcuts

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