Skip to content

Instantly share code, notes, and snippets.

@reitzig
Created June 15, 2020 20:18
Show Gist options
  • Save reitzig/2d53098861b6c1b7fcdfb065b4a81f2d to your computer and use it in GitHub Desktop.
Save reitzig/2d53098861b6c1b7fcdfb065b4a81f2d to your computer and use it in GitHub Desktop.
Go logging with Zap
// +build test
package main
import "go.uber.org/zap"
func makeLogger() (*zap.Logger, error) {
return zap.NewDevelopment()
}
// +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()
}
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!")
}
#!/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
@reitzig
Copy link
Author

reitzig commented Jun 15, 2020

Runs like this (Go 1.14.4, zap v1.15.0):

$ ./run_example.sh 
TEST:
2020-06-15T22:17:33.811+0200	DEBUG	foo/logging-example.go:16	Only in testing!
2020-06-15T22:17:33.811+0200	WARN	foo/logging-example.go:17	Always!
main.main
	/<snip>/foo/logging-example.go:17
runtime.main
	/usr/local/go/src/runtime/proc.go:203
PROD:
2020-06-15T22:17:34.387+0200	warn	foo/logging-example.go:17	Always!

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