From 804a8e5be68dd093d72c68b14b9898aa4426fb28 Mon Sep 17 00:00:00 2001 From: Julian Strobl Date: Tue, 12 Dec 2023 13:39:37 +0100 Subject: [PATCH] Add AppLogger to test runs (#230) * [log] Do not create a new object of `GetAppLogger()` every time * [tests] Enable AppLogger during testing Signed-off-by: Julian Strobl --- testutil/network/network.go | 5 +++++ util/logger.go | 40 ++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/testutil/network/network.go b/testutil/network/network.go index 7838914..9c3064c 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -21,6 +21,7 @@ import ( "github.com/planetmint/planetmint-go/app" "github.com/planetmint/planetmint-go/config" "github.com/planetmint/planetmint-go/lib" + "github.com/planetmint/planetmint-go/util" ) type ( @@ -42,6 +43,10 @@ func New(t *testing.T, configs ...Config) *Network { } validatorTmpDir := t.TempDir() + // enable application logger in tests + appLogger := util.GetAppLogger() + appLogger.SetTestingLogger(t) + // set the proper root dir for the test environment so that the abci.go logic works appConfig := config.GetConfig() appConfig.SetRoot(validatorTmpDir + "/node0/simd") diff --git a/util/logger.go b/util/logger.go index 36dd9eb..7e3bae5 100644 --- a/util/logger.go +++ b/util/logger.go @@ -1,11 +1,21 @@ package util -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + "sync" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" +) type AppLogger struct { + testingLogger *testing.T } -var globalApplicationLoggerTag string +var ( + globalApplicationLoggerTag string + appLogger *AppLogger + initAppLogger sync.Once +) func init() { // Initialize the package-level variable @@ -13,17 +23,41 @@ func init() { } func GetAppLogger() *AppLogger { - return &AppLogger{} + initAppLogger.Do(func() { + appLogger = &AppLogger{ + testingLogger: nil, + } + }) + return appLogger +} + +func (logger *AppLogger) SetTestingLogger(testingLogger *testing.T) *AppLogger { + logger.testingLogger = testingLogger + return logger +} + +func (logger *AppLogger) testingLog(msg string, keyvals ...interface{}) { + if logger.testingLogger == nil { + return + } + if len(keyvals) == 0 { + logger.testingLogger.Log(msg) + return + } + logger.testingLogger.Log(msg, keyvals) } func (logger *AppLogger) Info(ctx sdk.Context, msg string, keyvals ...interface{}) { + logger.testingLog(globalApplicationLoggerTag+msg, keyvals...) ctx.Logger().Info(globalApplicationLoggerTag+msg, keyvals...) } func (logger *AppLogger) Debug(ctx sdk.Context, msg string, keyvals ...interface{}) { + logger.testingLog(globalApplicationLoggerTag+msg, keyvals...) ctx.Logger().Debug(globalApplicationLoggerTag+msg, keyvals...) } func (logger *AppLogger) Error(ctx sdk.Context, msg string, keyvals ...interface{}) { + logger.testingLog(globalApplicationLoggerTag+msg, keyvals...) ctx.Logger().Error(globalApplicationLoggerTag+msg, keyvals...) }