From 80385bf78eb661813ccf0000e2053f961986fd65 Mon Sep 17 00:00:00 2001 From: Martin Kobetic Date: Wed, 1 Jun 2022 16:03:26 -0400 Subject: [PATCH] feat: add option for setting the encoding/format for logs (#250) --- waku.go | 10 +++++++++ waku/options.go | 1 + waku/v2/utils/logger.go | 50 +++++++++++++++++++++++------------------ 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/waku.go b/waku.go index 36676bd6..8dad165a 100644 --- a/waku.go +++ b/waku.go @@ -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.", 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{ Name: "relay", Value: true, @@ -357,6 +363,10 @@ func main() { 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) return nil }, diff --git a/waku/options.go b/waku/options.go index 2013b0fd..94b0d0d9 100644 --- a/waku/options.go +++ b/waku/options.go @@ -122,6 +122,7 @@ type Options struct { AdvertiseAddress string ShowAddresses bool LogLevel string + LogEncoding string Websocket WSOptions Relay RelayOptions diff --git a/waku/v2/utils/logger.go b/waku/v2/utils/logger.go index 2ee10c77..99b4afaf 100644 --- a/waku/v2/utils/logger.go +++ b/waku/v2/utils/logger.go @@ -1,6 +1,8 @@ package utils import ( + "fmt" + "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -22,28 +24,32 @@ func SetLogLevel(level string) error { // Logger creates a zap.Logger with some reasonable defaults func Logger() *zap.Logger { if log == nil { - cfg := zap.Config{ - Encoding: "console", - Level: atom, - OutputPaths: []string{"stderr"}, - ErrorOutputPaths: []string{"stderr"}, - EncoderConfig: zapcore.EncoderConfig{ - MessageKey: "message", - LevelKey: "level", - EncodeLevel: zapcore.CapitalLevelEncoder, - TimeKey: "time", - EncodeTime: zapcore.ISO8601TimeEncoder, - NameKey: "caller", - EncodeCaller: zapcore.ShortCallerEncoder, - }, - } - - logger, err := cfg.Build() - if err != nil { - panic("could not create logger") - } - - log = logger.Named("gowaku") + InitLogger("console") } return log } + +func InitLogger(encoding string) { + cfg := zap.Config{ + Encoding: encoding, + Level: atom, + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + EncoderConfig: zapcore.EncoderConfig{ + MessageKey: "message", + LevelKey: "level", + EncodeLevel: zapcore.CapitalLevelEncoder, + TimeKey: "time", + EncodeTime: zapcore.ISO8601TimeEncoder, + NameKey: "caller", + EncodeCaller: zapcore.ShortCallerEncoder, + }, + } + + logger, err := cfg.Build() + if err != nil { + panic(fmt.Errorf("could not create logger: %s", err.Error())) + } + + log = logger.Named("gowaku") +}