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 all 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
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ require (
github.com/lib/pq v1.10.9
github.com/minio/minio-go/v6 v6.0.57
github.com/mitchellh/go-homedir v1.1.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/afero v1.11.0
github.com/stretchr/testify v1.9.0
github.com/technosophos/moniker v0.0.0-20180509230615-a5dbd03a2245
Expand Down
12 changes: 0 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1188,18 +1188,6 @@ github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAm
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw=
github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
Expand Down
28 changes: 20 additions & 8 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 @@ -501,14 +502,25 @@ type testEntry struct {

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 (e *testEntry) Debugf(format string, args ...any) { e.msg = format }
func (e *testEntry) Infof(format string, args ...any) { e.msg = format }
func (e *testEntry) Warnf(format string, args ...any) { e.msg = format }
func (e *testEntry) Errorf(format string, args ...any) { e.msg = format }
func (e *testEntry) Fatalf(format string, args ...any) { e.msg = format }
func (e *testEntry) Printf(format string, args ...any) { e.msg = format }

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) 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