Bläddra i källkod

log: new package

ayn2op 2 år sedan
förälder
incheckning
6d76be4aae
3 ändrade filer med 44 tillägg och 21 borttagningar
  1. 2 20
      cmd/run.go
  2. 1 1
      internal/config/config.go
  3. 41 0
      internal/logger/logger.go

+ 2 - 20
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 {
-		return err
-	}
-
-	logPath = filepath.Join(logPath, constants.Name)
-	err = os.MkdirAll(logPath, os.ModePerm)
-	if err != nil {
+	if err := logger.Load(); 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)
 

+ 1 - 1
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 {

+ 41 - 0
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
+}