From d64a96f54f431120a3d69a7b42f3ddfafb8ecfbb Mon Sep 17 00:00:00 2001 From: Sami Hiltunen Date: Tue, 22 Aug 2023 12:17:28 +0300 Subject: Add a recording logger for tests Our tests are currently largely discarding all logs. This is done as we run our tests verbosely in the CI and the log output exceeded what the CI could at maximum display. Discarding the logs can make it more difficult to determine why the test exactly failed. This is especially true when concurrency is involved and a background worker not directly tied to the request fails. While the background worker would log the reason it failed, this is not visible in the tests. This commit solves the problem by adding a new logger that records its output and only prints it out if the test failed. This way in the general case we still have no log output in the tests but we will have logs when the test fails and we'd benefit from them. Ideally we'll standardise all test to use this logger and prevent usage of other loggers in tests. --- internal/testhelper/logger.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/internal/testhelper/logger.go b/internal/testhelper/logger.go index 63f165ae3..0b284924d 100644 --- a/internal/testhelper/logger.go +++ b/internal/testhelper/logger.go @@ -1,8 +1,8 @@ package testhelper import ( + "bytes" "fmt" - "io" "os" "path/filepath" "testing" @@ -12,6 +12,24 @@ import ( "gitlab.com/gitlab-org/gitaly/v16/internal/helper/perm" ) +// NewLogger returns a logger that records the log output and +// prints it out only if the test fails. +func NewLogger(tb testing.TB) *logrus.Logger { + logOutput := &bytes.Buffer{} + logger := logrus.New() //nolint:forbidigo + logger.Out = logOutput + + tb.Cleanup(func() { + if !tb.Failed() { + return + } + + tb.Logf("Recorded logs:\n%s\n", logOutput) + }) + + return logger +} + // NewDiscardingLogger creates a logger that discards everything. func NewDiscardingLogger(tb testing.TB) *logrus.Logger { logger := logrus.New() //nolint:forbidigo -- cgit v1.2.3