log: new package

This commit is contained in:
ayn2op 2023-10-30 16:50:51 +05:30
parent fb1945b5b4
commit 6d76be4aae
3 changed files with 44 additions and 21 deletions

View file

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

View file

@ -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
internal/logger/logger.go Normal file
View file

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