Created
June 15, 2020 20:18
-
-
Save reitzig/2d53098861b6c1b7fcdfb065b4a81f2d to your computer and use it in GitHub Desktop.
Go logging with Zap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +build test | |
package main | |
import "go.uber.org/zap" | |
func makeLogger() (*zap.Logger, error) { | |
return zap.NewDevelopment() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +build !test | |
package main | |
import ( | |
"go.uber.org/zap" | |
"go.uber.org/zap/zapcore" | |
) | |
func makeLogger() (*zap.Logger, error) { | |
prodConfig := zap.NewProductionConfig() | |
prodConfig.Encoding = "console" | |
prodConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder | |
prodConfig.EncoderConfig.EncodeDuration= zapcore.StringDurationEncoder | |
return prodConfig.Build() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"go.uber.org/zap" | |
) | |
func main() { | |
logger, err := makeLogger() | |
if err != nil { | |
panic(err) | |
} | |
defer logger.Sync() | |
undo := zap.ReplaceGlobals(logger) | |
defer undo() | |
logger.Debug("Only in testing!") | |
logger.Warn("Always!") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -u | |
go get -u 'go.uber.org/zap' | |
go build -tags test -o example | |
echo "TEST:" && ./example | |
# See two messages! | |
go build -o example | |
echo "PROD:" && ./example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runs like this (Go 1.14.4, zap v1.15.0):