Skip to content

errlog is a slog handler that logs errors with stack traces easily.

License

Notifications You must be signed in to change notification settings

ichizero/errlog

Repository files navigation

errlog

Test Go Reference Codecov Go Report Card

errlog is a error logging package based on log/slog standard library. It provides error logging with stack trace and source location. It does not require any third-party package.

🚀 Installation

go get github.com/ichizero/errlog

🧐 Usage

Initialize logger

errlog.NewHandler wraps slog.Handler, so you can provide *slog.JSONHandler, *slog.TextHandler, or any other handler.

h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{AddSource: true})
hErr := errlog.NewHandler(h, &errlog.HandlerOptions{OverrideSource: true, SuppressStackTrace: false})
slog.SetDefault(slog.New(hErr))

Logging error with stack trace

With errlog.Err

errlog.Err wraps error with stack trace and returns slog.Attr with key error.

err := errors.New("test error")
slog.ErrorContext(ctx, "test", errlog.Err(err))

With custom error

errlog.NewHandler outputs stack trace with the error that implements errlog.StackTrace interface, so you can provide custom error with stack trace.

type yourCustomError struct {
	err error
	stack []uintptr
}

func (e yourCustomError) Stack() []uintptr {
	return e.stack
}

If so, you can log stack trace without using errlog.Err.

err := newYourCustomError("error")
slog.ErrorContext(ctx, "test", slog.Any("error", err))

Example usage

package main

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

	"github.com/ichizero/errlog"
)

func main() {
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{AddSource: true})
	hErr := errlog.NewHandler(h, &errlog.HandlerOptions{OverrideSource: true, SuppressStackTrace: false})
	slog.SetDefault(slog.New(hErr))

	ctx := context.Background()

	err := errors.New("test error")
	slog.ErrorContext(ctx, "test", errlog.Err(err))

	err = errlog.WrapError(err)
	slog.ErrorContext(ctx, "test", slog.Any("error", err))
}