jeudi 14 mai 2020

A global variable becomes nil when called from another package in Golang

logger.go

package common
var once sync.Once
var Logger *logrus.Logger
func InitLogger() {
   once.Do(func() {
        Logger = logrus.New()
        Logger.Out = filename // file opened and *file assigned here for logging
    })

    return Logger
}

setup_test.go

package main
func setUp() {
    common.InitLogger()
    fmt.Println(common.Logger) // prints some pointer related things which means logger is initialized
}
func TestMain(m *testing.M) {
    fmt.Println("Starting Test...")
    setUp()
    code := m.Run()
    common.APILog.Println("Finishing Main...")
    os.Exit(code)
}

myapp_test.go

package myapp
func TestMyFunc(t *testing.T) {
    **t.Log(common.APILog)               // When i run go test ./... this Prints nil , Why ?**
    // Doing some tests
}

Due to this common.Logger.Println("some data") is giving nil pointer error everywhere As per my understanding once Logger is initialized it should be available as it is a global variable. I am definitely missing something subtle here. Please help

Aucun commentaire:

Enregistrer un commentaire