feat: add option for setting the encoding/format for logs (#250)

This commit is contained in:
Martin Kobetic 2022-06-01 16:03:26 -04:00 committed by Richard Ramos
parent fddffed78b
commit 80385bf78e
3 changed files with 39 additions and 22 deletions

10
waku.go
View File

@ -135,6 +135,12 @@ func main() {
Usage: "Define the logging level, supported strings are: DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL, and their lower-case forms.", Usage: "Define the logging level, supported strings are: DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL, and their lower-case forms.",
Destination: &options.LogLevel, Destination: &options.LogLevel,
}, },
&cli.StringFlag{
Name: "log-encoding",
Value: "console",
Usage: "Define the encoding used for the logs: console, json",
Destination: &options.LogEncoding,
},
&cli.BoolFlag{ &cli.BoolFlag{
Name: "relay", Name: "relay",
Value: true, Value: true,
@ -357,6 +363,10 @@ func main() {
return err return err
} }
// Set encoding for logs (console, json, ...)
// Note that libp2p reads the encoding from GOLOG_LOG_FMT env var.
utils.InitLogger(options.LogEncoding)
waku.Execute(options) waku.Execute(options)
return nil return nil
}, },

View File

@ -122,6 +122,7 @@ type Options struct {
AdvertiseAddress string AdvertiseAddress string
ShowAddresses bool ShowAddresses bool
LogLevel string LogLevel string
LogEncoding string
Websocket WSOptions Websocket WSOptions
Relay RelayOptions Relay RelayOptions

View File

@ -1,6 +1,8 @@
package utils package utils
import ( import (
"fmt"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
) )
@ -22,8 +24,14 @@ func SetLogLevel(level string) error {
// Logger creates a zap.Logger with some reasonable defaults // Logger creates a zap.Logger with some reasonable defaults
func Logger() *zap.Logger { func Logger() *zap.Logger {
if log == nil { if log == nil {
InitLogger("console")
}
return log
}
func InitLogger(encoding string) {
cfg := zap.Config{ cfg := zap.Config{
Encoding: "console", Encoding: encoding,
Level: atom, Level: atom,
OutputPaths: []string{"stderr"}, OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"}, ErrorOutputPaths: []string{"stderr"},
@ -40,10 +48,8 @@ func Logger() *zap.Logger {
logger, err := cfg.Build() logger, err := cfg.Build()
if err != nil { if err != nil {
panic("could not create logger") panic(fmt.Errorf("could not create logger: %s", err.Error()))
} }
log = logger.Named("gowaku") log = logger.Named("gowaku")
}
return log
} }