zap-examples icon indicating copy to clipboard operation
zap-examples copied to clipboard

[Question] cutomlogger example.

Open etsangsplk opened this issue 6 years ago • 1 comments

I modified the example to experiment. zap is good if used along the published cases, but not friendly on customization.

What I am expecting is that since zap has parent and child logger relationship, I would expect the settings being passed down if they belong to the same descendants paths.

While it looks like the case in first half of example, but it does not look like the case for zap.WrapCore (prints debug and info messages after // ****** )

Know that WithOptions is just cloning, so it is probably doing the right thing, and not the right method to call. But then how can I do that?

	cfg := zap.Config{
		Encoding:         "json",
		Level:            zap.NewAtomicLevelAt(zapcore.DebugLevel),
		OutputPaths:      []string{"stderr"},
		ErrorOutputPaths: []string{"stderr"},
		EncoderConfig: zapcore.EncoderConfig{
			MessageKey: "message",

			LevelKey:    "level",
			EncodeLevel: zapcore.CapitalLevelEncoder,

			TimeKey:    "time",
			EncodeTime: zapcore.ISO8601TimeEncoder,

			CallerKey:    "caller",
			EncodeCaller: zapcore.ShortCallerEncoder,
		},
	}
	logger, _ = cfg.Build()
        childlogger := logger.With(zap.String("logger", "child generation 1"))

	logger.Debug("This is a DEBUG message")
	logger.Info("This is an INFO message")
	logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2))
       // ****** Child logger also has the same logging level settings ****
       childlogger.Debug("This is a DEBUG message from child logger") 
       childlogger.Info("This is an INFO message from child logger") 

	fmt.Printf("\n*** Same logger with console logging enabled instead with Info level now\n\n")

	logger.WithOptions(
		zap.WrapCore(
			func(zapcore.Core) zapcore.Core {
				return zapcore.NewCore(zapcore.NewConsoleEncoder(cfg.EncoderConfig), zapcore.AddSync(os.Stderr), zapcore.InfoLevel)
			})).Debug("This is a DEBUG message, but should not be printed")

     // ****** new settings no longer honored after this line ****
    logger.Debug("This is a DEBUG message, but should not be printed") 

    childlogger.Debug("This is a DEBUG message from child logger") 
    childlogger.Info("This is an INFO message from child logger") 

etsangsplk avatar May 16 '18 21:05 etsangsplk

Yes, I encountered this. In my project, I am approaching this problem of independent child loggers differently. I will have an example out by this weekend. Thanks for your input!

sandipb avatar May 17 '18 09:05 sandipb