Go uber zap 使用Config配置logger簡單範例。
zap除了用presets函式如NewProduction()產生Logger,也能利用Config自訂log配置,例如輸出層級、輸出格式、輸出內容及輸出位置等。
範例環境:
- Go 1.16
- zap v1.19.1
範例
下面範例建立了一個Config實例,然後呼叫Config.Build()建立Logger。
Config中各屬性配置說明如下:
Level- 型態AtomicLevel。設定log輸出層級。Encoding- 型態string。設定輸出格式,值為json或console。EncoderConfig- 型態zapcore.EncoderConfig。設定輸出格式內容的配置MessageKey- 型態string。設定輸出log訊息的key名稱。LevelKey- 型態string。設定輸出log等級的key名稱。TimeKey- 型態string。設定輸出log時間的key名稱。EncodeLevel- 型態LevelEncoder。設定log等級輸出格式。EncodeTime- 型態TimeEncoder。設定log時間輸出格式(layout)。
OutputPaths- 型態[]string。 設定log輸出位置,例如標準輸出stdout(os.Stdout)、URL及檔案路徑。ErrorOutputPaths- 型態[]string。設定內部錯誤log輸出位置,例如stderr(os.Stderr)、URL及檔案路徑。
main.go
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func main() {
cfg := zap.Config{
Level: zap.NewAtomicLevelAt(zapcore.InfoLevel),
Encoding: "console",
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "msg",
LevelKey: "level",
TimeKey: "time",
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"),
},
OutputPaths: []string{"stdout", "./logs/log"},
ErrorOutputPaths: []string{"stderr"},
}
logger, err := cfg.Build()
if err != nil {
panic(err)
}
defer logger.Sync()
f := zap.Int("amount", 100)
logger.Debug("debug message", f)
logger.Info("info message", f)
logger.Error("error message", f)
logger.Warn("warn message", f)
}
另外也可改用json或yaml的宣告式配置來設定Config。例如下面的json配置效果同上。
main.go
package main
import (
"encoding/json"
"go.uber.org/zap"
)
func main() {
rawJSON := []byte(`{
"level": "info",
"encoding": "console",
"encoderConfig": {
"messageKey": "msg",
"levelKey": "level",
"timeKey": "time",
"levelEncoder": "capital",
"timeEncoder": {
"layout": "2006-01-02 15:04:05"
}
},
"outputPaths": ["stdout", "./logs/log"],
"errorOutputPaths": ["stderr"]
}`)
var cfg zap.Config
if err := json.Unmarshal(rawJSON, &cfg); err != nil {
panic(err)
}
logger, err := cfg.Build()
if err != nil {
panic(err)
}
defer logger.Sync()
f := zap.Int("amount", 100)
logger.Debug("debug message", f)
logger.Info("info message", f)
logger.Error("error message", f)
logger.Warn("warn message", f)
}
測試
在專案根目錄執行go run main.go輸出結果如下。以console格式印出info等級以上的log,包含日期時間訊息資訊。上面Config.OutputPaths設定了檔案路徑./logs/log,所以下面內容也會輸出到專案根目錄下的/logs/log檔。
2021-09-12 13:20:53 INFO info message {"amount": 100}
2021-09-12 13:20:53 ERROR error message {"amount": 100}
2021-09-12 13:20:53 WARN warn message {"amount": 100}
把Config.Encoding改為json則輸出結果如下。
{"level":"INFO","time":"2021-09-12 13:20:53","msg":"info message","amount":100}
{"level":"ERROR","time":"2021-09-12 13:20:53","msg":"error message","amount":100}
{"level":"WARN","time":"2021-09-12 13:20:53","msg":"warn message","amount":100}
把Config.EncoderConfig.EncodeTime改為zapcore.EpochNanosTimeEncoder則輸出結果如下。
{"level":"INFO","time":1631429209989703000,"msg":"info message","amount":100}
{"level":"ERROR","time":1631429209989776000,"msg":"error message","amount":100}
{"level":"WARN","time":1631429209989810000,"msg":"warn message","amount":100}
沒有留言:
張貼留言