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

Quieter fxtest logger #1226

Open
satazor opened this issue Jul 27, 2024 · 0 comments
Open

Quieter fxtest logger #1226

satazor opened this issue Jul 27, 2024 · 0 comments

Comments

@satazor
Copy link

satazor commented Jul 27, 2024

Is your feature request related to a problem? Please describe.

The current fxtest logger provided by fxtest.WithTestLogger is quite verbose, printing everything. When something fails in tests, I have to scroll down all the log messages until I find information about the actual error.

Describe the solution you'd like
An option that would print only errors, akin to how fxevent.SlogLogger where we can do:

	slogger := &fxevent.SlogLogger{Logger: slog.Default()}
	slogger.UseLogLevel(-1000)

To suppress every log, except errors.

Describe alternatives you've considered
Implementing a package like so:

// tbWriter is a io.Writer that writes to the provided test logger.
type tbWriter struct {
	t testing.TB
}

// Write writes the provided bytes to the underlying testing.TB.
func (w tbWriter) Write(bs []byte) (int, error) {
	w.t.Logf("%s", bs)

	return len(bs), nil
}

// QuietConsoleLogger is a fx logger that only logs errors.
type QuietConsoleLogger struct {
	fxevent.ConsoleLogger
}

// LogEvent logs the provided event if it is an error.
func (m QuietConsoleLogger) LogEvent(event fxevent.Event) {
	rv := reflect.Indirect(reflect.ValueOf(event))
	errRv := rv.FieldByName("Err")

	if !errRv.IsValid() {
		return
	}

	err, ok := errRv.Interface().(error)

	if ok && err != nil {
		m.ConsoleLogger.LogEvent(event)
	}
}

// WithQuietTestLogger provides a fx logger for tests that is silent except on errors.
func WithQuietTestLogger(t testing.TB) fxevent.Logger {
	return QuietConsoleLogger{
		ConsoleLogger: fxevent.ConsoleLogger{
			W: tbWriter{t},
		},
	}
}

Is this a breaking change?
No.

Additional context
N/A

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

No branches or pull requests

2 participants