Replace Echo logger with slog. (#67)

* Replace Echo logger with slog.
This commit is contained in:
Mike Stefanello 2024-06-14 21:01:48 -04:00 committed by GitHub
parent 97bef0257e
commit c8a3d64918
14 changed files with 315 additions and 57 deletions

22
pkg/log/log.go Normal file
View file

@ -0,0 +1,22 @@
package log
import (
"log/slog"
"github.com/labstack/echo/v4"
"github.com/mikestefanello/pagoda/pkg/context"
)
// Set sets a logger in the context
func Set(ctx echo.Context, logger *slog.Logger) {
ctx.Set(context.LoggerKey, logger)
}
// Ctx returns the logger stored in context, or provides the default logger if one is not present
func Ctx(ctx echo.Context) *slog.Logger {
if l, ok := ctx.Get(context.LoggerKey).(*slog.Logger); ok {
return l
}
return slog.Default()
}

21
pkg/log/log_test.go Normal file
View file

@ -0,0 +1,21 @@
package log
import (
"testing"
"github.com/labstack/echo/v4"
"github.com/mikestefanello/pagoda/pkg/tests"
"github.com/stretchr/testify/assert"
)
func TestCtxSet(t *testing.T) {
ctx, _ := tests.NewContext(echo.New(), "/")
logger := Ctx(ctx)
assert.NotNil(t, logger)
logger = logger.With("a", "b")
Set(ctx, logger)
got := Ctx(ctx)
assert.Equal(t, got, logger)
}