diff --git a/cmd/run.go b/cmd/run.go index 0d37e23..1dd7dd1 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -2,11 +2,9 @@ package cmd import ( "log" - "os" - "path/filepath" "github.com/ayn2op/discordo/internal/config" - "github.com/ayn2op/discordo/internal/constants" + "github.com/ayn2op/discordo/internal/logger" "github.com/ayn2op/discordo/ui" "github.com/rivo/tview" ) @@ -26,26 +24,10 @@ func Run(token string) error { return err } - logPath, err := os.UserCacheDir() - if err != nil { + if err := logger.Load(); err != nil { return err } - logPath = filepath.Join(logPath, constants.Name) - err = os.MkdirAll(logPath, os.ModePerm) - if err != nil { - return err - } - - logPath = filepath.Join(logPath, "logs.txt") - f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY, os.ModePerm) - if err != nil { - return err - } - - log.SetOutput(f) - log.SetFlags(log.LstdFlags | log.Llongfile) - if token == "" { lf := ui.NewLoginForm(cfg) diff --git a/internal/config/config.go b/internal/config/config.go index 60b732e..6b1d399 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -91,7 +91,7 @@ func initialize() (string, error) { return filepath.Join(path, "config.yml"), nil } -// Recursively creates the configuration file if it does not exist already and writes the default configuration to it; otherwise, the existing configuration file is read, and returns the parsed configuration. +// Reads the configuration file and parses it. func Load() (*Config, error) { path, err := initialize() if err != nil { diff --git a/internal/logger/logger.go b/internal/logger/logger.go new file mode 100644 index 0000000..2874af3 --- /dev/null +++ b/internal/logger/logger.go @@ -0,0 +1,41 @@ +package logger + +import ( + "log" + "os" + "path/filepath" + + "github.com/ayn2op/discordo/internal/constants" +) + +// Recursively creates the log directory if it does not exist already and returns the path to the log file. +func initialize() (string, error) { + path, err := os.UserCacheDir() + if err != nil { + return "", err + } + + path = filepath.Join(path, constants.Name) + if err := os.MkdirAll(path, os.ModePerm); err != nil { + return "", err + } + + return filepath.Join(path, "logs.txt"), nil +} + +// Opens the log file and configures standard logger. +func Load() error { + path, err := initialize() + if err != nil { + return err + } + + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.ModePerm) + if err != nil { + return err + } + + log.SetOutput(f) + log.SetFlags(log.LstdFlags | log.Lshortfile) + return nil +}