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

What is the corrrect way to use zap across multiple files? #924

Closed
albert-csms opened this issue Feb 25, 2021 · 3 comments
Closed

What is the corrrect way to use zap across multiple files? #924

albert-csms opened this issue Feb 25, 2021 · 3 comments

Comments

@albert-csms
Copy link

albert-csms commented Feb 25, 2021

I'm trying to figure out how to use zap across multiple files. It seems I'm not the only one with this confusion. In that link though, the OP chooses to replace globals, but the FAQ says to avoid when possible. I'm am not migrating, so I don't think that's the right solution for me.

In all the examples that are provided in the docs, zap is used only in main.go, but I've yet to find any examples on the docs (or elsewhere), with multiple files. This is how I am attempting to use zap:

In pkg/util/logger.go, I have

type ZapLogger struct {
	ZLog *zap.Logger
}

func ZapLog() *ZapLogger {
	lgr, err := zap.NewProduction()
	if err != nil {
		log.Fatalf("Status: Failed to initialize zap logger: %v", err)
	}
	lgr.Info("Zap log is now initialized")
	return &ZapLogger{ZLog: lgr}
}

func (z *ZapLogger) DebugLog(msg string, fields ...zap.Field) {
	if debugEnabled {
		z.ZLog.Debug(msg, zap.Field...)
	}
}

Then in cmd/server/server.go, I have:

func main() {
	zLgr := util.ZapLog()
	logger := zLgr.ZLog
	defer logger.Sync()

      //...
}

Then in other packages where I need to log, I import pkg/util, and call util.DebugLog("asdf", zap.String("qwerty")

Would this be the correct or an acceptable way of using zap?

@prashantv
Copy link
Collaborator

We recommend using dependency injection, and passing *zap.Logger explicitly as part of constructors. See the kafka-client in uber-go as an example: https://github.com/uber-go/kafka-client/blob/8b3555b395f960371e07e54d761130bf2e25638a/client.go#L48

@qiankunxienb
Copy link

Is there any way to register the *zap.Logger instance as a global, so that I will only set the format in main.go and use it in any other files in this runtime? Just like Python's logging or loguru.

@prashantv
Copy link
Collaborator

You can initialize a logger and set it as the global logger, and then use zap.L() to access the global logger in your callsites, see example.

However, it's better to pass the *zap.Logger explicitly as mentioned above.

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

No branches or pull requests

3 participants