gogo-zap

How to send log to a different location : UberZap


I need to send logs to the different location in go zap logger.

How can I do that?


Solution

  • zap can send logs to anything that implemnts the WriteSyncer interface. Which is simply an io.Writer which has a Sync method. If you need to add a no-op Sync method you can use zapcore.AddSync, or if you need it to be safe for concurrent you can add a protecting mutex with zapcore.Lock.

    Basically you'd have something like

    var output zapcore.WriteSyncer = os.Stdout // for example
    zapOutput := zapcore.Lock(output)
    encoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
    // you could also use zap.NewDevelopmentEncoderConfig()
    // define what level you want to log
    priority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
        return lvl >= zapcore.ErrorLevel
    })
    // Join the outputs, encoders, and level-handling functions into
    // zapcore.Cores, then tee the four cores together.
    core := zapcore.NewTee(
        zapcore.NewCore(encoder, zapOutput, priority),
        // you can add other cores here to log to multiple places
    )
    
    logger := zap.New(core) // this is your logger
    defer logger.Sync()     // don't forget to sync
    logger.Info("constructed a logger") // example log
    

    See the docs for more detail.