From 2a272a79760682b2629a80c311e552eac4645f8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=83=9E=E3=83=AA=E3=82=A6=E3=82=B9?= Date: Sat, 31 Dec 2022 13:00:32 -0500 Subject: [PATCH] Implemented log file --- cmd/root.go | 39 +++++++++++++++++++++++++++++++++++---- config/config.go | 8 +++++++- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index e95c290..dafb3f4 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,6 +1,10 @@ package cmd import ( + "net/url" + "os" + "runtime" + tea "github.com/charmbracelet/bubbletea" "github.com/mrusme/gobbs/config" "github.com/mrusme/gobbs/system" @@ -29,6 +33,34 @@ func init() { ) } +func loadLogger(filename string, debug bool) (*zap.Logger, error) { + if runtime.GOOS == "windows" { + zap.RegisterSink("winfile", func(u *url.URL) (zap.Sink, error) { + return os.OpenFile(u.Path[1:], os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) + }) + } + + var cfg zap.Config + if debug { + cfg = zap.NewDevelopmentConfig() + } else { + cfg = zap.NewProductionConfig() + } + + if runtime.GOOS == "windows" { + cfg.OutputPaths = []string{ + "stdout", + "winfile:///" + filename, + } + } else { + cfg.OutputPaths = []string{ + filename, + } + } + + return cfg.Build() +} + func load() { var err error var logger *zap.Logger @@ -38,10 +70,9 @@ func load() { panic(err) } - if CFG.Debug == "true" { - logger, _ = zap.NewDevelopment() - } else { - logger, _ = zap.NewProduction() + logger, err = loadLogger(CFG.Log, CFG.Debug) + if err != nil { + panic(err) } defer logger.Sync() LOG = logger.Sugar() diff --git a/config/config.go b/config/config.go index d2def1a..78294f7 100644 --- a/config/config.go +++ b/config/config.go @@ -25,7 +25,8 @@ type SystemConfig struct { } type Config struct { - Debug string + Debug bool + Log string Systems []SystemConfig } @@ -39,8 +40,13 @@ func Load() (Config, error) { if err != nil { return Config{}, err } + cacheDir, err := os.UserCacheDir() + if err != nil { + return Config{}, err + } viper.SetDefault("Debug", "true") + viper.SetDefault("Log", path.Join(cacheDir, "gobbs.log")) viper.SetConfigName("gobbs") viper.SetConfigType("toml")