Skip to content

DefaultLogger on log/slog; remove logrus #9

Description

@TopherGopher

Part of the easymongo refactor (see PLAN.md on the refactor branch).

Working context (read this first)

Scope

  • logger.go: keep the exported Logger interface exactly as is (Debugf(format string, args ...interface{}), Errorf(format string, args ...interface{})) so callers are unaffected.
  • Reimplement DefaultLogger on *slog.Logger with a text handler to stderr at slog.LevelDebug, adding the attribute src=easymongo. NewDefaultLogger() signature unchanged. Add NewSlogLogger(l *slog.Logger) Logger so callers can plug in their own slog logger.
  • Remove github.com/sirupsen/logrus from go.mod (the connect_test.go fixture is handled by the test-suite issue).
  • Optional follow-up, not in scope here: align easymongo's Logger with mongotest's structured Logger so the logrus/zap/zerolog adapter modules from mongotest work for both. Note it in the doc comment as a possible future change.

Implementation details

type slogLogger struct{ l *slog.Logger }
func NewSlogLogger(l *slog.Logger) Logger { return &slogLogger{l: l.With("src", "easymongo")} }
func (s *slogLogger) Debugf(format string, args ...interface{}) { s.l.Debug(fmt.Sprintf(format, args...)) }
func (s *slogLogger) Errorf(format string, args ...interface{}) { s.l.Error(fmt.Sprintf(format, args...)) }
func NewDefaultLogger() *DefaultLogger { /* wraps NewSlogLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))) */ }

Keep the exported DefaultLogger type name so existing references compile; it can embed the slog-backed logger.

Also fix the pre-existing bug at connect.go in the debug monitor: conn.log.Errorf("...: %w. Raw reply: %s", err, e.Reply) uses %w with a non-fmt.Errorf function, which prints %!w(...); change to %v.

Tests first (logger_test.go)

  • NewSlogLogger with a slog.NewJSONHandler writing to a buffer: Debugf("x %d", 1) produces a record with level=DEBUG, msg="x 1", src=easymongo; Errorf produces level=ERROR.
  • NewDefaultLogger() returns a non-nil Logger and does not panic when called.
  • ConnectWith(uri).Debug().Logger(l).Connect() followed by a query results in at least one Debugf call on l (integration, via easymongotest).

Acceptance

  • grep logrus go.mod returns nothing.

Depends on: #8 (removes the logrus test fixture).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions