slogcolor

package module
v0.0.0-...-1a3602b Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2025 License: MIT Imports: 15 Imported by: 0

README

🌈 slogcolor

Go Reference Go Report Card Go GitHub license Made in Slovakia

screenshot

slogcolor is a little, customizable color handler for log/slog. It enhances log readability by color-coding log levels and supports flexible formatting options. Its output is inspired by XMRig and zerolog.

Installation

Run:

go get -u github.com/otheroffram/slogcolor

Basic Usage

package main

import (
    "os"
    "time"
    "errors"
    "log/slog"

    "github.com/otheroffram/slogcolor"
)

func main() {
    // Configure slog to use slogcolor by default for colored output
    slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, slogcolor.DefaultOptions)))

    slog.Info("Initializing")
    slog.Debug("Init done", "duration", 500*time.Millisecond)
    slog.Warn("Slow request!", "method", "GET", "path", "/api/users", "duration", 750*time.Millisecond)
    slog.Error("DB connection lost!", "err", errors.New("connection reset"), "db", "horalky")
}
Default options

slogcolor provides a set of predefined options to simplify configuration. You can use these default options via DefaultOptions, or simply pass nil for the same effect.

slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, slogcolor.DefaultOptions)))

// or

slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, nil)))

The behavior is identical in both cases, so you can choose based on your coding style or preference.

Customized output format

The output format can also be customized using the Options like this:

opts := &slogcolor.Options{
    Level:         slog.LevelDebug,
    TimeFormat:    time.RFC3339,
    SrcFileMode:   slog.Nop,
}
slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts)))

or like this:

opts := slogcolor.DefaultOptions
opts.Level = slog.LevelDebug
opts.TimeFormat = time.RFC3339
opts.SrcFileMode = slog.Nop

slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts)))
Prefixes

Prefixes can be useful for adding context to log messages, such as identifying different subsystems or components (e.g., DB, SceneController, Network) that generated the log.

Messages can be prefixed with Prefix like this:

slog.Info(slogcolor.Prefix("MyPrefix", "kajšmentke"))
slog.Info(slogcolor.Prefix("SceneController", "switching scene"), "scene", "MainMenuScene")

// or

slog.Info(slogcolor.Prefix("MyPrefix")+"kajšmentke")
slog.Info(slogcolor.Prefix("SceneController")+"switching scene", "scene", "MainMenuScene")

It can also be used as an alias for ease of use, especially when you frequently use prefixes, like this:

var P = slogcolor.Prefix

slog.Info(P("MyPrefix", "kajšmentke"))

// or

slog.Info(P("MyPrefix")+"kajšmentke")
Disable colors

Colors are enabled by default but can be disabled using Options.NoColor. Particularly useful for automatically enabling colors based on the terminal capabilities using e.g. the go-isatty package.

w := os.Stderr

opts := slogcolor.DefaultOptions
opts.NoColor = !isatty.IsTerminal(w.Fd())

slog.SetDefault(slog.New(slogcolor.NewHandler(w, opts)))

License

Licensed under the MIT License (see LICENSE)

Documentation

Overview

slogcolor implements a color handler for log/slog.

Example
package main

import (
	"errors"
	"log/slog"
	"os"
	"time"

	"github.com/fatih/color"
	"github.com/otheroffram/slogcolor"
)

func main() {
	opts := slogcolor.DefaultOptions
	opts.Level = slog.LevelDebug

	opts.LevelTags = map[slog.Level]string{
		slog.LevelInfo: color.New(color.BgCyan, color.FgBlack).Sprint("Info"),
	}

	slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts)))
	slog.Info("Initializing")
	slog.Debug("Init done", "duration", 500*time.Millisecond)
	slog.Warn("Slow request!", "method", "GET", "path", "/api/users", "duration", 750*time.Millisecond)
	slog.Error("DB connection lost!", "err", errors.New("connection reset"), "db", "horalky")
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultLevelTags = map[slog.Level]string{
	slog.LevelDebug: color.New(color.BgCyan, color.FgHiWhite).Sprint("DEBUG"),
	slog.LevelInfo:  color.New(color.BgGreen, color.FgHiWhite).Sprint("INFO "),
	slog.LevelWarn:  color.New(color.BgYellow, color.FgHiWhite).Sprint("WARN "),
	slog.LevelError: color.New(color.BgRed, color.FgHiWhite).Sprint("ERROR"),
}

DefaultLevelTags are the default level tags.

Functions

func Prefix

func Prefix(prefix string, msg ...string) string

Prefix prepends a colored prefix to msg.

Types

type Handler

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

Handler is a colored slog handler.

func NewHandler

func NewHandler(out io.Writer, opts *Options) *Handler

NewHandler creates a new Handler with the specified options. If opts is nil, uses DefaultOptions.

func (*Handler) Enabled

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

Enabled implements slog.Handler.Enabled .

func (*Handler) Handle

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

Handle implements slog.Handler.Handle .

func (*Handler) WithAttrs

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

WithAttrs implements slog.Handler.WithAttrs .

func (*Handler) WithGroup

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

WithGroup implements slog.Handler.WithGroup .

type Options

type Options struct {
	// Level reports the minimum level to log.
	// Levels with lower levels are discarded.
	// If nil, the Handler uses [slog.LevelInfo].
	Level slog.Leveler

	// TimeFormat is the time format.
	TimeFormat string

	// SrcFileMode is the source file mode.
	SrcFileMode SourceFileMode

	// SrcFileLength to show fixed length filename to line up the log output, default 0 shows complete filename.
	SrcFileLength int

	// MsgPrefix to show prefix before message, default: white colored "| ".
	MsgPrefix string

	// MsgColor is the color of the message, default to empty.
	MsgColor *color.Color

	// MsgLength to show fixed length message to line up the log output, default 0 shows complete message.
	MsgLength int

	// NoColor disables color, default: false.
	NoColor bool

	// LevelTags is level tag for message, default: DefaultLevelStyles
	LevelTags map[slog.Level]string
}

Options represents the options passed into NewHandler.

var DefaultOptions *Options = &Options{
	Level:         slog.LevelInfo,
	TimeFormat:    time.DateTime,
	SrcFileMode:   ShortFile,
	SrcFileLength: 0,
	MsgPrefix:     color.HiWhiteString("| "),
	MsgLength:     0,
	MsgColor:      color.New(),
	NoColor:       false,
	LevelTags:     DefaultLevelTags,
}

DefaultOptions are the default options.

type SourceFileMode

type SourceFileMode int
const (
	// Nop does nothing.
	Nop SourceFileMode = iota

	// ShortFile produces only the filename (for example main.go:69).
	ShortFile

	// LongFile produces the full file path (for example /home/user/go/src/myapp/main.go:69).
	LongFile
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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