slogcolor

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2024 License: MIT Imports: 13 Imported by: 8

README

🌈 slogcolor

Go Reference Go Report Card GitHub license

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/MatusOllah/slogcolor

Basic Usage

package main

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

    "github.com/MatusOllah/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")
}
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/MatusOllah/slogcolor"
)

func main() {
	opts := slogcolor.DefaultOptions
	opts.Level = slog.LevelDebug
	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")
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Prefix added in v1.1.0

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
}

func NewHandler

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

NewHandler creates a new Handler.

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
}
var DefaultOptions *Options = &Options{
	Level:         slog.LevelInfo,
	TimeFormat:    time.DateTime,
	SrcFileMode:   ShortFile,
	SrcFileLength: 0,
	MsgPrefix:     color.HiWhiteString("| "),
	MsgLength:     0,
	MsgColor:      color.New(),
	NoColor:       false,
}

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/frajer/go/src/myapp/main.go:69).
	LongFile
)

Jump to

Keyboard shortcuts

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