feat(internal/peer): support dynamic log level

This commit is contained in:
Dustin Stiles 2025-03-23 10:02:19 -04:00
parent 27b6446893
commit fc046f8ee7
Signed by: duwstiles
GPG Key ID: BCD9912EC231FC87

View File

@ -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
}