From c509106aeca09405ea0aed22e4566270c1280e6c Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Fri, 24 Jan 2025 22:44:30 +0200 Subject: [PATCH] configure logging to file --- main.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/main.go b/main.go index 9d430d6..238bca1 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,8 @@ import ( "os/signal" "strings" "syscall" + + "github.com/op/go-logging" ) var isNode bool @@ -23,6 +25,12 @@ var justNodeId bool var daemonize bool var pidPath string +type LogConfig struct { + XMLName xml.Name `xml:"log"` + Level string `xml:"level,attr"` + LogPath string `xml:",innerxml"` +} + type NodeConfig struct { XMLName xml.Name `xml:"node"` KeyStore string `xml:"keystore"` @@ -36,6 +44,42 @@ type NodeConfig struct { } `xml:"neighbor"` RPCEndpoints []string `xml:"rpc"` + + Log LogConfig `xml:"log"` +} + +func setupLogging(log LogConfig) { + var level logging.Level + switch log.Level { + case "critical": + level = logging.CRITICAL + case "error": + level = logging.ERROR + case "warning": + level = logging.WARNING + case "notice": + level = logging.NOTICE + case "info": + level = logging.INFO + case "debug": + level = logging.DEBUG + default: + level = logging.INFO + } + + logging.SetLevel(level, "") + + // if log tag has file path, then it open file in append mode, + // otherwise it will use default stdout logger + if log.LogPath != "" { + logFile, err := os.OpenFile(log.LogPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, os.FileMode(0600)) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to open log file: %v\n", err) + os.Exit(1) + } + + logging.SetBackend(logging.NewLogBackend(logFile, "", 0)) + } } func bootstrapNode() { @@ -84,6 +128,9 @@ func nodeMain() { os.Exit(1) } + // setup logging + setupLogging(config.Log) + // check presense of keystore and id in config if config.KeyStore == "" { fmt.Fprintln(os.Stderr, "no keystore path specified!") @@ -170,6 +217,9 @@ func nodeMain() { } } + // start node + node.Start() + // TODO: daemonize // register go channel to receive unix signals,