From fc046f8ee702d46dcd5a60d481085234f5da9fa6 Mon Sep 17 00:00:00 2001 From: Dustin Stiles Date: Sun, 23 Mar 2025 10:02:19 -0400 Subject: [PATCH] feat(internal/peer): support dynamic log level --- internal/peer/peer.go | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/internal/peer/peer.go b/internal/peer/peer.go index 8089638..733db9c 100644 --- a/internal/peer/peer.go +++ b/internal/peer/peer.go @@ -4,10 +4,12 @@ import ( "context" "crypto/ed25519" "encoding/base64" + "errors" "fmt" "io" "log/slog" "net" + "os" "strings" "koti.casa/numenor-labs/dsfx/internal/lib/crypto/identity" @@ -31,6 +33,7 @@ const ( // Conf holds the configuration for the dsfxctl application. type Conf struct { + LogLevel string // Directories ConfigDir string StorageDir string @@ -39,6 +42,22 @@ type Conf struct { Port string } +// SlogLevel returns the appropriate slog.Level based on the LogLevel string. +func (c Conf) SlogLevel() slog.Level { + switch c.LogLevel { + case "debug": + return slog.LevelDebug + case "info": + return slog.LevelInfo + case "warn": + return slog.LevelWarn + case "error": + return slog.LevelError + default: + return slog.LevelInfo + } +} + func loadConfigFromSystem(sys system.System) Conf { var c Conf @@ -62,9 +81,13 @@ func loadConfigFromSystem(sys system.System) Conf { c.Port = DefaultPort } + // defaults are handled by Conf.SlogLevel. + c.LogLevel = sys.GetEnv("DSFX_LOG_LEVEL") + return c } +// Peer ... type Peer struct { disk disk.Disk system system.System @@ -73,6 +96,7 @@ type Peer struct { conf Conf } +// New ... func New(disk disk.Disk, system system.System) *Peer { conf := loadConfigFromSystem(system) @@ -82,10 +106,11 @@ func New(disk disk.Disk, system system.System) *Peer { return &Peer{disk, system, config, storage, conf} } +// Run ... func (p *Peer) Run(ctx context.Context) error { opts := &slog.HandlerOptions{ AddSource: false, - Level: slog.LevelInfo, + Level: p.conf.SlogLevel(), } logger := slog.New(slog.NewTextHandler(p.system.Stdout(), opts)) @@ -168,6 +193,9 @@ func (p *Peer) loadAdmins() ([]string, error) { // hasAdminsFile ... func (p *Peer) hasAdminsFile() (bool, error) { f, err := p.config.Open("admins") + if errors.Is(err, os.ErrNotExist) { + return false, nil // Key file does not exist + } if err != nil { return false, err } @@ -235,6 +263,9 @@ func (p *Peer) loadIdentity() (ed25519.PrivateKey, error) { // hasKeyFile checks if the key file exists in the disk storage. func (p *Peer) hasKeyFile() (bool, error) { f, err := p.config.Open("ed25519.key") + if errors.Is(err, os.ErrNotExist) { + return false, nil // Key file does not exist + } if err != nil { return false, err }