Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replacing logrus with slog v1 #2010

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/proxy/actions/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func App(logger *log.Logger, conf *config.Config) (http.Handler, error) {
conf.GoEnv,
)
if err != nil {
logger.Info(err)
logger.Info(err.Error())
} else {
defer flushTraces()
}
Expand All @@ -87,7 +87,7 @@ func App(logger *log.Logger, conf *config.Config) (http.Handler, error) {
// was specified by the user.
flushStats, err := observ.RegisterStatsExporter(r, conf.StatsExporter, Service)
if err != nil {
logger.Info(err)
logger.Info(err.Error())
} else {
defer flushStats()
}
Expand Down
8 changes: 4 additions & 4 deletions cmd/proxy/actions/basicauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package actions
import (
"bytes"
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gomods/athens/pkg/log"
"github.com/sirupsen/logrus"
)

var basicAuthTests = [...]struct {
Expand Down Expand Up @@ -70,10 +70,10 @@ func TestBasicAuth(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, tc.path, nil)
r.SetBasicAuth(tc.user, tc.pass)
lggr := log.New("none", logrus.DebugLevel, "")
buf := &bytes.Buffer{}
lggr.Out = buf
ctx := log.SetEntryInContext(context.Background(), lggr)
lggr := log.New("none", slog.LevelDebug, "", buf)
entry := lggr.WithFields(map[string]any{})
ctx := log.SetEntryInContext(context.Background(), entry)
r = r.WithContext(ctx)
handler.ServeHTTP(w, r)
resp := w.Result()
Expand Down
6 changes: 3 additions & 3 deletions cmd/proxy/actions/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ package actions
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"strconv"
"time"

"github.com/gomods/athens/pkg/errors"
"github.com/gomods/athens/pkg/index"
"github.com/gomods/athens/pkg/log"
"github.com/sirupsen/logrus"
)

// indexHandler implements GET baseURL/index.
Expand Down Expand Up @@ -46,13 +46,13 @@ func getIndexLines(r *http.Request, index index.Indexer) ([]*index.Line, error)
if limitStr := r.FormValue("limit"); limitStr != "" {
limit, err = strconv.Atoi(limitStr)
if err != nil || limit <= 0 {
return nil, errors.E(op, err, errors.KindBadRequest, logrus.InfoLevel)
return nil, errors.E(op, err, errors.KindBadRequest, slog.LevelInfo)
}
}
if sinceStr := r.FormValue("since"); sinceStr != "" {
since, err = time.Parse(time.RFC3339, sinceStr)
if err != nil {
return nil, errors.E(op, err, errors.KindBadRequest, logrus.InfoLevel)
return nil, errors.E(op, err, errors.KindBadRequest, slog.LevelInfo)
}
}
list, err := index.Lines(r.Context(), since, limit)
Expand Down
17 changes: 9 additions & 8 deletions cmd/proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"flag"
"fmt"
stdlog "log"
"log/slog"
"net"
"net/http"
_ "net/http/pprof"
Expand All @@ -18,7 +19,6 @@ import (
"github.com/gomods/athens/pkg/build"
"github.com/gomods/athens/pkg/config"
athenslog "github.com/gomods/athens/pkg/log"
"github.com/sirupsen/logrus"
)

var (
Expand All @@ -37,21 +37,22 @@ func main() {
stdlog.Fatalf("Could not load config file: %v", err)
}

logLvl, err := logrus.ParseLevel(conf.LogLevel)
var logLvl slog.Level
err = logLvl.UnmarshalText([]byte(conf.LogLevel))
if err != nil {
stdlog.Fatalf("Could not parse log level %q: %v", conf.LogLevel, err)
}

logger := athenslog.New(conf.CloudRuntime, logLvl, conf.LogFormat)
logger := athenslog.New(conf.CloudRuntime, logLvl, conf.LogFormat, os.Stdout)

// Turn standard logger output into logrus Errors.
logrusErrorWriter := logger.WriterLevel(logrus.ErrorLevel)
// Turn standard logger output into slog Errors.
slogErrorWriter := logger.WriterLevel(slog.LevelError)
defer func() {
if err := logrusErrorWriter.Close(); err != nil {
logger.WithError(err).Warn("Could not close logrus writer pipe")
if err := slogErrorWriter.Close(); err != nil {
logger.WithError(err).Warn("Could not close slog writer pipe")
}
}()
stdlog.SetOutput(logrusErrorWriter)
stdlog.SetOutput(slogErrorWriter)
stdlog.SetFlags(stdlog.Flags() &^ (stdlog.Ldate | stdlog.Ltime))

handler, err := actions.App(logger, conf)
Expand Down
27 changes: 22 additions & 5 deletions pkg/download/protocol_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
"log/slog"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -504,11 +505,27 @@ var _ log.Entry = &testEntry{}
func (e *testEntry) Debugf(format string, args ...any) {
e.msg = format
}
func (*testEntry) Infof(format string, args ...any) {}
func (*testEntry) Warnf(format string, args ...any) {}
func (*testEntry) Errorf(format string, args ...any) {}
func (*testEntry) WithFields(fields map[string]any) log.Entry { return nil }
func (*testEntry) SystemErr(err error) {}
func (*testEntry) Infof(format string, args ...any) {}
func (*testEntry) Warnf(format string, args ...any) {}
func (*testEntry) Errorf(format string, args ...any) {}
func (*testEntry) Fatalf(format string, args ...any) {}
func (*testEntry) Panicf(format string, args ...any) {}
func (*testEntry) Printf(format string, args ...any) {}

func (*testEntry) Debug(args ...any) {}
func (*testEntry) Info(args ...any) {}
func (*testEntry) Warn(args ...any) {}
func (*testEntry) Error(args ...any) {}
func (*testEntry) Fatal(args ...any) {}
func (*testEntry) Panic(args ...any) {}
func (*testEntry) Print(args ...any) {}

func (*testEntry) WithFields(fields map[string]any) log.Entry { return nil }
func (*testEntry) SystemErr(err error) {}
func (*testEntry) WithField(key string, value any) log.Entry { return nil }
func (*testEntry) WithError(err error) log.Entry { return nil }
func (*testEntry) WithContext(ctx context.Context) log.Entry { return nil }
func (*testEntry) WriterLevel(level slog.Level) *io.PipeWriter { return nil }

func Test_copyContextWithCustomTimeout(t *testing.T) {
testEntry := &testEntry{}
Expand Down
23 changes: 10 additions & 13 deletions pkg/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ package errors
import (
"errors"
"fmt"
"log/slog"
"net/http"
"runtime"

"github.com/sirupsen/logrus"
)

// Kind enums.
Expand Down Expand Up @@ -37,7 +36,7 @@ type Error struct {
Module M
Version V
Err error
Severity logrus.Level
Severity slog.Level
}

// Error returns the underlying error's
Expand Down Expand Up @@ -111,7 +110,7 @@ func E(op Op, args ...any) error {
e.Module = a
case V:
e.Version = a
case logrus.Level:
case slog.Level:
e.Severity = a
case int:
e.Kind = a
Expand All @@ -126,17 +125,15 @@ func E(op Op, args ...any) error {
// Severity returns the log level of an error
// if none exists, then the level is Error because
// it is an unexpected.
func Severity(err error) logrus.Level {
func Severity(err error) slog.Level {
var e Error
if !errors.As(err, &e) {
return logrus.ErrorLevel
return slog.LevelError
}

// if there's no severity (0 is Panic level in logrus
// which we should not use since cloud providers only have
// debug, info, warn, and error) then look for the
// if there's no severity then look for the
// child's severity.
if e.Severity < logrus.ErrorLevel {
if e.Severity < slog.LevelError {
return Severity(e.Err)
}

Expand All @@ -146,13 +143,13 @@ func Severity(err error) logrus.Level {
// Expect is a helper that returns an Info level
// if the error has the expected kind, otherwise
// it returns an Error level.
func Expect(err error, kinds ...int) logrus.Level {
func Expect(err error, kinds ...int) slog.Level {
for _, kind := range kinds {
if Kind(err) == kind {
return logrus.InfoLevel
return slog.LevelInfo
}
}
return logrus.ErrorLevel
return slog.LevelError
}

// Kind recursively searches for the
Expand Down
22 changes: 11 additions & 11 deletions pkg/errors/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package errors

import (
"errors"
"log/slog"
"net/http"
"testing"

"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
Expand Down Expand Up @@ -35,16 +35,16 @@ func TestSeverity(t *testing.T) {
msg := "test error"

err := E(op, msg)
require.Equal(t, logrus.ErrorLevel, Severity(err))
require.Equal(t, slog.LevelError, Severity(err))

err = E(op, msg, logrus.WarnLevel)
require.Equal(t, logrus.WarnLevel, Severity(err))
err = E(op, msg, slog.LevelWarn)
require.Equal(t, slog.LevelWarn, Severity(err))

err = E(op, err)
require.Equal(t, logrus.WarnLevel, Severity(err))
require.Equal(t, slog.LevelWarn, Severity(err))

err = E(op, err, logrus.InfoLevel)
require.Equal(t, logrus.InfoLevel, Severity(err))
err = E(op, err, slog.LevelInfo)
require.Equal(t, slog.LevelInfo, Severity(err))
}

func TestKind(t *testing.T) {
Expand Down Expand Up @@ -85,14 +85,14 @@ func TestExpect(t *testing.T) {
err := E("TestExpect", "error message", KindBadRequest)

severity := Expect(err, KindBadRequest)
require.Equalf(t, severity, logrus.InfoLevel, "expected an info level log but got %v", severity)
require.Equalf(t, severity, slog.LevelInfo, "expected an info level log but got %v", severity)

severity = Expect(err, KindAlreadyExists)
require.Equalf(t, severity, logrus.ErrorLevel, "expected an error level but got %v", severity)
require.Equalf(t, severity, slog.LevelError, "expected an error level but got %v", severity)

severity = Expect(err, KindAlreadyExists, KindBadRequest)
require.Equalf(t, severity, logrus.InfoLevel, "expected an info level log but got %v", severity)
require.Equalf(t, severity, slog.LevelInfo, "expected an info level log but got %v", severity)

severity = Expect(err, KindAlreadyExists, KindNotImplemented)
require.Equalf(t, severity, logrus.ErrorLevel, "expected an error level but got %v", severity)
require.Equalf(t, severity, slog.LevelError, "expected an error level but got %v", severity)
}
Loading
Loading